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
6,007
10,383
Log4Net configuring log level
How do I make Log4net only log Info level logs? Is that even possible? Can you only set a threshold? This is what I have, and it logs Info and above as I would expect. Is there anything i can do to make it only log info?
Within the definition of the appender, I believe you can do something like this:...
Log4Net configuring log level How do I make Log4net only log Info level logs? Is that even possible? Can you only set a threshold? This is what I have, and it logs Info and above as I would expect. Is there anything i can do to make it only log info?
TITLE: Log4Net configuring log level QUESTION: How do I make Log4net only log Info level logs? Is that even possible? Can you only set a threshold? This is what I have, and it logs Info and above as I would expect. Is there anything i can do to make it only log info? ANSWER: Within the definition of the appender, I believe you can do something like this:...
[ "log4net" ]
67
100
116,544
5
0
2008-08-08T14:43:11.877000
2008-08-13T21:18:38.423000
6,009
6,017
How do you deal with configuration files in source control?
Let's say you have a typical web app and with a file configuration.whatever. Every developer working on the project will have one version for their dev boxes, there will be a dev, prod and stage versions. How do you deal with this in source control? Not check in this file at all, check it with different names or do something fancy altogether?
What I've done in the past is to have a default config file which is checked in to source control. Then, each developer has their own override config file which is excluded from source control. The app first loads the default, and then if the override file is present, loads that and uses any settings from the override in preference to the default file. In general, the smaller the override file the better, but it can always contain more settings for a developer with a very non-standard environment.
How do you deal with configuration files in source control? Let's say you have a typical web app and with a file configuration.whatever. Every developer working on the project will have one version for their dev boxes, there will be a dev, prod and stage versions. How do you deal with this in source control? Not check in this file at all, check it with different names or do something fancy altogether?
TITLE: How do you deal with configuration files in source control? QUESTION: Let's say you have a typical web app and with a file configuration.whatever. Every developer working on the project will have one version for their dev boxes, there will be a dev, prod and stage versions. How do you deal with this in source control? Not check in this file at all, check it with different names or do something fancy altogether? ANSWER: What I've done in the past is to have a default config file which is checked in to source control. Then, each developer has their own override config file which is excluded from source control. The app first loads the default, and then if the override file is present, loads that and uses any settings from the override in preference to the default file. In general, the smaller the override file the better, but it can always contain more settings for a developer with a very non-standard environment.
[ "svn", "git", "version-control", "cvs" ]
103
73
22,810
19
0
2008-08-08T14:44:25.570000
2008-08-08T14:50:00.287000
6,076
7,740
Default Form Button in FireFox
I am building a server control that will search our db and return results. The server control is contains an ASP:Panel. I have set the default button on the panel equal to my button id and have set the form default button equal to my button id. On the Panel: MyPanel.DefaultButton = SearchButton.ID On the Control: Me.Page.Form.DefaultButton = SearchButton.UniqueID Works fine in IE & Safari I can type a search term and hit the enter key and it searches fine. If I do it in Firefox I get an alert box saying "Object reference not set to an instance of an a object. Anyone run across this before?
Ends up this resolved my issue: SearchButton.UseSubmitBehavior = False
Default Form Button in FireFox I am building a server control that will search our db and return results. The server control is contains an ASP:Panel. I have set the default button on the panel equal to my button id and have set the form default button equal to my button id. On the Panel: MyPanel.DefaultButton = SearchButton.ID On the Control: Me.Page.Form.DefaultButton = SearchButton.UniqueID Works fine in IE & Safari I can type a search term and hit the enter key and it searches fine. If I do it in Firefox I get an alert box saying "Object reference not set to an instance of an a object. Anyone run across this before?
TITLE: Default Form Button in FireFox QUESTION: I am building a server control that will search our db and return results. The server control is contains an ASP:Panel. I have set the default button on the panel equal to my button id and have set the form default button equal to my button id. On the Panel: MyPanel.DefaultButton = SearchButton.ID On the Control: Me.Page.Form.DefaultButton = SearchButton.UniqueID Works fine in IE & Safari I can type a search term and hit the enter key and it searches fine. If I do it in Firefox I get an alert box saying "Object reference not set to an instance of an a object. Anyone run across this before? ANSWER: Ends up this resolved my issue: SearchButton.UseSubmitBehavior = False
[ "asp.net", "vb.net" ]
7
2
1,686
3
0
2008-08-08T15:32:15.787000
2008-08-11T12:51:23.970000
6,080
6,088
What to use for login ID?
We are in the early design stages of a major rewrite of our product. Right now our customers are mostly businesses. We manage accounts. User names for an account are each on their own namespace but it means that we can't move assets between servers. We want to move to a single namespace. But that brings the problem of unique user names. So what's the best idea? Email address (w/verification)? Unique alpha-numeric string ("johnsmith9234")? Should we look at OpenID?
EMAIL ADDRESS Rational Users don't change emails very often Removes the step of asking for username and email address, which you'll need anyway Users don't often forget their email address (see number one) Email will be unique unless the user already registered for the site, in which case forward them to a forgot your password screen Almost everyone is using email as the primary login for access to a website, this means the rate of adoption shouldn't be affected by the fact that you're asking for an email address Update After registration, be sure to ask the user to create some kind of username, don't litter a public site with their email address! Also, another benefit of using an email address as a login: you won't need any other information (like password / password confirm), just send them a temp password through the mail, or forgo passwords altogether and send them a one-use URL to their email address every time they'd like to login (see: mugshot.org )
What to use for login ID? We are in the early design stages of a major rewrite of our product. Right now our customers are mostly businesses. We manage accounts. User names for an account are each on their own namespace but it means that we can't move assets between servers. We want to move to a single namespace. But that brings the problem of unique user names. So what's the best idea? Email address (w/verification)? Unique alpha-numeric string ("johnsmith9234")? Should we look at OpenID?
TITLE: What to use for login ID? QUESTION: We are in the early design stages of a major rewrite of our product. Right now our customers are mostly businesses. We manage accounts. User names for an account are each on their own namespace but it means that we can't move assets between servers. We want to move to a single namespace. But that brings the problem of unique user names. So what's the best idea? Email address (w/verification)? Unique alpha-numeric string ("johnsmith9234")? Should we look at OpenID? ANSWER: EMAIL ADDRESS Rational Users don't change emails very often Removes the step of asking for username and email address, which you'll need anyway Users don't often forget their email address (see number one) Email will be unique unless the user already registered for the site, in which case forward them to a forgot your password screen Almost everyone is using email as the primary login for access to a website, this means the rate of adoption shouldn't be affected by the fact that you're asking for an email address Update After registration, be sure to ask the user to create some kind of username, don't litter a public site with their email address! Also, another benefit of using an email address as a login: you won't need any other information (like password / password confirm), just send them a temp password through the mail, or forgo passwords altogether and send them a one-use URL to their email address every time they'd like to login (see: mugshot.org )
[ "authentication", "web-applications", "account" ]
17
42
7,246
10
0
2008-08-08T15:40:58.903000
2008-08-08T15:46:12.187000
6,085
6,514
Gathering OS and tool version numbers for build archive purposes
Our automated build machine needs to archive the version numbers of the OS plus various tools used during each build. (In case we ever need to replicate exactly the same build later on, perhaps when the machine is long dead.) I see the command "msinfo32.exe" can be used to dump a whole load of system version information, which we might as well archive. Does anyone know of a way to easily archive the version numbers of the Visual Studio tools? What mechanisms do other developers use to gather this kind of information for archive purposes? Extra information for Fabio Gomes. I agree with you that in 5 years time it'll probably be impossible to recreate the exact OS and tool configuration (down to the nearest security update). Unfortunately this really comes from a contractual requirement. As part of our deliverable to a customer we must provide a copy of all source code and clear instructions on exactly how to replicate the build. It's probably impossible for us to meet this requirement perfectly. So - I'll just mark your answer as correct (I agree with you that it's practically impossible), and get on with playing with the rest of stack overflow.:) PS. It would be really great if stack overflow supported replies to answers instead of having to edit the original question.. But I see it has already been denied.
Sorry, but what could lead for a need to replicated the exact same build in the future? In my experience, either you keep your product installers safe or start a new build from scratch. Also IMO the only way to replicated the exact same build in the future is to run your build machine on a Virtual Machine and keep the VM backup around. I think that most softwares you will need to replicate the exact same build in the future will not be available anymore, so you will need to keep a copy of every software version you install in this machine. Could you be more specific about the problem you are trying to solve?
Gathering OS and tool version numbers for build archive purposes Our automated build machine needs to archive the version numbers of the OS plus various tools used during each build. (In case we ever need to replicate exactly the same build later on, perhaps when the machine is long dead.) I see the command "msinfo32.exe" can be used to dump a whole load of system version information, which we might as well archive. Does anyone know of a way to easily archive the version numbers of the Visual Studio tools? What mechanisms do other developers use to gather this kind of information for archive purposes? Extra information for Fabio Gomes. I agree with you that in 5 years time it'll probably be impossible to recreate the exact OS and tool configuration (down to the nearest security update). Unfortunately this really comes from a contractual requirement. As part of our deliverable to a customer we must provide a copy of all source code and clear instructions on exactly how to replicate the build. It's probably impossible for us to meet this requirement perfectly. So - I'll just mark your answer as correct (I agree with you that it's practically impossible), and get on with playing with the rest of stack overflow.:) PS. It would be really great if stack overflow supported replies to answers instead of having to edit the original question.. But I see it has already been denied.
TITLE: Gathering OS and tool version numbers for build archive purposes QUESTION: Our automated build machine needs to archive the version numbers of the OS plus various tools used during each build. (In case we ever need to replicate exactly the same build later on, perhaps when the machine is long dead.) I see the command "msinfo32.exe" can be used to dump a whole load of system version information, which we might as well archive. Does anyone know of a way to easily archive the version numbers of the Visual Studio tools? What mechanisms do other developers use to gather this kind of information for archive purposes? Extra information for Fabio Gomes. I agree with you that in 5 years time it'll probably be impossible to recreate the exact OS and tool configuration (down to the nearest security update). Unfortunately this really comes from a contractual requirement. As part of our deliverable to a customer we must provide a copy of all source code and clear instructions on exactly how to replicate the build. It's probably impossible for us to meet this requirement perfectly. So - I'll just mark your answer as correct (I agree with you that it's practically impossible), and get on with playing with the rest of stack overflow.:) PS. It would be really great if stack overflow supported replies to answers instead of having to edit the original question.. But I see it has already been denied. ANSWER: Sorry, but what could lead for a need to replicated the exact same build in the future? In my experience, either you keep your product installers safe or start a new build from scratch. Also IMO the only way to replicated the exact same build in the future is to run your build machine on a Virtual Machine and keep the VM backup around. I think that most softwares you will need to replicate the exact same build in the future will not be available anymore, so you will need to keep a copy of every software version you install in this machine. Could you be more specific about the problem you are trying to solve?
[ "build-automation", "versions", "archive" ]
6
0
431
3
0
2008-08-08T15:44:25.823000
2008-08-09T01:28:45.113000
6,110
6,120
Normalizing a Table with Low Integrity
I've been handed a table with about 18000 rows. Each record describes the location of one customer. The issue is, that when the person created the table, they did not add a field for "Company Name", only "Location Name," and one company can have many locations. For example, here are some records that describe the same customer: Location Table ID Location_Name 1 TownShop#1 2 Town Shop - Loc 2 3 The Town Shop 4 TTS - Someplace 5 Town Shop,the 3 6 Toen Shop4 My goal is to make it look like: Location Table ID Company_ID Location_Name 1 1 Town Shop#1 2 1 Town Shop - Loc 2 3 1 The Town Shop 4 1 TTS - Someplace 5 1 Town Shop,the 3 6 1 Toen Shop4 Company Table Company_ID Company_Name 1 The Town Shop There is no "Company" table, I will have to generate the Company Name list from the most descriptive or best Location Name that represents the multiple locations. Currently I am thinking I need to generate a list of Location Names that are similar, and then and go through that list by hand. Any suggestions on how I can approach this is appreciated. @Neall, Thank you for your statement, but unfortunately, each location name is distinct, there are no duplicate location names, only similar. So in the results from your statement "repcount" is 1 in each row. @yukondude, Your step 4 is the heart of my question.
Please update the question, do you have a list of CompanyNames available to you? I ask because you maybe able to use Levenshtein algo to find a relationship between your list of CompanyNames and LocationNames. Update There is not a list of Company Names, I will have to generate the company name from the most descriptive or best Location Name that represents the multiple locations. Okay... try this: Build a list of candidate CompanyNames by finding LocationNames made up of mostly or all alphabetic characters. You can use regular expressions for this. Store this list in a separate table. Sort that list alphabetically and (manually) determine which entries should be CompanyNames. Compare each CompanyName to each LocationName and come up with a match score (use Levenshtein or some other string matching algo). Store the result in a separate table. Set a threshold score such that any MatchScore < Threshold will not be considered a match for a given CompanyName. Manually vet through the LocationNames by CompanyName | LocationName | MatchScore, and figure out which ones actually match. Ordering by MatchScore should make the process less painful. The whole purpose of the above actions is to automate parts and limit the scope of your problem. It's far from perfect, but will hopefully save you the trouble of going through 18K records by hand.
Normalizing a Table with Low Integrity I've been handed a table with about 18000 rows. Each record describes the location of one customer. The issue is, that when the person created the table, they did not add a field for "Company Name", only "Location Name," and one company can have many locations. For example, here are some records that describe the same customer: Location Table ID Location_Name 1 TownShop#1 2 Town Shop - Loc 2 3 The Town Shop 4 TTS - Someplace 5 Town Shop,the 3 6 Toen Shop4 My goal is to make it look like: Location Table ID Company_ID Location_Name 1 1 Town Shop#1 2 1 Town Shop - Loc 2 3 1 The Town Shop 4 1 TTS - Someplace 5 1 Town Shop,the 3 6 1 Toen Shop4 Company Table Company_ID Company_Name 1 The Town Shop There is no "Company" table, I will have to generate the Company Name list from the most descriptive or best Location Name that represents the multiple locations. Currently I am thinking I need to generate a list of Location Names that are similar, and then and go through that list by hand. Any suggestions on how I can approach this is appreciated. @Neall, Thank you for your statement, but unfortunately, each location name is distinct, there are no duplicate location names, only similar. So in the results from your statement "repcount" is 1 in each row. @yukondude, Your step 4 is the heart of my question.
TITLE: Normalizing a Table with Low Integrity QUESTION: I've been handed a table with about 18000 rows. Each record describes the location of one customer. The issue is, that when the person created the table, they did not add a field for "Company Name", only "Location Name," and one company can have many locations. For example, here are some records that describe the same customer: Location Table ID Location_Name 1 TownShop#1 2 Town Shop - Loc 2 3 The Town Shop 4 TTS - Someplace 5 Town Shop,the 3 6 Toen Shop4 My goal is to make it look like: Location Table ID Company_ID Location_Name 1 1 Town Shop#1 2 1 Town Shop - Loc 2 3 1 The Town Shop 4 1 TTS - Someplace 5 1 Town Shop,the 3 6 1 Toen Shop4 Company Table Company_ID Company_Name 1 The Town Shop There is no "Company" table, I will have to generate the Company Name list from the most descriptive or best Location Name that represents the multiple locations. Currently I am thinking I need to generate a list of Location Names that are similar, and then and go through that list by hand. Any suggestions on how I can approach this is appreciated. @Neall, Thank you for your statement, but unfortunately, each location name is distinct, there are no duplicate location names, only similar. So in the results from your statement "repcount" is 1 in each row. @yukondude, Your step 4 is the heart of my question. ANSWER: Please update the question, do you have a list of CompanyNames available to you? I ask because you maybe able to use Levenshtein algo to find a relationship between your list of CompanyNames and LocationNames. Update There is not a list of Company Names, I will have to generate the company name from the most descriptive or best Location Name that represents the multiple locations. Okay... try this: Build a list of candidate CompanyNames by finding LocationNames made up of mostly or all alphabetic characters. You can use regular expressions for this. Store this list in a separate table. Sort that list alphabetically and (manually) determine which entries should be CompanyNames. Compare each CompanyName to each LocationName and come up with a match score (use Levenshtein or some other string matching algo). Store the result in a separate table. Set a threshold score such that any MatchScore < Threshold will not be considered a match for a given CompanyName. Manually vet through the LocationNames by CompanyName | LocationName | MatchScore, and figure out which ones actually match. Ordering by MatchScore should make the process less painful. The whole purpose of the above actions is to automate parts and limit the scope of your problem. It's far from perfect, but will hopefully save you the trouble of going through 18K records by hand.
[ "database" ]
6
1
866
5
0
2008-08-08T16:19:20.607000
2008-08-08T16:41:29.623000
6,113
6,117
What is the best way to store connection string in .NET DLLs?
The application my team is currently developing has a DLL that is used to perform all database access. The application can not use a trusted connection because the database is behind a firewall and the domain server is not. So it appears that the connection string needs to have a DB username and password. The DLL currently has the database connection string hard coded, but I don't want to do this when we launch as the assembly can be disassembled and the username and password would be right there in the open. One of the requirements is that the password needs to be changed once every few months, so we would need to roll that out to our internal user base. Is there a way to store the password encrypted in such a way we can easily distribute to the entire user base without storing it in the assembly? UPDATE: Thanks to everyone who's answered. I'll try to answer some of the questions back to me... The data DLL is used by both ASP.NET WebForms and VB.NET WinForms. I understand that Applications can have their own config files, but I haven't seen anything on config files for DLLs. Unfortunately, I can't get to the Jon Galloway post at work so I can't judge if that will work. From a development standpoint, we don't want to use web services inhouse, but may be providing them to third parties sometime next year. I don't think impersonation will work because we can't authenticate the user through the firewall. As a user (or former user) can be an attacker, we're keeping it from everyone!
I'm not certain, but I believe you can put it in a config file and encrypt the config file. Update: See Jon Galloway's post here.
What is the best way to store connection string in .NET DLLs? The application my team is currently developing has a DLL that is used to perform all database access. The application can not use a trusted connection because the database is behind a firewall and the domain server is not. So it appears that the connection string needs to have a DB username and password. The DLL currently has the database connection string hard coded, but I don't want to do this when we launch as the assembly can be disassembled and the username and password would be right there in the open. One of the requirements is that the password needs to be changed once every few months, so we would need to roll that out to our internal user base. Is there a way to store the password encrypted in such a way we can easily distribute to the entire user base without storing it in the assembly? UPDATE: Thanks to everyone who's answered. I'll try to answer some of the questions back to me... The data DLL is used by both ASP.NET WebForms and VB.NET WinForms. I understand that Applications can have their own config files, but I haven't seen anything on config files for DLLs. Unfortunately, I can't get to the Jon Galloway post at work so I can't judge if that will work. From a development standpoint, we don't want to use web services inhouse, but may be providing them to third parties sometime next year. I don't think impersonation will work because we can't authenticate the user through the firewall. As a user (or former user) can be an attacker, we're keeping it from everyone!
TITLE: What is the best way to store connection string in .NET DLLs? QUESTION: The application my team is currently developing has a DLL that is used to perform all database access. The application can not use a trusted connection because the database is behind a firewall and the domain server is not. So it appears that the connection string needs to have a DB username and password. The DLL currently has the database connection string hard coded, but I don't want to do this when we launch as the assembly can be disassembled and the username and password would be right there in the open. One of the requirements is that the password needs to be changed once every few months, so we would need to roll that out to our internal user base. Is there a way to store the password encrypted in such a way we can easily distribute to the entire user base without storing it in the assembly? UPDATE: Thanks to everyone who's answered. I'll try to answer some of the questions back to me... The data DLL is used by both ASP.NET WebForms and VB.NET WinForms. I understand that Applications can have their own config files, but I haven't seen anything on config files for DLLs. Unfortunately, I can't get to the Jon Galloway post at work so I can't judge if that will work. From a development standpoint, we don't want to use web services inhouse, but may be providing them to third parties sometime next year. I don't think impersonation will work because we can't authenticate the user through the firewall. As a user (or former user) can be an attacker, we're keeping it from everyone! ANSWER: I'm not certain, but I believe you can put it in a config file and encrypt the config file. Update: See Jon Galloway's post here.
[ ".net", "sql-server", "connection-string" ]
17
10
15,659
8
0
2008-08-08T16:32:30.440000
2008-08-08T16:38:34.513000
6,126
6,140
How do you handle huge if-conditions?
It's something that's bugged me in every language I've used, I have an if statement but the conditional part has so many checks that I have to split it over multiple lines, use a nested if statement or just accept that it's ugly and move on with my life. Are there any other methods that you've found that might be of use to me and anybody else that's hit the same problem? Example, all on one line: if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true) { Example, multi-line: if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true) { Example-nested: if (var1 = true && var2 = true && var2 = true && var3 = true) { if (var4 = true && var5 = true && var6 = true) {
Separate the condition in several booleans and then use a master boolean as the condition. bool isOpaque = object.Alpha == 1.0f; bool isDrawable = object.CanDraw && object.Layer == currentLayer; bool isHidden = hideList.Find(object); bool isVisible = isOpaque && isDrawable &&! isHidden; if(isVisible) { //... } Better yet: public bool IsVisible { get { bool isOpaque = object.Alpha == 1.0f; bool isDrawable = object.CanDraw && object.Layer == currentLayer; bool isHidden = hideList.Find(object); return isOpaque && isDrawable &&! isHidden; } } void Draw() { if(IsVisible) { //... } } Make sure you give your variables name that actualy indicate intention rather than function. This will greatly help the developer maintaining your code... it could be YOU!
How do you handle huge if-conditions? It's something that's bugged me in every language I've used, I have an if statement but the conditional part has so many checks that I have to split it over multiple lines, use a nested if statement or just accept that it's ugly and move on with my life. Are there any other methods that you've found that might be of use to me and anybody else that's hit the same problem? Example, all on one line: if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true) { Example, multi-line: if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true) { Example-nested: if (var1 = true && var2 = true && var2 = true && var3 = true) { if (var4 = true && var5 = true && var6 = true) {
TITLE: How do you handle huge if-conditions? QUESTION: It's something that's bugged me in every language I've used, I have an if statement but the conditional part has so many checks that I have to split it over multiple lines, use a nested if statement or just accept that it's ugly and move on with my life. Are there any other methods that you've found that might be of use to me and anybody else that's hit the same problem? Example, all on one line: if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true) { Example, multi-line: if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true) { Example-nested: if (var1 = true && var2 = true && var2 = true && var3 = true) { if (var4 = true && var5 = true && var6 = true) { ANSWER: Separate the condition in several booleans and then use a master boolean as the condition. bool isOpaque = object.Alpha == 1.0f; bool isDrawable = object.CanDraw && object.Layer == currentLayer; bool isHidden = hideList.Find(object); bool isVisible = isOpaque && isDrawable &&! isHidden; if(isVisible) { //... } Better yet: public bool IsVisible { get { bool isOpaque = object.Alpha == 1.0f; bool isDrawable = object.CanDraw && object.Layer == currentLayer; bool isHidden = hideList.Find(object); return isOpaque && isDrawable &&! isHidden; } } void Draw() { if(IsVisible) { //... } } Make sure you give your variables name that actualy indicate intention rather than function. This will greatly help the developer maintaining your code... it could be YOU!
[ "language-agnostic", "if-statement" ]
29
62
7,038
21
0
2008-08-08T16:45:58.540000
2008-08-08T16:54:30.143000
6,130
6,144
Repair SVN Checksum
I'm using subclipse in Flex Builder 3, and recently received this error when trying to commit: svn: Checksum mismatch for '/Users/redacted/Documents/Flex Builder 3/path/to/my/file.mxml'; expected: 'f8cb275de72776657406154dd3c10348', actual: 'null' I worked around it by: Committing all the other changed files, omitting the troublesome one. Copying the contents of the trouble file to a TextMate window Deleting my project in FlexBuilder/Eclipse Checking my project out fresh from SVN Copying the text of the trouble file back in from the TextMate Window Committing the changes. It worked, but I can't help but think there's a better way. What's actaully happening to cause the svn:checksum error, and what's the best fix. Maybe more important -- is this a symptom of a greater problem?
The file in the.svn directory that keeps track of what you have checked out, when, what revision, and from where, has gotten corrupted somehow, for that particular file. This is no more dangerous or critical than the normal odd file problem, and can be because of various problems, like a subversion program dying mid-change, power-disruption, etc. Unless it happens more I wouldn't make much out of it. It can be fixed by doing what you did, make a copy of your work-files, check out a fresh copy, and add the modified files back in. Note that this might cause problems if you have a busy project where you would normally have to merge in changes. For instance, you and a collegue both check out a fresh copy, and start working on the same file. At some point, your collegue checks in his modifications. When you attempt to do the same, you get the checksum problem you have. If you now make copies of your changed files, do a fresh checkout, then subversion will lose track of how your changes should be merged back in. If you didn't get the problem in this case, when you got around to checkin in your modifications, you would need to update your working copy first, and possibly handle a conflict with your file. However, if you do a fresh checkout, complete with your collegues changes, it now looks like you removed his changes and substituted with your own. No conflicts, and no indications from subversion that something is amiss.
Repair SVN Checksum I'm using subclipse in Flex Builder 3, and recently received this error when trying to commit: svn: Checksum mismatch for '/Users/redacted/Documents/Flex Builder 3/path/to/my/file.mxml'; expected: 'f8cb275de72776657406154dd3c10348', actual: 'null' I worked around it by: Committing all the other changed files, omitting the troublesome one. Copying the contents of the trouble file to a TextMate window Deleting my project in FlexBuilder/Eclipse Checking my project out fresh from SVN Copying the text of the trouble file back in from the TextMate Window Committing the changes. It worked, but I can't help but think there's a better way. What's actaully happening to cause the svn:checksum error, and what's the best fix. Maybe more important -- is this a symptom of a greater problem?
TITLE: Repair SVN Checksum QUESTION: I'm using subclipse in Flex Builder 3, and recently received this error when trying to commit: svn: Checksum mismatch for '/Users/redacted/Documents/Flex Builder 3/path/to/my/file.mxml'; expected: 'f8cb275de72776657406154dd3c10348', actual: 'null' I worked around it by: Committing all the other changed files, omitting the troublesome one. Copying the contents of the trouble file to a TextMate window Deleting my project in FlexBuilder/Eclipse Checking my project out fresh from SVN Copying the text of the trouble file back in from the TextMate Window Committing the changes. It worked, but I can't help but think there's a better way. What's actaully happening to cause the svn:checksum error, and what's the best fix. Maybe more important -- is this a symptom of a greater problem? ANSWER: The file in the.svn directory that keeps track of what you have checked out, when, what revision, and from where, has gotten corrupted somehow, for that particular file. This is no more dangerous or critical than the normal odd file problem, and can be because of various problems, like a subversion program dying mid-change, power-disruption, etc. Unless it happens more I wouldn't make much out of it. It can be fixed by doing what you did, make a copy of your work-files, check out a fresh copy, and add the modified files back in. Note that this might cause problems if you have a busy project where you would normally have to merge in changes. For instance, you and a collegue both check out a fresh copy, and start working on the same file. At some point, your collegue checks in his modifications. When you attempt to do the same, you get the checksum problem you have. If you now make copies of your changed files, do a fresh checkout, then subversion will lose track of how your changes should be merged back in. If you didn't get the problem in this case, when you got around to checkin in your modifications, you would need to update your working copy first, and possibly handle a conflict with your file. However, if you do a fresh checkout, complete with your collegues changes, it now looks like you removed his changes and substituted with your own. No conflicts, and no indications from subversion that something is amiss.
[ "svn", "subclipse" ]
68
38
84,281
21
0
2008-08-08T16:49:17.377000
2008-08-08T16:56:13.027000
6,151
6,200
How do I edit work items in the Visual Studio 2008 xml editor?
I'm trying to customize some TFS work items via the VS2008 xml editor, but every time I open a work item xml file it jumps to the graphical designer. All that gives me is a "View XML" button that doesn't let you edit the xml directly.
I don't have TFS but I know in regular VS there is an Open With... option in most items' contextual menu that even let you change the default editor. Very useful when you are tired of the Designer opening instead of the Code file on Windows forms.
How do I edit work items in the Visual Studio 2008 xml editor? I'm trying to customize some TFS work items via the VS2008 xml editor, but every time I open a work item xml file it jumps to the graphical designer. All that gives me is a "View XML" button that doesn't let you edit the xml directly.
TITLE: How do I edit work items in the Visual Studio 2008 xml editor? QUESTION: I'm trying to customize some TFS work items via the VS2008 xml editor, but every time I open a work item xml file it jumps to the graphical designer. All that gives me is a "View XML" button that doesn't let you edit the xml directly. ANSWER: I don't have TFS but I know in regular VS there is an Open With... option in most items' contextual menu that even let you change the default editor. Very useful when you are tired of the Designer opening instead of the Code file on Windows forms.
[ "windows", "visual-studio", "tfs" ]
7
1
1,182
4
0
2008-08-08T17:04:25.973000
2008-08-08T17:52:07.783000
6,173
6,183
Regular expression for parsing links from a webpage?
I'm looking for a.NET regular expression extract all the URLs from a webpage but haven't found one to be comprehensive enough to cover all the different ways you can specify a link. And a side question: Is there one regex to rule them all? Or am I better off using a series of less complicated regular expressions and just using mutliple passes against the raw HTML? (Speed vs. Maintainability)
((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+) I took this from regexlib.com [editor's note: the {1} has no real function in this regex; see this post ]
Regular expression for parsing links from a webpage? I'm looking for a.NET regular expression extract all the URLs from a webpage but haven't found one to be comprehensive enough to cover all the different ways you can specify a link. And a side question: Is there one regex to rule them all? Or am I better off using a series of less complicated regular expressions and just using mutliple passes against the raw HTML? (Speed vs. Maintainability)
TITLE: Regular expression for parsing links from a webpage? QUESTION: I'm looking for a.NET regular expression extract all the URLs from a webpage but haven't found one to be comprehensive enough to cover all the different ways you can specify a link. And a side question: Is there one regex to rule them all? Or am I better off using a series of less complicated regular expressions and just using mutliple passes against the raw HTML? (Speed vs. Maintainability) ANSWER: ((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+) I took this from regexlib.com [editor's note: the {1} has no real function in this regex; see this post ]
[ ".net", "html", "regex" ]
17
12
12,361
9
0
2008-08-08T17:24:19.100000
2008-08-08T17:32:12.253000
6,184
6,211
How do I make event callbacks into my win forms thread safe?
When you subscribe to an event on an object from within a form, you are essentially handing over control of your callback method to the event source. You have no idea whether that event source will choose to trigger the event on a different thread. The problem is that when the callback is invoked, you cannot assume that you can make update controls on your form because sometimes those controls will throw an exception if the event callback was called on a thread different than the thread the form was run on.
To simplify Simon's code a bit, you could use the built in generic Action delegate. It saves peppering your code with a bunch of delegate types you don't really need. Also, in.NET 3.5 they added a params parameter to the Invoke method so you don't have to define a temporary array. void SomethingHappened(object sender, EventArgs ea) { if (InvokeRequired) { Invoke(new Action (SomethingHappened), sender, ea); return; } textBox1.Text = "Something happened"; }
How do I make event callbacks into my win forms thread safe? When you subscribe to an event on an object from within a form, you are essentially handing over control of your callback method to the event source. You have no idea whether that event source will choose to trigger the event on a different thread. The problem is that when the callback is invoked, you cannot assume that you can make update controls on your form because sometimes those controls will throw an exception if the event callback was called on a thread different than the thread the form was run on.
TITLE: How do I make event callbacks into my win forms thread safe? QUESTION: When you subscribe to an event on an object from within a form, you are essentially handing over control of your callback method to the event source. You have no idea whether that event source will choose to trigger the event on a different thread. The problem is that when the callback is invoked, you cannot assume that you can make update controls on your form because sometimes those controls will throw an exception if the event callback was called on a thread different than the thread the form was run on. ANSWER: To simplify Simon's code a bit, you could use the built in generic Action delegate. It saves peppering your code with a bunch of delegate types you don't really need. Also, in.NET 3.5 they added a params parameter to the Invoke method so you don't have to define a temporary array. void SomethingHappened(object sender, EventArgs ea) { if (InvokeRequired) { Invoke(new Action (SomethingHappened), sender, ea); return; } textBox1.Text = "Something happened"; }
[ "c#", ".net", "winforms", "multithreading", "events" ]
39
35
33,935
6
0
2008-08-08T17:32:41.783000
2008-08-08T18:05:24.493000
6,207
281,143
Experiences of the Smart Client Software Factory
Has anyone had any experience in building a 'real world' application with the Smart Client Software Factory, from Microsofts Patterns and Practices group? I'm looking for advice on how difficult it was to master, whether it decreased your time to market and any other general pitfalls.
We used SCSF for a real world app with about 10 developers. It was a steep learning curve to set up and develop a pattern of usage, but once it was set up, introducing new developers to the project was VERY easy. Using CAB and SCSF was very beneficial to our project especially getting each developer up to speed and productive. A downfall of SCSF is that it provides ALOT of functionality that may not be used (we probably only used 60% of the functionality). I am also using SCSF for a new project and am considering refactoring to PRISM. PRISM allows you to cull the functionality that is not used. If you use WPF, I suggest looking into PRISM.
Experiences of the Smart Client Software Factory Has anyone had any experience in building a 'real world' application with the Smart Client Software Factory, from Microsofts Patterns and Practices group? I'm looking for advice on how difficult it was to master, whether it decreased your time to market and any other general pitfalls.
TITLE: Experiences of the Smart Client Software Factory QUESTION: Has anyone had any experience in building a 'real world' application with the Smart Client Software Factory, from Microsofts Patterns and Practices group? I'm looking for advice on how difficult it was to master, whether it decreased your time to market and any other general pitfalls. ANSWER: We used SCSF for a real world app with about 10 developers. It was a steep learning curve to set up and develop a pattern of usage, but once it was set up, introducing new developers to the project was VERY easy. Using CAB and SCSF was very beneficial to our project especially getting each developer up to speed and productive. A downfall of SCSF is that it provides ALOT of functionality that may not be used (we probably only used 60% of the functionality). I am also using SCSF for a new project and am considering refactoring to PRISM. PRISM allows you to cull the functionality that is not used. If you use WPF, I suggest looking into PRISM.
[ ".net", "scsf" ]
16
16
4,594
5
0
2008-08-08T17:59:41.230000
2008-11-11T15:07:06.753000
6,208
6,258
FF3 WinXP != FF3 Ubuntu - why?
I've got a website that I've just uploaded onto the interwebs, and it's displaying differently using Firefox 3.0.1 on Ubuntu and WinXP. Two things I've noticed on Ubuntu: The favicon is missing The background color isn't displaying (it's set in the stylesheet) What have I done wrong? The CSS file is being fetched under Ubuntu, so why isn't it applying all of the stylesheet, just the bits it likes? And why isn't the favicon displaying? Are they the same problem? The answer on the background color: invalid HTML. But I'd love for someone to explain why it works under Windows and not Ubuntu. The answer on favicon: previously, there was no favicon. The browser cached the lack of favicon. Clear the Firefox cache, and all is well.
I would first suggesting getting you html and css code validated. If there are any errors in your markup, these can cause errors in the rendering. CSS Validator HTML Validator
FF3 WinXP != FF3 Ubuntu - why? I've got a website that I've just uploaded onto the interwebs, and it's displaying differently using Firefox 3.0.1 on Ubuntu and WinXP. Two things I've noticed on Ubuntu: The favicon is missing The background color isn't displaying (it's set in the stylesheet) What have I done wrong? The CSS file is being fetched under Ubuntu, so why isn't it applying all of the stylesheet, just the bits it likes? And why isn't the favicon displaying? Are they the same problem? The answer on the background color: invalid HTML. But I'd love for someone to explain why it works under Windows and not Ubuntu. The answer on favicon: previously, there was no favicon. The browser cached the lack of favicon. Clear the Firefox cache, and all is well.
TITLE: FF3 WinXP != FF3 Ubuntu - why? QUESTION: I've got a website that I've just uploaded onto the interwebs, and it's displaying differently using Firefox 3.0.1 on Ubuntu and WinXP. Two things I've noticed on Ubuntu: The favicon is missing The background color isn't displaying (it's set in the stylesheet) What have I done wrong? The CSS file is being fetched under Ubuntu, so why isn't it applying all of the stylesheet, just the bits it likes? And why isn't the favicon displaying? Are they the same problem? The answer on the background color: invalid HTML. But I'd love for someone to explain why it works under Windows and not Ubuntu. The answer on favicon: previously, there was no favicon. The browser cached the lack of favicon. Clear the Firefox cache, and all is well. ANSWER: I would first suggesting getting you html and css code validated. If there are any errors in your markup, these can cause errors in the rendering. CSS Validator HTML Validator
[ "css", "firefox", "ubuntu" ]
14
10
1,020
7
0
2008-08-08T18:03:26.230000
2008-08-08T18:54:41.010000
6,209
6,223
Split a string ignoring quoted sections
Given a string like this: a,"string, with",various,"values, and some",quoted What is a good algorithm to split this based on commas while ignoring the commas inside the quoted sections? The output should be an array: [ "a", "string, with", "various", "values, and some", "quoted" ]
If my language of choice didn't offer a way to do this without thinking then I would initially consider two options as the easy way out: Pre-parse and replace the commas within the string with another control character then split them, followed by a post-parse on the array to replace the control character used previously with the commas. Alternatively split them on the commas then post-parse the resulting array into another array checking for leading quotes on each array entry and concatenating the entries until I reached a terminating quote. These are hacks however, and if this is a pure 'mental' exercise then I suspect they will prove unhelpful. If this is a real world problem then it would help to know the language so that we could offer some specific advice.
Split a string ignoring quoted sections Given a string like this: a,"string, with",various,"values, and some",quoted What is a good algorithm to split this based on commas while ignoring the commas inside the quoted sections? The output should be an array: [ "a", "string, with", "various", "values, and some", "quoted" ]
TITLE: Split a string ignoring quoted sections QUESTION: Given a string like this: a,"string, with",various,"values, and some",quoted What is a good algorithm to split this based on commas while ignoring the commas inside the quoted sections? The output should be an array: [ "a", "string, with", "various", "values, and some", "quoted" ] ANSWER: If my language of choice didn't offer a way to do this without thinking then I would initially consider two options as the easy way out: Pre-parse and replace the commas within the string with another control character then split them, followed by a post-parse on the array to replace the control character used previously with the commas. Alternatively split them on the commas then post-parse the resulting array into another array checking for leading quotes on each array entry and concatenating the entries until I reached a terminating quote. These are hacks however, and if this is a pure 'mental' exercise then I suspect they will prove unhelpful. If this is a real world problem then it would help to know the language so that we could offer some specific advice.
[ "language-agnostic", "parsing", "csv" ]
22
2
10,281
13
0
2008-08-08T18:04:03.653000
2008-08-08T18:18:34.577000
6,210
6,213
E-mail Notifications
In a.net system I'm building, there is a need for automated e-mail notifications. These should be editable by an admin. What's the easiest way to do this? SQL table and WYSIWIG for editing? The queue is a great idea. I've been throwing around that type of process for awhile with my old company.
From a high level, yes.:D The main thing is some place to store the templates. A database is a great option unless you're not already using one, then file systems work fine. WSIWIG editors (such as fckeditor) work well and give you some good options regarding the features that you allow. Some sort of token replacement system is also a good idea if you need it. For example, if someone puts %FIRSTNAME% in the email template, the code that generates the email can do some simple pattern matching to replace known tokens with other known values that may be dynamic based on user or other circumstances.
E-mail Notifications In a.net system I'm building, there is a need for automated e-mail notifications. These should be editable by an admin. What's the easiest way to do this? SQL table and WYSIWIG for editing? The queue is a great idea. I've been throwing around that type of process for awhile with my old company.
TITLE: E-mail Notifications QUESTION: In a.net system I'm building, there is a need for automated e-mail notifications. These should be editable by an admin. What's the easiest way to do this? SQL table and WYSIWIG for editing? The queue is a great idea. I've been throwing around that type of process for awhile with my old company. ANSWER: From a high level, yes.:D The main thing is some place to store the templates. A database is a great option unless you're not already using one, then file systems work fine. WSIWIG editors (such as fckeditor) work well and give you some good options regarding the features that you allow. Some sort of token replacement system is also a good idea if you need it. For example, if someone puts %FIRSTNAME% in the email template, the code that generates the email can do some simple pattern matching to replace known tokens with other known values that may be dynamic based on user or other circumstances.
[ ".net", "email" ]
4
3
977
5
0
2008-08-08T18:04:24.950000
2008-08-08T18:09:55.017000
6,222
7,877
Eclipse on win64
Is anyone successfully using the latest 64-bit Ganymede release of Eclipse on Windows XP or Vista 64-bit? Currently I run the normal Eclipse 3.4 distribution on a 32bit JDK and launch & compile my apps with a 64bit JDK. Our previous experience has been that the 64bit Eclipse distro is unstable for us, so I'm curious if anyone is using it successfully. We are using JDK 1.6.0_05.
I'm using Eclipse with a 64bit VM. However I have to use Java 1.5, because with Java 1.6, even 1.6.0_10ea, Eclipse crashed when changing the.classpath-file. On Linux I had the same problems and could only get the 64bit Eclipse to work with 64bit Java 1.5. The problem seems to be with the just in time compilation, since with vmparam -Xint eclipse works -- but this is not a sollution, because it's slow then. Edit: With 1.6.0_11 it seems to work. 1.6_10 final might work as well as mentioned in the comment, but I've not tested that.
Eclipse on win64 Is anyone successfully using the latest 64-bit Ganymede release of Eclipse on Windows XP or Vista 64-bit? Currently I run the normal Eclipse 3.4 distribution on a 32bit JDK and launch & compile my apps with a 64bit JDK. Our previous experience has been that the 64bit Eclipse distro is unstable for us, so I'm curious if anyone is using it successfully. We are using JDK 1.6.0_05.
TITLE: Eclipse on win64 QUESTION: Is anyone successfully using the latest 64-bit Ganymede release of Eclipse on Windows XP or Vista 64-bit? Currently I run the normal Eclipse 3.4 distribution on a 32bit JDK and launch & compile my apps with a 64bit JDK. Our previous experience has been that the 64bit Eclipse distro is unstable for us, so I'm curious if anyone is using it successfully. We are using JDK 1.6.0_05. ANSWER: I'm using Eclipse with a 64bit VM. However I have to use Java 1.5, because with Java 1.6, even 1.6.0_10ea, Eclipse crashed when changing the.classpath-file. On Linux I had the same problems and could only get the 64bit Eclipse to work with 64bit Java 1.5. The problem seems to be with the just in time compilation, since with vmparam -Xint eclipse works -- but this is not a sollution, because it's slow then. Edit: With 1.6.0_11 it seems to work. 1.6_10 final might work as well as mentioned in the comment, but I've not tested that.
[ "java", "eclipse", "eclipse-3.4", "ganymede" ]
16
7
4,438
2
0
2008-08-08T18:17:50.460000
2008-08-11T15:42:36.747000
6,284
7,167
VS 2008 - Objects disappearing?
I've only been using VS 2008 Team Foundation for a few weeks. Over the last few days, I've noticed that sometimes one of my objects/controls on my page just disappears from intellisense. The project builds perfectly and the objects are still in the HTML, but I still can't find the object. Any one else notice this? Edit: For what it's worth, I know if I close VS and then open it up again, it comes back.
I am also having a number of problems with VS 2008. Who would guess that I don't ever need to select multiple controls on a web form... Anyway, a lot has been fixed in Service Pack 1, which is in Beta currently. Might be worth installing that. It has gone a little way to fixing absolute positioning. This isn't your problem, of course, but your fix might be in there as well.
VS 2008 - Objects disappearing? I've only been using VS 2008 Team Foundation for a few weeks. Over the last few days, I've noticed that sometimes one of my objects/controls on my page just disappears from intellisense. The project builds perfectly and the objects are still in the HTML, but I still can't find the object. Any one else notice this? Edit: For what it's worth, I know if I close VS and then open it up again, it comes back.
TITLE: VS 2008 - Objects disappearing? QUESTION: I've only been using VS 2008 Team Foundation for a few weeks. Over the last few days, I've noticed that sometimes one of my objects/controls on my page just disappears from intellisense. The project builds perfectly and the objects are still in the HTML, but I still can't find the object. Any one else notice this? Edit: For what it's worth, I know if I close VS and then open it up again, it comes back. ANSWER: I am also having a number of problems with VS 2008. Who would guess that I don't ever need to select multiple controls on a web form... Anyway, a lot has been fixed in Service Pack 1, which is in Beta currently. Might be worth installing that. It has gone a little way to fixing absolute positioning. This isn't your problem, of course, but your fix might be in there as well.
[ ".net", "visual-studio", "tfs" ]
8
2
864
3
0
2008-08-08T19:24:43.710000
2008-08-10T11:53:28.923000
6,301
6,320
Why is Array.Length an int, and not an uint
Why is Array.Length an int, and not a uint. This bothers me (just a bit) because a length value can never be negative. This also forced me to use an int for a length-property on my own class, because when you specify an int-value, this needs to be cast explicitly... So the ultimate question is: is there any use for an unsigned int ( uint )? Even Microsoft seems not to use them.
Unsigned int isn't CLS compliant and would therefore restrict usage of the property to those languages that do implement a UInt. See here: Framework 1.1 Introduction to the.NET Framework Class Library Framework 2.0.NET Framework Class Library Overview
Why is Array.Length an int, and not an uint Why is Array.Length an int, and not a uint. This bothers me (just a bit) because a length value can never be negative. This also forced me to use an int for a length-property on my own class, because when you specify an int-value, this needs to be cast explicitly... So the ultimate question is: is there any use for an unsigned int ( uint )? Even Microsoft seems not to use them.
TITLE: Why is Array.Length an int, and not an uint QUESTION: Why is Array.Length an int, and not a uint. This bothers me (just a bit) because a length value can never be negative. This also forced me to use an int for a length-property on my own class, because when you specify an int-value, this needs to be cast explicitly... So the ultimate question is: is there any use for an unsigned int ( uint )? Even Microsoft seems not to use them. ANSWER: Unsigned int isn't CLS compliant and would therefore restrict usage of the property to those languages that do implement a UInt. See here: Framework 1.1 Introduction to the.NET Framework Class Library Framework 2.0.NET Framework Class Library Overview
[ "c#", ".net", "int", "uint" ]
109
68
18,294
5
0
2008-08-08T19:34:13.503000
2008-08-08T19:50:14.987000
6,325
6,333
Why are unsigned int's not CLS compliant?
Why are unsigned integers not CLS compliant? I am starting to think the type specification is just for performance and not for correctness.
Not all languages have the concept of unsigned ints. For example VB 6 had no concept of unsigned ints which I suspect drove the decision of the designers of VB7/7.1 not to implement as well (it's implemented now in VB8). To quote: http://msdn.microsoft.com/en-us/library/12a7a7h3.aspx The CLS was designed to be large enough to include the language constructs that are commonly needed by developers, yet small enough that most languages are able to support it. In addition, any language construct that makes it impossible to rapidly verify the type safety of code was excluded from the CLS so that all CLS-compliant languages can produce verifiable code if they choose to do so. Update: I did wonder about this some years back, and whilst I can't see why a UInt wouldn't be type safety verifiable, I guess the CLS guys had to have a cut off point somewhere as to what would be the baseline minimum number of value types supported. Also when you think about the longer term where more and more languages are being ported to the CLR why force them to implement unsigned ints to gain CLS compliance if there is absolutely no concept, ever?
Why are unsigned int's not CLS compliant? Why are unsigned integers not CLS compliant? I am starting to think the type specification is just for performance and not for correctness.
TITLE: Why are unsigned int's not CLS compliant? QUESTION: Why are unsigned integers not CLS compliant? I am starting to think the type specification is just for performance and not for correctness. ANSWER: Not all languages have the concept of unsigned ints. For example VB 6 had no concept of unsigned ints which I suspect drove the decision of the designers of VB7/7.1 not to implement as well (it's implemented now in VB8). To quote: http://msdn.microsoft.com/en-us/library/12a7a7h3.aspx The CLS was designed to be large enough to include the language constructs that are commonly needed by developers, yet small enough that most languages are able to support it. In addition, any language construct that makes it impossible to rapidly verify the type safety of code was excluded from the CLS so that all CLS-compliant languages can produce verifiable code if they choose to do so. Update: I did wonder about this some years back, and whilst I can't see why a UInt wouldn't be type safety verifiable, I guess the CLS guys had to have a cut off point somewhere as to what would be the baseline minimum number of value types supported. Also when you think about the longer term where more and more languages are being ported to the CLR why force them to implement unsigned ints to gain CLS compliance if there is absolutely no concept, ever?
[ "c#", ".net", "unsigned-integer", "cls-compliant" ]
123
102
22,478
4
0
2008-08-08T19:55:39.920000
2008-08-08T20:01:53.497000
6,326
6,355
Haml: how do I set a dynamic class value?
I have the following html.erb code that I'm looking to move to Haml: <%= item.dashboardstatus.status %> What it does is associate the CSS class of the currently assigned status to the span. How is this done in Haml? I'm sure I'm missing something really simple.
Not sure. Maybe: %span{:class => item.dashboardstatus.cssclass }= item.dashboardstatus.status
Haml: how do I set a dynamic class value? I have the following html.erb code that I'm looking to move to Haml: <%= item.dashboardstatus.status %> What it does is associate the CSS class of the currently assigned status to the span. How is this done in Haml? I'm sure I'm missing something really simple.
TITLE: Haml: how do I set a dynamic class value? QUESTION: I have the following html.erb code that I'm looking to move to Haml: <%= item.dashboardstatus.status %> What it does is associate the CSS class of the currently assigned status to the span. How is this done in Haml? I'm sure I'm missing something really simple. ANSWER: Not sure. Maybe: %span{:class => item.dashboardstatus.cssclass }= item.dashboardstatus.status
[ "css", "ruby-on-rails", "haml" ]
20
21
7,166
3
0
2008-08-08T19:56:42.787000
2008-08-08T20:28:18.387000
6,340
6,349
Multiple foreign keys?
I've got a table that is supposed to track days and costs for shipping product from one vendor to another. We (brilliantly:p) stored both the shipping vendors (FedEx, UPS) with the product handling vendors (Think... Dunder Mifflin) in a "VENDOR" table. So, I have three columns in my SHIPPING_DETAILS table that all reference VENDOR.no. For some reason MySQL isn't letting me define all three as foreign keys. Any ideas? CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; Edited to remove double primary key definition... Yeah, unfortunately that didn't fix it though. Now I'm getting: Can't create table './ REMOVED MY DB NAME /SHIPPING_GRID.frm' (errno: 150) Doing a phpinfo() tells me this for mysql: Client API version 5.0.45 Yes, the VENDOR.no is type int(6).
You defined the primary key twice. Try: CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; The VENDOR primary key must be INT(6), and both tables must be of type InnoDB.
Multiple foreign keys? I've got a table that is supposed to track days and costs for shipping product from one vendor to another. We (brilliantly:p) stored both the shipping vendors (FedEx, UPS) with the product handling vendors (Think... Dunder Mifflin) in a "VENDOR" table. So, I have three columns in my SHIPPING_DETAILS table that all reference VENDOR.no. For some reason MySQL isn't letting me define all three as foreign keys. Any ideas? CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; Edited to remove double primary key definition... Yeah, unfortunately that didn't fix it though. Now I'm getting: Can't create table './ REMOVED MY DB NAME /SHIPPING_GRID.frm' (errno: 150) Doing a phpinfo() tells me this for mysql: Client API version 5.0.45 Yes, the VENDOR.no is type int(6).
TITLE: Multiple foreign keys? QUESTION: I've got a table that is supposed to track days and costs for shipping product from one vendor to another. We (brilliantly:p) stored both the shipping vendors (FedEx, UPS) with the product handling vendors (Think... Dunder Mifflin) in a "VENDOR" table. So, I have three columns in my SHIPPING_DETAILS table that all reference VENDOR.no. For some reason MySQL isn't letting me define all three as foreign keys. Any ideas? CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; Edited to remove double primary key definition... Yeah, unfortunately that didn't fix it though. Now I'm getting: Can't create table './ REMOVED MY DB NAME /SHIPPING_GRID.frm' (errno: 150) Doing a phpinfo() tells me this for mysql: Client API version 5.0.45 Yes, the VENDOR.no is type int(6). ANSWER: You defined the primary key twice. Try: CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; The VENDOR primary key must be INT(6), and both tables must be of type InnoDB.
[ "sql", "mysql", "foreign-keys" ]
18
13
98,266
3
0
2008-08-08T20:07:43.390000
2008-08-08T20:18:25.553000
6,369
10,838
How to pass a comma separated list to a stored procedure?
So I have a Sybase stored proc that takes 1 parameter that's a comma separated list of strings and runs a query with in in an IN() clause: CREATE PROCEDURE getSomething @keyList varchar(4096) AS SELECT * FROM mytbl WHERE name IN (@keyList) How do I call my stored proc with more than 1 value in the list? So far I've tried exec getSomething 'John' -- works but only 1 value exec getSomething 'John','Tom' -- doesn't work - expects two variables exec getSomething "'John','Tom'" -- doesn't work - doesn't find anything exec getSomething '"John","Tom"' -- doesn't work - doesn't find anything exec getSomething '\'John\',\'Tom\'' -- doesn't work - syntax error EDIT: I actually found this page that has a great reference of the various ways to pas an array to a sproc
If you're using Sybase 12.5 or earlier then you can't use functions. A workaround might be to populate a temporary table with the values and read them from there.
How to pass a comma separated list to a stored procedure? So I have a Sybase stored proc that takes 1 parameter that's a comma separated list of strings and runs a query with in in an IN() clause: CREATE PROCEDURE getSomething @keyList varchar(4096) AS SELECT * FROM mytbl WHERE name IN (@keyList) How do I call my stored proc with more than 1 value in the list? So far I've tried exec getSomething 'John' -- works but only 1 value exec getSomething 'John','Tom' -- doesn't work - expects two variables exec getSomething "'John','Tom'" -- doesn't work - doesn't find anything exec getSomething '"John","Tom"' -- doesn't work - doesn't find anything exec getSomething '\'John\',\'Tom\'' -- doesn't work - syntax error EDIT: I actually found this page that has a great reference of the various ways to pas an array to a sproc
TITLE: How to pass a comma separated list to a stored procedure? QUESTION: So I have a Sybase stored proc that takes 1 parameter that's a comma separated list of strings and runs a query with in in an IN() clause: CREATE PROCEDURE getSomething @keyList varchar(4096) AS SELECT * FROM mytbl WHERE name IN (@keyList) How do I call my stored proc with more than 1 value in the list? So far I've tried exec getSomething 'John' -- works but only 1 value exec getSomething 'John','Tom' -- doesn't work - expects two variables exec getSomething "'John','Tom'" -- doesn't work - doesn't find anything exec getSomething '"John","Tom"' -- doesn't work - doesn't find anything exec getSomething '\'John\',\'Tom\'' -- doesn't work - syntax error EDIT: I actually found this page that has a great reference of the various ways to pas an array to a sproc ANSWER: If you're using Sybase 12.5 or earlier then you can't use functions. A workaround might be to populate a temporary table with the values and read them from there.
[ "sql", "sap-ase" ]
19
4
52,340
11
0
2008-08-08T20:48:29.377000
2008-08-14T09:27:30.793000
6,371
6,380
How do you manage databases in development, test, and production?
I've had a hard time trying to find good examples of how to manage database schemas and data between development, test, and production servers. Here's our setup. Each developer has a virtual machine running our app and the MySQL database. It is their personal sandbox to do whatever they want. Currently, developers will make a change to the SQL schema and do a dump of the database to a text file that they commit into SVN. We're wanting to deploy a continuous integration development server that will always be running the latest committed code. If we do that now, it will reload the database from SVN for each build. We have a test (virtual) server that runs "release candidates." Deploying to the test server is currently a very manual process, and usually involves me loading the latest SQL from SVN and tweaking it. Also, the data on the test server is inconsistent. You end up with whatever test data the last developer to commit had on his sandbox server. Where everything breaks down is the deployment to production. Since we can't overwrite the live data with test data, this involves manually re-creating all the schema changes. If there were a large number of schema changes or conversion scripts to manipulate the data, this can get really hairy. If the problem was just the schema, It'd be an easier problem, but there is "base" data in the database that is updated during development as well, such as meta-data in security and permissions tables. This is the biggest barrier I see in moving toward continuous integration and one-step-builds. How do you solve it? A follow-up question: how do you track database versions so you know which scripts to run to upgrade a given database instance? Is a version table like Lance mentions below the standard procedure? Thanks for the reference to Tarantino. I'm not in a.NET environment, but I found their DataBaseChangeMangement wiki page to be very helpful. Especially this Powerpoint Presentation (.ppt) I'm going to write a Python script that checks the names of *.sql scripts in a given directory against a table in the database and runs the ones that aren't there in order based on a integer that forms the first part of the filename. If it is a pretty simple solution, as I suspect it will be, then I'll post it here. I've got a working script for this. It handles initializing the DB if it doesn't exist and running upgrade scripts as necessary. There are also switches for wiping an existing database and importing test data from a file. It's about 200 lines, so I won't post it (though I might put it on pastebin if there's interest).
There are a couple of good options. I wouldn't use the "restore a backup" strategy. Script all your schema changes, and have your CI server run those scripts on the database. Have a version table to keep track of the current database version, and only execute the scripts if they are for a newer version. Use a migration solution. These solutions vary by language, but for.NET I use Migrator.NET. This allows you to version your database and move up and down between versions. Your schema is specified in C# code.
How do you manage databases in development, test, and production? I've had a hard time trying to find good examples of how to manage database schemas and data between development, test, and production servers. Here's our setup. Each developer has a virtual machine running our app and the MySQL database. It is their personal sandbox to do whatever they want. Currently, developers will make a change to the SQL schema and do a dump of the database to a text file that they commit into SVN. We're wanting to deploy a continuous integration development server that will always be running the latest committed code. If we do that now, it will reload the database from SVN for each build. We have a test (virtual) server that runs "release candidates." Deploying to the test server is currently a very manual process, and usually involves me loading the latest SQL from SVN and tweaking it. Also, the data on the test server is inconsistent. You end up with whatever test data the last developer to commit had on his sandbox server. Where everything breaks down is the deployment to production. Since we can't overwrite the live data with test data, this involves manually re-creating all the schema changes. If there were a large number of schema changes or conversion scripts to manipulate the data, this can get really hairy. If the problem was just the schema, It'd be an easier problem, but there is "base" data in the database that is updated during development as well, such as meta-data in security and permissions tables. This is the biggest barrier I see in moving toward continuous integration and one-step-builds. How do you solve it? A follow-up question: how do you track database versions so you know which scripts to run to upgrade a given database instance? Is a version table like Lance mentions below the standard procedure? Thanks for the reference to Tarantino. I'm not in a.NET environment, but I found their DataBaseChangeMangement wiki page to be very helpful. Especially this Powerpoint Presentation (.ppt) I'm going to write a Python script that checks the names of *.sql scripts in a given directory against a table in the database and runs the ones that aren't there in order based on a integer that forms the first part of the filename. If it is a pretty simple solution, as I suspect it will be, then I'll post it here. I've got a working script for this. It handles initializing the DB if it doesn't exist and running upgrade scripts as necessary. There are also switches for wiping an existing database and importing test data from a file. It's about 200 lines, so I won't post it (though I might put it on pastebin if there's interest).
TITLE: How do you manage databases in development, test, and production? QUESTION: I've had a hard time trying to find good examples of how to manage database schemas and data between development, test, and production servers. Here's our setup. Each developer has a virtual machine running our app and the MySQL database. It is their personal sandbox to do whatever they want. Currently, developers will make a change to the SQL schema and do a dump of the database to a text file that they commit into SVN. We're wanting to deploy a continuous integration development server that will always be running the latest committed code. If we do that now, it will reload the database from SVN for each build. We have a test (virtual) server that runs "release candidates." Deploying to the test server is currently a very manual process, and usually involves me loading the latest SQL from SVN and tweaking it. Also, the data on the test server is inconsistent. You end up with whatever test data the last developer to commit had on his sandbox server. Where everything breaks down is the deployment to production. Since we can't overwrite the live data with test data, this involves manually re-creating all the schema changes. If there were a large number of schema changes or conversion scripts to manipulate the data, this can get really hairy. If the problem was just the schema, It'd be an easier problem, but there is "base" data in the database that is updated during development as well, such as meta-data in security and permissions tables. This is the biggest barrier I see in moving toward continuous integration and one-step-builds. How do you solve it? A follow-up question: how do you track database versions so you know which scripts to run to upgrade a given database instance? Is a version table like Lance mentions below the standard procedure? Thanks for the reference to Tarantino. I'm not in a.NET environment, but I found their DataBaseChangeMangement wiki page to be very helpful. Especially this Powerpoint Presentation (.ppt) I'm going to write a Python script that checks the names of *.sql scripts in a given directory against a table in the database and runs the ones that aren't there in order based on a integer that forms the first part of the filename. If it is a pretty simple solution, as I suspect it will be, then I'll post it here. I've got a working script for this. It handles initializing the DB if it doesn't exist and running upgrade scripts as necessary. There are also switches for wiping an existing database and importing test data from a file. It's about 200 lines, so I won't post it (though I might put it on pastebin if there's interest). ANSWER: There are a couple of good options. I wouldn't use the "restore a backup" strategy. Script all your schema changes, and have your CI server run those scripts on the database. Have a version table to keep track of the current database version, and only execute the scripts if they are for a newer version. Use a migration solution. These solutions vary by language, but for.NET I use Migrator.NET. This allows you to version your database and move up and down between versions. Your schema is specified in C# code.
[ "mysql", "svn" ]
185
58
43,195
14
0
2008-08-08T20:50:02.930000
2008-08-08T21:01:09.490000
6,373
6,424
What's the difference in closure style
There are two popular closure styles in javascript. The first I call anonymous constructor: new function() { var code... } and the inline executed function: (function() { var code... })(); are there differences in behaviour between those two? Is one "better" over the other?
Both cases will execute the function, the only real difference is what the return value of the expression may be, and what the value of "this" will be inside the function. Basically behaviour of new expression Is effectively equivalent to var tempObject = {}; var result = expression.call(tempObject); if (result is not an object) result = tempObject; Although of course tempObject and result are transient values you can never see (they're implementation details in the interpreter), and there is no JS mechanism to do the "is not an object" check. Broadly speaking the "new function() {.. }" method will be slower due to the need to create the this object for the constructor. That said this should be not be a real difference as object allocation is not slow, and you shouldn't be using such code in hot code (due to the cost of creating the function object and associated closure). Edit: one thing i realised that i missed from this is that the tempObject will get expression s prototype, eg. (before the expression.call ) tempObject.__proto__ = expression.prototype
What's the difference in closure style There are two popular closure styles in javascript. The first I call anonymous constructor: new function() { var code... } and the inline executed function: (function() { var code... })(); are there differences in behaviour between those two? Is one "better" over the other?
TITLE: What's the difference in closure style QUESTION: There are two popular closure styles in javascript. The first I call anonymous constructor: new function() { var code... } and the inline executed function: (function() { var code... })(); are there differences in behaviour between those two? Is one "better" over the other? ANSWER: Both cases will execute the function, the only real difference is what the return value of the expression may be, and what the value of "this" will be inside the function. Basically behaviour of new expression Is effectively equivalent to var tempObject = {}; var result = expression.call(tempObject); if (result is not an object) result = tempObject; Although of course tempObject and result are transient values you can never see (they're implementation details in the interpreter), and there is no JS mechanism to do the "is not an object" check. Broadly speaking the "new function() {.. }" method will be slower due to the need to create the this object for the constructor. That said this should be not be a real difference as object allocation is not slow, and you shouldn't be using such code in hot code (due to the cost of creating the function object and associated closure). Edit: one thing i realised that i missed from this is that the tempObject will get expression s prototype, eg. (before the expression.call ) tempObject.__proto__ = expression.prototype
[ "javascript" ]
23
12
1,793
5
0
2008-08-08T20:53:21.393000
2008-08-08T22:02:14.830000
6,378
8,431
What client(s) should be targeted in implementing an ICalendar export for events?
http://en.wikipedia.org/wiki/ICalendar I'm working to implement an export feature for events. The link above lists tons of clients that support the ICalendar standard, but the "three big ones" I can see are Apple's iCal, Microsoft's Outlook, and Google's Gmail. I'm starting to get the feeling that each of these client implement different parts of the "standard", and I'm unsure of what pieces of information we should be trying to export from the application so that someone can put it on their calendar (especially around recurrence). For example, from what I understand Outlook doesn't support hourly recurrence. Could any of you provide guidance of the "happy medium" here from a features implementation standpoint? Secondary question, if we decide to cut features from the export (such as hourly recurrence) because it isn't supported in Outlook, should we support it in the application as well? (it is a general purpose event scheduling application, with no business specific use in mind...so we really are looking for the happy medium).
I have to say that I don't use the hourly recurrence feature as really how many people have events that repeat in the same day? I could see if someone however was to schedule when they needed to take a particular medicine at recurring times throughout the day. I would say support full features in the application itself, but provide a warning when they go to export the calendar that all event details may not work as expected or find a way to export in a different manner for Outlook alone that does provide the hourly recurrence feature.
What client(s) should be targeted in implementing an ICalendar export for events? http://en.wikipedia.org/wiki/ICalendar I'm working to implement an export feature for events. The link above lists tons of clients that support the ICalendar standard, but the "three big ones" I can see are Apple's iCal, Microsoft's Outlook, and Google's Gmail. I'm starting to get the feeling that each of these client implement different parts of the "standard", and I'm unsure of what pieces of information we should be trying to export from the application so that someone can put it on their calendar (especially around recurrence). For example, from what I understand Outlook doesn't support hourly recurrence. Could any of you provide guidance of the "happy medium" here from a features implementation standpoint? Secondary question, if we decide to cut features from the export (such as hourly recurrence) because it isn't supported in Outlook, should we support it in the application as well? (it is a general purpose event scheduling application, with no business specific use in mind...so we really are looking for the happy medium).
TITLE: What client(s) should be targeted in implementing an ICalendar export for events? QUESTION: http://en.wikipedia.org/wiki/ICalendar I'm working to implement an export feature for events. The link above lists tons of clients that support the ICalendar standard, but the "three big ones" I can see are Apple's iCal, Microsoft's Outlook, and Google's Gmail. I'm starting to get the feeling that each of these client implement different parts of the "standard", and I'm unsure of what pieces of information we should be trying to export from the application so that someone can put it on their calendar (especially around recurrence). For example, from what I understand Outlook doesn't support hourly recurrence. Could any of you provide guidance of the "happy medium" here from a features implementation standpoint? Secondary question, if we decide to cut features from the export (such as hourly recurrence) because it isn't supported in Outlook, should we support it in the application as well? (it is a general purpose event scheduling application, with no business specific use in mind...so we really are looking for the happy medium). ANSWER: I have to say that I don't use the hourly recurrence feature as really how many people have events that repeat in the same day? I could see if someone however was to schedule when they needed to take a particular medicine at recurring times throughout the day. I would say support full features in the application itself, but provide a warning when they go to export the calendar that all event details may not work as expected or find a way to export in a different manner for Outlook alone that does provide the hourly recurrence feature.
[ "outlook", "gmail", "icalendar", "recurrence" ]
5
2
772
2
0
2008-08-08T20:58:11.103000
2008-08-12T03:10:43.130000
6,392
6,496
Java Time Zone is messed up
I am running a Tomcat application, and I need to display some time values. Unfortunately, the time is coming up an hour off. I looked into it and discovered that my default TimeZone is being set to: sun.util.calendar.ZoneInfo[id="GMT-08:00", offset=-28800000, dstSavings=0, useDaylight=false, transitions=0, lastRule=null] Rather than the Pacific time zone. This is further indicated when I try to print the default time zone's display name, and it comes up "GMT-08:00", which seems to indicate to me that it is not correctly set to the US Pacific time zone. I am running on Ubuntu Hardy Heron, upgraded from Gutsy Gibbon. Is there a configuration file I can update to tell the JRE to use Pacific with all the associated daylight savings time information? The time on my machine shows correctly, so it doesn't seem to be an OS-wide misconfiguration. Ok, here's an update. A coworker suggested I update JAVA_OPTS in my /etc/profile to include "-Duser.timezone=US/Pacific", which worked (I also saw CATALINA_OPTS, which I updated as well). Actually, I just exported the change into the variables rather than use the new /etc/profile (a reboot later will pick up the changes and I will be golden). However, I still think there is a better solution... there should be a configuration for Java somewhere that says what timezone it is using, or how it is grabbing the timezone. If someone knows such a setting, that would be awesome, but for now this is a decent workaround. I am using 1.5, and it is most definitely a DST problem. As you can see, the time zone is set to not use daylight savings. My belief is it is generically set to -8 offset rather than the specific Pacific timezone. Since the generic -8 offset has no daylight savings info, it's of course not using it, but the question is, where do I tell Java to use Pacific time zone when it starts up? I'm NOT looking for a programmatic solution, it should be a configuration solution.
It's a "quirk" in the way the JVM looks up the zoneinfo file. See Bug ID 6456628. The easiest workaround is to make /etc/localtime a symlink to the correct zoneinfo file. For Pacific time, the following commands should work: # sudo cp /etc/localtime /etc/localtime.dist # sudo ln -fs /usr/share/zoneinfo/America/Los_Angeles /etc/localtime I haven't had any problems with the symlink approach. Edit: Added "sudo" to the commands.
Java Time Zone is messed up I am running a Tomcat application, and I need to display some time values. Unfortunately, the time is coming up an hour off. I looked into it and discovered that my default TimeZone is being set to: sun.util.calendar.ZoneInfo[id="GMT-08:00", offset=-28800000, dstSavings=0, useDaylight=false, transitions=0, lastRule=null] Rather than the Pacific time zone. This is further indicated when I try to print the default time zone's display name, and it comes up "GMT-08:00", which seems to indicate to me that it is not correctly set to the US Pacific time zone. I am running on Ubuntu Hardy Heron, upgraded from Gutsy Gibbon. Is there a configuration file I can update to tell the JRE to use Pacific with all the associated daylight savings time information? The time on my machine shows correctly, so it doesn't seem to be an OS-wide misconfiguration. Ok, here's an update. A coworker suggested I update JAVA_OPTS in my /etc/profile to include "-Duser.timezone=US/Pacific", which worked (I also saw CATALINA_OPTS, which I updated as well). Actually, I just exported the change into the variables rather than use the new /etc/profile (a reboot later will pick up the changes and I will be golden). However, I still think there is a better solution... there should be a configuration for Java somewhere that says what timezone it is using, or how it is grabbing the timezone. If someone knows such a setting, that would be awesome, but for now this is a decent workaround. I am using 1.5, and it is most definitely a DST problem. As you can see, the time zone is set to not use daylight savings. My belief is it is generically set to -8 offset rather than the specific Pacific timezone. Since the generic -8 offset has no daylight savings info, it's of course not using it, but the question is, where do I tell Java to use Pacific time zone when it starts up? I'm NOT looking for a programmatic solution, it should be a configuration solution.
TITLE: Java Time Zone is messed up QUESTION: I am running a Tomcat application, and I need to display some time values. Unfortunately, the time is coming up an hour off. I looked into it and discovered that my default TimeZone is being set to: sun.util.calendar.ZoneInfo[id="GMT-08:00", offset=-28800000, dstSavings=0, useDaylight=false, transitions=0, lastRule=null] Rather than the Pacific time zone. This is further indicated when I try to print the default time zone's display name, and it comes up "GMT-08:00", which seems to indicate to me that it is not correctly set to the US Pacific time zone. I am running on Ubuntu Hardy Heron, upgraded from Gutsy Gibbon. Is there a configuration file I can update to tell the JRE to use Pacific with all the associated daylight savings time information? The time on my machine shows correctly, so it doesn't seem to be an OS-wide misconfiguration. Ok, here's an update. A coworker suggested I update JAVA_OPTS in my /etc/profile to include "-Duser.timezone=US/Pacific", which worked (I also saw CATALINA_OPTS, which I updated as well). Actually, I just exported the change into the variables rather than use the new /etc/profile (a reboot later will pick up the changes and I will be golden). However, I still think there is a better solution... there should be a configuration for Java somewhere that says what timezone it is using, or how it is grabbing the timezone. If someone knows such a setting, that would be awesome, but for now this is a decent workaround. I am using 1.5, and it is most definitely a DST problem. As you can see, the time zone is set to not use daylight savings. My belief is it is generically set to -8 offset rather than the specific Pacific timezone. Since the generic -8 offset has no daylight savings info, it's of course not using it, but the question is, where do I tell Java to use Pacific time zone when it starts up? I'm NOT looking for a programmatic solution, it should be a configuration solution. ANSWER: It's a "quirk" in the way the JVM looks up the zoneinfo file. See Bug ID 6456628. The easiest workaround is to make /etc/localtime a symlink to the correct zoneinfo file. For Pacific time, the following commands should work: # sudo cp /etc/localtime /etc/localtime.dist # sudo ln -fs /usr/share/zoneinfo/America/Los_Angeles /etc/localtime I haven't had any problems with the symlink approach. Edit: Added "sudo" to the commands.
[ "java", "linux", "timezone" ]
34
30
45,722
5
0
2008-08-08T21:24:01.490000
2008-08-09T00:46:46.260000
6,406
6,412
How to access .Net element on Master page from a Content page?
Is it possible to access an element on a Master page from the page loaded within the ContentPlaceHolder for the master? I have a ListView that lists people's names in a navigation area on the Master page. I would like to update the ListView after a person has been added to the table that the ListView is data bound to. The ListView currently does not update it's values until the cache is reloaded. We have found that just re-running the ListView.DataBind() will update a listview's contents. We have not been able to run the ListView.DataBind() on a page that uses the Master page. Below is a sample of what I wanted to do but a compiler error says "PeopleListView does not exist in the current context" GIS.master - Where ListView resides... GISInput_People.aspx - Uses GIS.master as it's master page GISInput_People.aspx.cs AddNewPerson() { // Add person to table.... // Update Person List PeopleListView.DataBind();... } What would be the best way to resolve an issue like this in C#.Net?
I believe you could do this by using this.Master.FindControl or something similar, but you probably shouldn't - it requires the content page to know too much about the structure of the master page. I would suggest another method, such as firing an event in the content area that the master could listen for and re-bind when fired.
How to access .Net element on Master page from a Content page? Is it possible to access an element on a Master page from the page loaded within the ContentPlaceHolder for the master? I have a ListView that lists people's names in a navigation area on the Master page. I would like to update the ListView after a person has been added to the table that the ListView is data bound to. The ListView currently does not update it's values until the cache is reloaded. We have found that just re-running the ListView.DataBind() will update a listview's contents. We have not been able to run the ListView.DataBind() on a page that uses the Master page. Below is a sample of what I wanted to do but a compiler error says "PeopleListView does not exist in the current context" GIS.master - Where ListView resides... GISInput_People.aspx - Uses GIS.master as it's master page GISInput_People.aspx.cs AddNewPerson() { // Add person to table.... // Update Person List PeopleListView.DataBind();... } What would be the best way to resolve an issue like this in C#.Net?
TITLE: How to access .Net element on Master page from a Content page? QUESTION: Is it possible to access an element on a Master page from the page loaded within the ContentPlaceHolder for the master? I have a ListView that lists people's names in a navigation area on the Master page. I would like to update the ListView after a person has been added to the table that the ListView is data bound to. The ListView currently does not update it's values until the cache is reloaded. We have found that just re-running the ListView.DataBind() will update a listview's contents. We have not been able to run the ListView.DataBind() on a page that uses the Master page. Below is a sample of what I wanted to do but a compiler error says "PeopleListView does not exist in the current context" GIS.master - Where ListView resides... GISInput_People.aspx - Uses GIS.master as it's master page GISInput_People.aspx.cs AddNewPerson() { // Add person to table.... // Update Person List PeopleListView.DataBind();... } What would be the best way to resolve an issue like this in C#.Net? ANSWER: I believe you could do this by using this.Master.FindControl or something similar, but you probably shouldn't - it requires the content page to know too much about the structure of the master page. I would suggest another method, such as firing an event in the content area that the master could listen for and re-bind when fired.
[ "c#", ".net" ]
15
17
11,714
6
0
2008-08-08T21:39:04.283000
2008-08-08T21:46:22.053000
6,414
6,417
C# loop — break vs. continue
In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration? Example: foreach (DataRow row in myTable.Rows) { if (someConditionEvalsToTrue) { break; //what's the difference between this and continue? //continue; } }
break will exit the loop completely, continue will just skip the current iteration. For example: for (int i = 0; i < 10; i++) { if (i == 0) { break; } DoSomeThingWith(i); } The break will cause the loop to exit on the first iteration — DoSomeThingWith will never be executed. While: for (int i = 0; i < 10; i++) { if (i == 0) { continue; } DoSomeThingWith(i); } Here continue skips to the next iteration of the for-loop, meaning DoSomeThingWith will not execute for i == 0. But the loop will continue and DoSomeThingWith will be executed for i == 1 to i == 9.
C# loop — break vs. continue In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration? Example: foreach (DataRow row in myTable.Rows) { if (someConditionEvalsToTrue) { break; //what's the difference between this and continue? //continue; } }
TITLE: C# loop — break vs. continue QUESTION: In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration? Example: foreach (DataRow row in myTable.Rows) { if (someConditionEvalsToTrue) { break; //what's the difference between this and continue? //continue; } } ANSWER: break will exit the loop completely, continue will just skip the current iteration. For example: for (int i = 0; i < 10; i++) { if (i == 0) { break; } DoSomeThingWith(i); } The break will cause the loop to exit on the first iteration — DoSomeThingWith will never be executed. While: for (int i = 0; i < 10; i++) { if (i == 0) { continue; } DoSomeThingWith(i); } Here continue skips to the next iteration of the for-loop, meaning DoSomeThingWith will not execute for i == 0. But the loop will continue and DoSomeThingWith will be executed for i == 1 to i == 9.
[ "c#", "loops", "break", "enumeration", "continue" ]
878
1,614
862,830
16
0
2008-08-08T21:49:01.127000
2008-08-08T21:51:35.397000
6,430
6,435
How to programmatically iterate datagrid rows?
I'm suddenly back to WinForms, after years of web development, and am having trouble with something that should be simple. I have an ArrayList of business objects bound to a Windows Forms DataGrid. I'd like the user to be able to edit the cells, and when finished, press a Save button. At that point I'd like to iterate the all the rows and columns in the DataGrid to find any changes, and save them to the database. But I can't find a way to access the DataGrid rows. I'll also want to validate individual cells real time, as they are edited, but I'm pretty sure that can be done. (Maybe not with an ArrayList as the DataSource?) But as for iterating the DataGrid, I'm quite surprised it doesn't seem possible. Must I really stuff my business objects data into datatables in order to use the datagrid?
foreach(var row in DataGrid1.Rows) { DoStuff(row); } //Or --------------------------------------------- foreach(DataGridRow row in DataGrid1.Rows) { DoStuff(row); } //Or --------------------------------------------- for(int i = 0; i< DataGrid1.Rows.Count - 1; i++) { DoStuff(DataGrid1.Rows[i]); }
How to programmatically iterate datagrid rows? I'm suddenly back to WinForms, after years of web development, and am having trouble with something that should be simple. I have an ArrayList of business objects bound to a Windows Forms DataGrid. I'd like the user to be able to edit the cells, and when finished, press a Save button. At that point I'd like to iterate the all the rows and columns in the DataGrid to find any changes, and save them to the database. But I can't find a way to access the DataGrid rows. I'll also want to validate individual cells real time, as they are edited, but I'm pretty sure that can be done. (Maybe not with an ArrayList as the DataSource?) But as for iterating the DataGrid, I'm quite surprised it doesn't seem possible. Must I really stuff my business objects data into datatables in order to use the datagrid?
TITLE: How to programmatically iterate datagrid rows? QUESTION: I'm suddenly back to WinForms, after years of web development, and am having trouble with something that should be simple. I have an ArrayList of business objects bound to a Windows Forms DataGrid. I'd like the user to be able to edit the cells, and when finished, press a Save button. At that point I'd like to iterate the all the rows and columns in the DataGrid to find any changes, and save them to the database. But I can't find a way to access the DataGrid rows. I'll also want to validate individual cells real time, as they are edited, but I'm pretty sure that can be done. (Maybe not with an ArrayList as the DataSource?) But as for iterating the DataGrid, I'm quite surprised it doesn't seem possible. Must I really stuff my business objects data into datatables in order to use the datagrid? ANSWER: foreach(var row in DataGrid1.Rows) { DoStuff(row); } //Or --------------------------------------------- foreach(DataGridRow row in DataGrid1.Rows) { DoStuff(row); } //Or --------------------------------------------- for(int i = 0; i< DataGrid1.Rows.Count - 1; i++) { DoStuff(DataGrid1.Rows[i]); }
[ "winforms" ]
4
5
9,121
4
0
2008-08-08T22:08:29.980000
2008-08-08T22:20:28.973000
6,440
6,445
.NET 3.5 Redistributable -- 200 MB? Other options?
I've been using a lot of new.NET 3.5 features in the work that I've been doing, lately. The application that I'm building is intended for distribution among consumers who will probably not have the latest version (or perhaps any version ) of the.NET framework on their machines. I went to go download the.NET 3.5 redistributable package only to find out that it's almost 200 MB! This is unacceptable for my application, because it's supposed to be a quick and painless consumer application that installs quickly and keeps a low profile on the user's machine. For users that have.NET 3.5 already installed, our binary downloads have been instantaneous, so far. This 200 MB gorilla will more than quadruple the size of the download. Is there any other option than this redistributable package that I can use to make sure the framework is on the machine that won't take the user out of our "quick and painless" workflow? Our target time from beginning of download to finalizing the install is less than two minutes. Is it just not possible for someone who doesn't already have.NET installed?
That's one of the sad reasons i'm still targeting.net 2.0 whenever possible:/ But people don't neccessarily need the full 200 MB Package. There is a 3 MB Bootstrapper which will only download the required components:.net 3.5 SP1 Bootstrapper However, the worst case scenario is still a pretty hefty download. Also, see this article for a more detailed explanation on the size and an alternative workaround to the size problem. Addition: Since answering this question, Scott Hanselman created SmallestDotNet.com, which will determine the smallest required download. Doesn't change the worst case scenario, but is still useful to know.
.NET 3.5 Redistributable -- 200 MB? Other options? I've been using a lot of new.NET 3.5 features in the work that I've been doing, lately. The application that I'm building is intended for distribution among consumers who will probably not have the latest version (or perhaps any version ) of the.NET framework on their machines. I went to go download the.NET 3.5 redistributable package only to find out that it's almost 200 MB! This is unacceptable for my application, because it's supposed to be a quick and painless consumer application that installs quickly and keeps a low profile on the user's machine. For users that have.NET 3.5 already installed, our binary downloads have been instantaneous, so far. This 200 MB gorilla will more than quadruple the size of the download. Is there any other option than this redistributable package that I can use to make sure the framework is on the machine that won't take the user out of our "quick and painless" workflow? Our target time from beginning of download to finalizing the install is less than two minutes. Is it just not possible for someone who doesn't already have.NET installed?
TITLE: .NET 3.5 Redistributable -- 200 MB? Other options? QUESTION: I've been using a lot of new.NET 3.5 features in the work that I've been doing, lately. The application that I'm building is intended for distribution among consumers who will probably not have the latest version (or perhaps any version ) of the.NET framework on their machines. I went to go download the.NET 3.5 redistributable package only to find out that it's almost 200 MB! This is unacceptable for my application, because it's supposed to be a quick and painless consumer application that installs quickly and keeps a low profile on the user's machine. For users that have.NET 3.5 already installed, our binary downloads have been instantaneous, so far. This 200 MB gorilla will more than quadruple the size of the download. Is there any other option than this redistributable package that I can use to make sure the framework is on the machine that won't take the user out of our "quick and painless" workflow? Our target time from beginning of download to finalizing the install is less than two minutes. Is it just not possible for someone who doesn't already have.NET installed? ANSWER: That's one of the sad reasons i'm still targeting.net 2.0 whenever possible:/ But people don't neccessarily need the full 200 MB Package. There is a 3 MB Bootstrapper which will only download the required components:.net 3.5 SP1 Bootstrapper However, the worst case scenario is still a pretty hefty download. Also, see this article for a more detailed explanation on the size and an alternative workaround to the size problem. Addition: Since answering this question, Scott Hanselman created SmallestDotNet.com, which will determine the smallest required download. Doesn't change the worst case scenario, but is still useful to know.
[ ".net", "redistributable" ]
19
21
12,024
6
0
2008-08-08T22:32:01.243000
2008-08-08T22:35:06.417000
6,441
6,868
How can I enable disabled radio buttons?
The following code works great in IE, but not in FF or Safari. I can't for the life of me work out why. The code is supposed to disable radio buttons if you select the "Disable 2 radio buttons" option. It should enable the radio buttons if you select the "Enable both radio buttons" option. These both work... However, if you don't use your mouse to move between the 2 options ("Enable..." and "Disable...") then the radio buttons do not appear to be disabled or enabled correctly, until you click anywhere else on the page (not on the radio buttons themselves). If anyone has time/is curious/feeling helpful, please paste the code below into an html page and load it up in a browser. It works great in IE, but the problem manifests itself in FF (3 in my case) and Safari, all on Windows XP. function SetLocationOptions() { var frmTemp = document.frm; var selTemp = frmTemp.user; if (selTemp.selectedIndex >= 0) { var myOpt = selTemp.options[selTemp.selectedIndex]; if (myOpt.attributes[0].nodeValue == '1') { frmTemp.transfer_to[0].disabled = true; frmTemp.transfer_to[1].disabled = true; frmTemp.transfer_to[2].checked = true; } else { frmTemp.transfer_to[0].disabled = false; frmTemp.transfer_to[1].disabled = false; } } } Choose One Enable both radio buttons Disable 2 radio buttons Premium Other Both
To get FF to mimic IE's behavior when using the keyboard, you can use the keyup event on the select box. In your example (I am not a fan of attaching event handlers this way, but that's another topic), it would be like this:
How can I enable disabled radio buttons? The following code works great in IE, but not in FF or Safari. I can't for the life of me work out why. The code is supposed to disable radio buttons if you select the "Disable 2 radio buttons" option. It should enable the radio buttons if you select the "Enable both radio buttons" option. These both work... However, if you don't use your mouse to move between the 2 options ("Enable..." and "Disable...") then the radio buttons do not appear to be disabled or enabled correctly, until you click anywhere else on the page (not on the radio buttons themselves). If anyone has time/is curious/feeling helpful, please paste the code below into an html page and load it up in a browser. It works great in IE, but the problem manifests itself in FF (3 in my case) and Safari, all on Windows XP. function SetLocationOptions() { var frmTemp = document.frm; var selTemp = frmTemp.user; if (selTemp.selectedIndex >= 0) { var myOpt = selTemp.options[selTemp.selectedIndex]; if (myOpt.attributes[0].nodeValue == '1') { frmTemp.transfer_to[0].disabled = true; frmTemp.transfer_to[1].disabled = true; frmTemp.transfer_to[2].checked = true; } else { frmTemp.transfer_to[0].disabled = false; frmTemp.transfer_to[1].disabled = false; } } } Choose One Enable both radio buttons Disable 2 radio buttons Premium Other Both
TITLE: How can I enable disabled radio buttons? QUESTION: The following code works great in IE, but not in FF or Safari. I can't for the life of me work out why. The code is supposed to disable radio buttons if you select the "Disable 2 radio buttons" option. It should enable the radio buttons if you select the "Enable both radio buttons" option. These both work... However, if you don't use your mouse to move between the 2 options ("Enable..." and "Disable...") then the radio buttons do not appear to be disabled or enabled correctly, until you click anywhere else on the page (not on the radio buttons themselves). If anyone has time/is curious/feeling helpful, please paste the code below into an html page and load it up in a browser. It works great in IE, but the problem manifests itself in FF (3 in my case) and Safari, all on Windows XP. function SetLocationOptions() { var frmTemp = document.frm; var selTemp = frmTemp.user; if (selTemp.selectedIndex >= 0) { var myOpt = selTemp.options[selTemp.selectedIndex]; if (myOpt.attributes[0].nodeValue == '1') { frmTemp.transfer_to[0].disabled = true; frmTemp.transfer_to[1].disabled = true; frmTemp.transfer_to[2].checked = true; } else { frmTemp.transfer_to[0].disabled = false; frmTemp.transfer_to[1].disabled = false; } } } Choose One Enable both radio buttons Disable 2 radio buttons Premium Other Both ANSWER: To get FF to mimic IE's behavior when using the keyboard, you can use the keyup event on the select box. In your example (I am not a fan of attaching event handlers this way, but that's another topic), it would be like this:
[ "javascript", "html", "radio-button" ]
19
6
3,675
3
0
2008-08-08T22:33:19.960000
2008-08-09T18:15:12.900000
6,467
3,125,174
Date arithmetic in Unix shell scripts
I need to do date arithmetic in Unix shell scripts that I use to control the execution of third party programs. I'm using a function to increment a day and another to decrement: IncrementaDia(){ echo $1 | awk ' BEGIN { diasDelMes[1] = 31 diasDelMes[2] = 28 diasDelMes[3] = 31 diasDelMes[4] = 30 diasDelMes[5] = 31 diasDelMes[6] = 30 diasDelMes[7] = 31 diasDelMes[8] = 31 diasDelMes[9] = 30 diasDelMes[10] = 31 diasDelMes[11] = 30 diasDelMes[12] = 31 } { anio=substr($1,1,4) mes=substr($1,5,2) dia=substr($1,7,2) if((anio % 4 == 0 && anio % 100!= 0) || anio % 400 == 0) { diasDelMes[2] = 29; } if( dia == diasDelMes[int(mes)] ) { if( int(mes) == 12 ) { anio = anio + 1 mes = 1 dia = 1 } else { mes = mes + 1 dia = 1 } } else { dia = dia + 1 } } END { printf("%04d%02d%02d", anio, mes, dia) } ' } if [ $# -eq 1 ]; then tomorrow=$1 else today=$(date +"%Y%m%d") tomorrow=$(IncrementaDia $hoy) fi but now I need to do more complex arithmetic. What it's the best and more compatible way to do this?
I have written a bash script for converting dates expressed in English into conventional mm/dd/yyyy dates. It is called ComputeDate. Here are some examples of its use. For brevity I have placed the output of each invocation on the same line as the invocation, separarted by a colon (:). The quotes shown below are not necessary when running ComputeDate: $ ComputeDate 'yesterday': 03/19/2010 $ ComputeDate 'yes': 03/19/2010 $ ComputeDate 'today': 03/20/2010 $ ComputeDate 'tod': 03/20/2010 $ ComputeDate 'now': 03/20/2010 $ ComputeDate 'tomorrow': 03/21/2010 $ ComputeDate 'tom': 03/21/2010 $ ComputeDate '10/29/32': 10/29/2032 $ ComputeDate 'October 29': 10/1/2029 $ ComputeDate 'October 29, 2010': 10/29/2010 $ ComputeDate 'this monday': 'this monday' has passed. Did you mean 'next monday?' $ ComputeDate 'a week after today': 03/27/2010 $ ComputeDate 'this satu': 03/20/2010 $ ComputeDate 'next monday': 03/22/2010 $ ComputeDate 'next thur': 03/25/2010 $ ComputeDate 'mon in 2 weeks': 03/28/2010 $ ComputeDate 'the last day of the month': 03/31/2010 $ ComputeDate 'the last day of feb': 2/28/2010 $ ComputeDate 'the last day of feb 2000': 2/29/2000 $ ComputeDate '1 week from yesterday': 03/26/2010 $ ComputeDate '1 week from today': 03/27/2010 $ ComputeDate '1 week from tomorrow': 03/28/2010 $ ComputeDate '2 weeks from yesterday': 4/2/2010 $ ComputeDate '2 weeks from today': 4/3/2010 $ ComputeDate '2 weeks from tomorrow': 4/4/2010 $ ComputeDate '1 week after the last day of march': 4/7/2010 $ ComputeDate '1 week after next Thursday': 4/1/2010 $ ComputeDate '2 weeks after the last day of march': 4/14/2010 $ ComputeDate '2 weeks after 1 day after the last day of march': 4/15/2010 $ ComputeDate '1 day after the last day of march': 4/1/2010 $ ComputeDate '1 day after 1 day after 1 day after 1 day after today': 03/24/2010 I have included this script as an answer to this problem because it illustrates how to do date arithmetic via a set of bash functions and these functions may prove useful for others. It handles leap years and leap centuries correctly: #! /bin/bash # ConvertDate -- convert a human-readable date to a MM/DD/YY date # # Date::= Month/Day/Year # | Month/Day # | DayOfWeek # | [this|next] DayOfWeek # | DayofWeek [of|in] [Number|next] weeks[s] # | Number [day|week][s] from Date # | the last day of the month # | the last day of Month # # Month::= January | February | March | April | May |... | December # January::= jan | january | 1 # February::= feb | january | 2 #... # December::= dec | december | 12 # Day::= 1 | 2 |... | 31 # DayOfWeek::= today | Sunday | Monday | Tuesday |... | Saturday # Sunday::= sun* #... # Saturday::= sat* # # Number::= Day | a # # Author: Larry Morell if [ $# = 0 ]; then printdirections $0 exit fi # Request the value of a variable GetVar () { Var=$1 echo -n "$Var= [${!Var}]: " local X read X if [! -z $X ]; then eval $Var="$X" fi } IsLeapYear () { local Year=$1 if [ $[20$Year % 4] -eq 0 ]; then echo yes else echo no fi } # AddToDate -- compute another date within the same year DayNames=(mon tue wed thu fri sat sun ) # To correspond with 'date' output Day2Int () { ErrorFlag= case $1 in -e ) ErrorFlag=-e; shift;; esac local dow=$1 n=0 while [ $n -lt 7 -a $dow!= "${DayNames[n]}" ]; do let n++ done if [ -z "$ErrorFlag" -a $n -eq 7 ]; then echo Cannot convert $dow to a numeric day of wee exit fi echo $[n+1] } Months=(31 28 31 30 31 30 31 31 30 31 30 31) MonthNames=(jan feb mar apr may jun jul aug sep oct nov dec) # Returns the month (1-12) from a date, or a month name Month2Int () { ErrorFlag= case $1 in -e ) ErrorFlag=-e; shift;; esac M=$1 Month=${M%%/*} # Remove /... case $Month in [a-z]* ) Month=${Month:0:3} M=0 while [ $M -lt 12 -a ${MonthNames[M]}!= $Month ]; do let M++ done let M++ esac if [ -z "$ErrorFlag" -a $M -gt 12 ]; then echo "'$Month' Is not a valid month." exit fi echo $M } # Retrieve month,day,year from a legal date GetMonth() { echo ${1%%/*} } GetDay() { echo $1 | col / 2 } GetYear() { echo ${1##*/} } AddToDate() { local Date=$1 local days=$2 local Month=`GetMonth $Date` local Day=`echo $Date | col / 2` # Day of Date local Year=`echo $Date | col / 3` # Year of Date local LeapYear=`IsLeapYear $Year` if [ $LeapYear = "yes" ]; then let Months[1]++ fi Day=$[Day+days] while [ $Day -gt ${Months[$Month-1]} ]; do Day=$[Day - ${Months[$Month-1]}] let Month++ done echo "$Month/$Day/$Year" } # Convert a date to normal form NormalizeDate () { Date=`echo "$*" | sed 'sX *X/Xg'` local Day=`date +%d` local Month=`date +%m` local Year=`date +%Y` #echo Normalizing Date=$Date > /dev/tty case $Date in */*/* ) Month=`echo $Date | col / 1 ` Month=`Month2Int $Month` Day=`echo $Date | col / 2` Year=`echo $Date | col / 3`;; */* ) Month=`echo $Date | col / 1 ` Month=`Month2Int $Month` Day=1 Year=`echo $Date | col / 2 `;; [a-z]* ) # Better be a month or day of week Exp=${Date:0:3} case $Exp in jan|feb|mar|apr|may|june|jul|aug|sep|oct|nov|dec ) Month=$Exp Month=`Month2Int $Month` Day=1 #Year stays the same;; mon|tue|wed|thu|fri|sat|sun ) # Compute the next such day local DayOfWeek=`date +%u` D=`Day2Int $Exp` if [ $DayOfWeek -le $D ]; then Date=`AddToDate $Month/$Day/$Year $[D-DayOfWeek]` else Date=`AddToDate $Month/$Day/$Year $[7+D-DayOfWeek]` fi # Reset Month/Day/Year Month=`echo $Date | col / 1 ` Day=`echo $Date | col / 2` Year=`echo $Date | col / 3`;; * ) echo "$Exp is not a valid month or day" exit;; esac;; * ) echo "$Date is not a valid date" exit;; esac case $Day in [0-9]* );; # Day must be numeric * ) echo "$Date is not a valid date" exit;; esac [0-9][0-9][0-9][0-9] );; # Year must be 4 digits [0-9][0-9] ) Year=20$Year;; esac Date=$Month/$Day/$Year echo $Date } # NormalizeDate jan # NormalizeDate january # NormalizeDate jan 2009 # NormalizeDate jan 22 1983 # NormalizeDate 1/22 # NormalizeDate 1 22 # NormalizeDate sat # NormalizeDate sun # NormalizeDate mon ComputeExtension () { local Date=$1; shift local Month=`GetMonth $Date` local Day=`echo $Date | col / 2` local Year=`echo $Date | col / 3` local ExtensionExp="$*" case $ExtensionExp in *w*d* ) # like 5 weeks 3 days or even 5w2d ExtensionExp=`echo $ExtensionExp | sed 's/[a-z]/ /g'` weeks=`echo $ExtensionExp | col 1` days=`echo $ExtensionExp | col 2` days=$[7*weeks+days] Due=`AddToDate $Month/$Day/$Year $days`;; *d ) # Like 5 days or 5d ExtensionExp=`echo $ExtensionExp | sed 's/[a-z]/ /g'` days=$ExtensionExp Due=`AddToDate $Month/$Day/$Year $days`;; * ) Due=$ExtensionExp;; esac echo $Due } # Pop -- remove the first element from an array and shift left Pop () { Var=$1 eval "unset $Var[0]" eval "$Var=(\${$Var[*]})" } ComputeDate () { local Date=`NormalizeDate $1`; shift local Expression=`echo $* | sed 's/^ *a /1 /;s/,/ /' | tr A-Z a-z ` local Exp=(`echo $Expression `) local Token=$Exp # first one local Ans= #echo "Computing date for ${Exp[*]}" > /dev/tty case $Token in */* ) # Regular date M=`GetMonth $Token` D=`GetDay $Token` Y=`GetYear $Token` if [ -z "$Y" ]; then Y=$Year elif [ ${#Y} -eq 2 ]; then Y=20$Y fi Ans="$M/$D/$Y";; yes* ) Ans=`AddToDate $Date -1`;; tod*|now ) Ans=$Date;; tom* ) Ans=`AddToDate $Date 1`;; the ) case $Expression in *day*after* ) #the day after Date Pop Exp; # Skip the Pop Exp; # Skip day Pop Exp; # Skip after #echo Calling ComputeDate $Date ${Exp[*]} > /dev/tty Date=`ComputeDate $Date ${Exp[*]}` #Recursive call #echo "New date is " $Date > /dev/tty Ans=`AddToDate $Date 1`;; *last*day*of*th*month|*end*of*th*month ) M=`date +%m` Day=${Months[M-1]} if [ $M -eq 2 -a `IsLeapYear $Year` = yes ]; then let Day++ fi Ans=$Month/$Day/$Year;; *last*day*of* ) D=${Expression##*of } D=`NormalizeDate $D` M=`GetMonth $D` Y=`GetYear $D` # echo M is $M > /dev/tty Day=${Months[M-1]} if [ $M -eq 2 -a `IsLeapYear $Y` = yes ]; then let Day++ fi Ans=$[M]/$Day/$Y;; * ) echo "Unknown expression: " $Expression exit;; esac;; next* ) # next DayOfWeek Pop Exp dow=`Day2Int $DayOfWeek` # First 3 chars tdow=`Day2Int ${Exp:0:3}` # First 3 chars n=$[7-dow+tdow] Ans=`AddToDate $Date $n`;; this* ) Pop Exp dow=`Day2Int $DayOfWeek` tdow=`Day2Int ${Exp:0:3}` # First 3 chars if [ $dow -gt $tdow ]; then echo "'this $Exp' has passed. Did you mean 'next $Exp?'" exit fi n=$[tdow-dow] Ans=`AddToDate $Date $n`;; [a-z]* ) # DayOfWeek... M=${Exp:0:3} case $M in jan|feb|mar|apr|may|june|jul|aug|sep|oct|nov|dec ) ND=`NormalizeDate ${Exp[*]}` Ans=$ND;; mon|tue|wed|thu|fri|sat|sun ) dow=`Day2Int $DayOfWeek` Ans=`NormalizeDate $Exp` if [ ${#Exp[*]} -gt 1 ]; then # Just a DayOfWeek #tdow=`GetDay $Exp` # First 3 chars #if [ $dow -gt $tdow ]; then #echo "'this $Exp' has passed. Did you mean 'next $Exp'?" #exit #fi #n=$[tdow-dow] #else # DayOfWeek in a future week Pop Exp # toss monday Pop Exp # toss in/off if [ $Exp = next ]; then Exp=2 fi n=$[7*(Exp-1)] # number of weeks n=$[n+7-dow+tdow] Ans=`AddToDate $Date $n` fi;; esac;; [0-9]* ) # Number weeks [from|after] Date n=$Exp Pop Exp; case $Exp in w* ) let n=7*n;; esac Pop Exp; Pop Exp #echo Calling ComputeDate $Date ${Exp[*]} > /dev/tty Date=`ComputeDate $Date ${Exp[*]}` #Recursive call #echo "New date is " $Date > /dev/tty Ans=`AddToDate $Date $n`;; esac echo $Ans } Year=`date +%Y` Month=`date +%m` Day=`date +%d` DayOfWeek=`date +%a |tr A-Z a-z` Date="$Month/$Day/$Year" ComputeDate $Date $* This script makes extensive use of another script I wrote (called col... many apologies to those who use the standard col supplied with Linux). This version of col simplifies extracting columns from the stdin. Thus, $ echo a b c d e | col 5 3 2 prints e c b Here it the col script: #!/bin/sh # col -- extract columns from a file # Usage: # col [-r] [c] col-1 col-2... # where [c] if supplied defines the field separator # where each col-i represents a column interpreted according to the presence of -r as follows: # -r present: counting starts from the right end of the line # -r absent: counting starts from the left side of the line Separator=" " Reverse=false case "$1" in -r ) Reverse=true; shift;;; [0-9]* );; * )Separator="$1"; shift;;; esac case "$1" in -r ) Reverse=true; shift;;; [0-9]* );; * )Separator="$1"; shift;;; esac # Replace each col-i with $i Cols="" for f in $* do if [ $Reverse = true ]; then Cols="$Cols \$(NF-$f+1)," else Cols="$Cols \$$f," fi done Cols=`echo "$Cols" | sed 's/,$//'` #echo "Using column specifications of $Cols" awk -F "$Separator" "{print $Cols}" It also uses printdirections for printing out directions when the script is invoked improperly: #!/bin/sh # # printdirections -- print header lines of a shell script # # Usage: # printdirections path # where # path is a *full* path to the shell script in question # beginning with '/' # # To use printdirections, you must include (as comments at the top # of your shell script) documentation for running the shell script. if [ $# -eq 0 -o "$*" = "-h" ]; then printdirections $0 exit fi # Delete the command invocation at the top of the file, if any # Delete from the place where printdirections occurs to the end of the file # Remove the # comments # There is a bizarre oddity here. sed '/#!/d;/.*printdirections/,$d;/ *#/!d;s/# //;s/#//' $1 > /tmp/printdirections.$$ # Count the number of lines numlines=`wc -l /tmp/printdirections.$$ | awk '{print $1}'` # Remove the last line numlines=`expr $numlines - 1` head -n $numlines /tmp/printdirections.$$ rm /tmp/printdirections.$$ To use this place the three scripts in the files ComputeDate, col, and printdirections, respectively. Place the file in directory named by your PATH, typically, ~/bin. Then make them executable with: $ chmod a+x ComputeDate col printdirections Problems? Send me some emaiL: morell AT cs.atu.edu Place ComputeDate in the subject.
Date arithmetic in Unix shell scripts I need to do date arithmetic in Unix shell scripts that I use to control the execution of third party programs. I'm using a function to increment a day and another to decrement: IncrementaDia(){ echo $1 | awk ' BEGIN { diasDelMes[1] = 31 diasDelMes[2] = 28 diasDelMes[3] = 31 diasDelMes[4] = 30 diasDelMes[5] = 31 diasDelMes[6] = 30 diasDelMes[7] = 31 diasDelMes[8] = 31 diasDelMes[9] = 30 diasDelMes[10] = 31 diasDelMes[11] = 30 diasDelMes[12] = 31 } { anio=substr($1,1,4) mes=substr($1,5,2) dia=substr($1,7,2) if((anio % 4 == 0 && anio % 100!= 0) || anio % 400 == 0) { diasDelMes[2] = 29; } if( dia == diasDelMes[int(mes)] ) { if( int(mes) == 12 ) { anio = anio + 1 mes = 1 dia = 1 } else { mes = mes + 1 dia = 1 } } else { dia = dia + 1 } } END { printf("%04d%02d%02d", anio, mes, dia) } ' } if [ $# -eq 1 ]; then tomorrow=$1 else today=$(date +"%Y%m%d") tomorrow=$(IncrementaDia $hoy) fi but now I need to do more complex arithmetic. What it's the best and more compatible way to do this?
TITLE: Date arithmetic in Unix shell scripts QUESTION: I need to do date arithmetic in Unix shell scripts that I use to control the execution of third party programs. I'm using a function to increment a day and another to decrement: IncrementaDia(){ echo $1 | awk ' BEGIN { diasDelMes[1] = 31 diasDelMes[2] = 28 diasDelMes[3] = 31 diasDelMes[4] = 30 diasDelMes[5] = 31 diasDelMes[6] = 30 diasDelMes[7] = 31 diasDelMes[8] = 31 diasDelMes[9] = 30 diasDelMes[10] = 31 diasDelMes[11] = 30 diasDelMes[12] = 31 } { anio=substr($1,1,4) mes=substr($1,5,2) dia=substr($1,7,2) if((anio % 4 == 0 && anio % 100!= 0) || anio % 400 == 0) { diasDelMes[2] = 29; } if( dia == diasDelMes[int(mes)] ) { if( int(mes) == 12 ) { anio = anio + 1 mes = 1 dia = 1 } else { mes = mes + 1 dia = 1 } } else { dia = dia + 1 } } END { printf("%04d%02d%02d", anio, mes, dia) } ' } if [ $# -eq 1 ]; then tomorrow=$1 else today=$(date +"%Y%m%d") tomorrow=$(IncrementaDia $hoy) fi but now I need to do more complex arithmetic. What it's the best and more compatible way to do this? ANSWER: I have written a bash script for converting dates expressed in English into conventional mm/dd/yyyy dates. It is called ComputeDate. Here are some examples of its use. For brevity I have placed the output of each invocation on the same line as the invocation, separarted by a colon (:). The quotes shown below are not necessary when running ComputeDate: $ ComputeDate 'yesterday': 03/19/2010 $ ComputeDate 'yes': 03/19/2010 $ ComputeDate 'today': 03/20/2010 $ ComputeDate 'tod': 03/20/2010 $ ComputeDate 'now': 03/20/2010 $ ComputeDate 'tomorrow': 03/21/2010 $ ComputeDate 'tom': 03/21/2010 $ ComputeDate '10/29/32': 10/29/2032 $ ComputeDate 'October 29': 10/1/2029 $ ComputeDate 'October 29, 2010': 10/29/2010 $ ComputeDate 'this monday': 'this monday' has passed. Did you mean 'next monday?' $ ComputeDate 'a week after today': 03/27/2010 $ ComputeDate 'this satu': 03/20/2010 $ ComputeDate 'next monday': 03/22/2010 $ ComputeDate 'next thur': 03/25/2010 $ ComputeDate 'mon in 2 weeks': 03/28/2010 $ ComputeDate 'the last day of the month': 03/31/2010 $ ComputeDate 'the last day of feb': 2/28/2010 $ ComputeDate 'the last day of feb 2000': 2/29/2000 $ ComputeDate '1 week from yesterday': 03/26/2010 $ ComputeDate '1 week from today': 03/27/2010 $ ComputeDate '1 week from tomorrow': 03/28/2010 $ ComputeDate '2 weeks from yesterday': 4/2/2010 $ ComputeDate '2 weeks from today': 4/3/2010 $ ComputeDate '2 weeks from tomorrow': 4/4/2010 $ ComputeDate '1 week after the last day of march': 4/7/2010 $ ComputeDate '1 week after next Thursday': 4/1/2010 $ ComputeDate '2 weeks after the last day of march': 4/14/2010 $ ComputeDate '2 weeks after 1 day after the last day of march': 4/15/2010 $ ComputeDate '1 day after the last day of march': 4/1/2010 $ ComputeDate '1 day after 1 day after 1 day after 1 day after today': 03/24/2010 I have included this script as an answer to this problem because it illustrates how to do date arithmetic via a set of bash functions and these functions may prove useful for others. It handles leap years and leap centuries correctly: #! /bin/bash # ConvertDate -- convert a human-readable date to a MM/DD/YY date # # Date::= Month/Day/Year # | Month/Day # | DayOfWeek # | [this|next] DayOfWeek # | DayofWeek [of|in] [Number|next] weeks[s] # | Number [day|week][s] from Date # | the last day of the month # | the last day of Month # # Month::= January | February | March | April | May |... | December # January::= jan | january | 1 # February::= feb | january | 2 #... # December::= dec | december | 12 # Day::= 1 | 2 |... | 31 # DayOfWeek::= today | Sunday | Monday | Tuesday |... | Saturday # Sunday::= sun* #... # Saturday::= sat* # # Number::= Day | a # # Author: Larry Morell if [ $# = 0 ]; then printdirections $0 exit fi # Request the value of a variable GetVar () { Var=$1 echo -n "$Var= [${!Var}]: " local X read X if [! -z $X ]; then eval $Var="$X" fi } IsLeapYear () { local Year=$1 if [ $[20$Year % 4] -eq 0 ]; then echo yes else echo no fi } # AddToDate -- compute another date within the same year DayNames=(mon tue wed thu fri sat sun ) # To correspond with 'date' output Day2Int () { ErrorFlag= case $1 in -e ) ErrorFlag=-e; shift;; esac local dow=$1 n=0 while [ $n -lt 7 -a $dow!= "${DayNames[n]}" ]; do let n++ done if [ -z "$ErrorFlag" -a $n -eq 7 ]; then echo Cannot convert $dow to a numeric day of wee exit fi echo $[n+1] } Months=(31 28 31 30 31 30 31 31 30 31 30 31) MonthNames=(jan feb mar apr may jun jul aug sep oct nov dec) # Returns the month (1-12) from a date, or a month name Month2Int () { ErrorFlag= case $1 in -e ) ErrorFlag=-e; shift;; esac M=$1 Month=${M%%/*} # Remove /... case $Month in [a-z]* ) Month=${Month:0:3} M=0 while [ $M -lt 12 -a ${MonthNames[M]}!= $Month ]; do let M++ done let M++ esac if [ -z "$ErrorFlag" -a $M -gt 12 ]; then echo "'$Month' Is not a valid month." exit fi echo $M } # Retrieve month,day,year from a legal date GetMonth() { echo ${1%%/*} } GetDay() { echo $1 | col / 2 } GetYear() { echo ${1##*/} } AddToDate() { local Date=$1 local days=$2 local Month=`GetMonth $Date` local Day=`echo $Date | col / 2` # Day of Date local Year=`echo $Date | col / 3` # Year of Date local LeapYear=`IsLeapYear $Year` if [ $LeapYear = "yes" ]; then let Months[1]++ fi Day=$[Day+days] while [ $Day -gt ${Months[$Month-1]} ]; do Day=$[Day - ${Months[$Month-1]}] let Month++ done echo "$Month/$Day/$Year" } # Convert a date to normal form NormalizeDate () { Date=`echo "$*" | sed 'sX *X/Xg'` local Day=`date +%d` local Month=`date +%m` local Year=`date +%Y` #echo Normalizing Date=$Date > /dev/tty case $Date in */*/* ) Month=`echo $Date | col / 1 ` Month=`Month2Int $Month` Day=`echo $Date | col / 2` Year=`echo $Date | col / 3`;; */* ) Month=`echo $Date | col / 1 ` Month=`Month2Int $Month` Day=1 Year=`echo $Date | col / 2 `;; [a-z]* ) # Better be a month or day of week Exp=${Date:0:3} case $Exp in jan|feb|mar|apr|may|june|jul|aug|sep|oct|nov|dec ) Month=$Exp Month=`Month2Int $Month` Day=1 #Year stays the same;; mon|tue|wed|thu|fri|sat|sun ) # Compute the next such day local DayOfWeek=`date +%u` D=`Day2Int $Exp` if [ $DayOfWeek -le $D ]; then Date=`AddToDate $Month/$Day/$Year $[D-DayOfWeek]` else Date=`AddToDate $Month/$Day/$Year $[7+D-DayOfWeek]` fi # Reset Month/Day/Year Month=`echo $Date | col / 1 ` Day=`echo $Date | col / 2` Year=`echo $Date | col / 3`;; * ) echo "$Exp is not a valid month or day" exit;; esac;; * ) echo "$Date is not a valid date" exit;; esac case $Day in [0-9]* );; # Day must be numeric * ) echo "$Date is not a valid date" exit;; esac [0-9][0-9][0-9][0-9] );; # Year must be 4 digits [0-9][0-9] ) Year=20$Year;; esac Date=$Month/$Day/$Year echo $Date } # NormalizeDate jan # NormalizeDate january # NormalizeDate jan 2009 # NormalizeDate jan 22 1983 # NormalizeDate 1/22 # NormalizeDate 1 22 # NormalizeDate sat # NormalizeDate sun # NormalizeDate mon ComputeExtension () { local Date=$1; shift local Month=`GetMonth $Date` local Day=`echo $Date | col / 2` local Year=`echo $Date | col / 3` local ExtensionExp="$*" case $ExtensionExp in *w*d* ) # like 5 weeks 3 days or even 5w2d ExtensionExp=`echo $ExtensionExp | sed 's/[a-z]/ /g'` weeks=`echo $ExtensionExp | col 1` days=`echo $ExtensionExp | col 2` days=$[7*weeks+days] Due=`AddToDate $Month/$Day/$Year $days`;; *d ) # Like 5 days or 5d ExtensionExp=`echo $ExtensionExp | sed 's/[a-z]/ /g'` days=$ExtensionExp Due=`AddToDate $Month/$Day/$Year $days`;; * ) Due=$ExtensionExp;; esac echo $Due } # Pop -- remove the first element from an array and shift left Pop () { Var=$1 eval "unset $Var[0]" eval "$Var=(\${$Var[*]})" } ComputeDate () { local Date=`NormalizeDate $1`; shift local Expression=`echo $* | sed 's/^ *a /1 /;s/,/ /' | tr A-Z a-z ` local Exp=(`echo $Expression `) local Token=$Exp # first one local Ans= #echo "Computing date for ${Exp[*]}" > /dev/tty case $Token in */* ) # Regular date M=`GetMonth $Token` D=`GetDay $Token` Y=`GetYear $Token` if [ -z "$Y" ]; then Y=$Year elif [ ${#Y} -eq 2 ]; then Y=20$Y fi Ans="$M/$D/$Y";; yes* ) Ans=`AddToDate $Date -1`;; tod*|now ) Ans=$Date;; tom* ) Ans=`AddToDate $Date 1`;; the ) case $Expression in *day*after* ) #the day after Date Pop Exp; # Skip the Pop Exp; # Skip day Pop Exp; # Skip after #echo Calling ComputeDate $Date ${Exp[*]} > /dev/tty Date=`ComputeDate $Date ${Exp[*]}` #Recursive call #echo "New date is " $Date > /dev/tty Ans=`AddToDate $Date 1`;; *last*day*of*th*month|*end*of*th*month ) M=`date +%m` Day=${Months[M-1]} if [ $M -eq 2 -a `IsLeapYear $Year` = yes ]; then let Day++ fi Ans=$Month/$Day/$Year;; *last*day*of* ) D=${Expression##*of } D=`NormalizeDate $D` M=`GetMonth $D` Y=`GetYear $D` # echo M is $M > /dev/tty Day=${Months[M-1]} if [ $M -eq 2 -a `IsLeapYear $Y` = yes ]; then let Day++ fi Ans=$[M]/$Day/$Y;; * ) echo "Unknown expression: " $Expression exit;; esac;; next* ) # next DayOfWeek Pop Exp dow=`Day2Int $DayOfWeek` # First 3 chars tdow=`Day2Int ${Exp:0:3}` # First 3 chars n=$[7-dow+tdow] Ans=`AddToDate $Date $n`;; this* ) Pop Exp dow=`Day2Int $DayOfWeek` tdow=`Day2Int ${Exp:0:3}` # First 3 chars if [ $dow -gt $tdow ]; then echo "'this $Exp' has passed. Did you mean 'next $Exp?'" exit fi n=$[tdow-dow] Ans=`AddToDate $Date $n`;; [a-z]* ) # DayOfWeek... M=${Exp:0:3} case $M in jan|feb|mar|apr|may|june|jul|aug|sep|oct|nov|dec ) ND=`NormalizeDate ${Exp[*]}` Ans=$ND;; mon|tue|wed|thu|fri|sat|sun ) dow=`Day2Int $DayOfWeek` Ans=`NormalizeDate $Exp` if [ ${#Exp[*]} -gt 1 ]; then # Just a DayOfWeek #tdow=`GetDay $Exp` # First 3 chars #if [ $dow -gt $tdow ]; then #echo "'this $Exp' has passed. Did you mean 'next $Exp'?" #exit #fi #n=$[tdow-dow] #else # DayOfWeek in a future week Pop Exp # toss monday Pop Exp # toss in/off if [ $Exp = next ]; then Exp=2 fi n=$[7*(Exp-1)] # number of weeks n=$[n+7-dow+tdow] Ans=`AddToDate $Date $n` fi;; esac;; [0-9]* ) # Number weeks [from|after] Date n=$Exp Pop Exp; case $Exp in w* ) let n=7*n;; esac Pop Exp; Pop Exp #echo Calling ComputeDate $Date ${Exp[*]} > /dev/tty Date=`ComputeDate $Date ${Exp[*]}` #Recursive call #echo "New date is " $Date > /dev/tty Ans=`AddToDate $Date $n`;; esac echo $Ans } Year=`date +%Y` Month=`date +%m` Day=`date +%d` DayOfWeek=`date +%a |tr A-Z a-z` Date="$Month/$Day/$Year" ComputeDate $Date $* This script makes extensive use of another script I wrote (called col... many apologies to those who use the standard col supplied with Linux). This version of col simplifies extracting columns from the stdin. Thus, $ echo a b c d e | col 5 3 2 prints e c b Here it the col script: #!/bin/sh # col -- extract columns from a file # Usage: # col [-r] [c] col-1 col-2... # where [c] if supplied defines the field separator # where each col-i represents a column interpreted according to the presence of -r as follows: # -r present: counting starts from the right end of the line # -r absent: counting starts from the left side of the line Separator=" " Reverse=false case "$1" in -r ) Reverse=true; shift;;; [0-9]* );; * )Separator="$1"; shift;;; esac case "$1" in -r ) Reverse=true; shift;;; [0-9]* );; * )Separator="$1"; shift;;; esac # Replace each col-i with $i Cols="" for f in $* do if [ $Reverse = true ]; then Cols="$Cols \$(NF-$f+1)," else Cols="$Cols \$$f," fi done Cols=`echo "$Cols" | sed 's/,$//'` #echo "Using column specifications of $Cols" awk -F "$Separator" "{print $Cols}" It also uses printdirections for printing out directions when the script is invoked improperly: #!/bin/sh # # printdirections -- print header lines of a shell script # # Usage: # printdirections path # where # path is a *full* path to the shell script in question # beginning with '/' # # To use printdirections, you must include (as comments at the top # of your shell script) documentation for running the shell script. if [ $# -eq 0 -o "$*" = "-h" ]; then printdirections $0 exit fi # Delete the command invocation at the top of the file, if any # Delete from the place where printdirections occurs to the end of the file # Remove the # comments # There is a bizarre oddity here. sed '/#!/d;/.*printdirections/,$d;/ *#/!d;s/# //;s/#//' $1 > /tmp/printdirections.$$ # Count the number of lines numlines=`wc -l /tmp/printdirections.$$ | awk '{print $1}'` # Remove the last line numlines=`expr $numlines - 1` head -n $numlines /tmp/printdirections.$$ rm /tmp/printdirections.$$ To use this place the three scripts in the files ComputeDate, col, and printdirections, respectively. Place the file in directory named by your PATH, typically, ~/bin. Then make them executable with: $ chmod a+x ComputeDate col printdirections Problems? Send me some emaiL: morell AT cs.atu.edu Place ComputeDate in the subject.
[ "unix", "shell", "date", "math", "scripting" ]
24
17
80,147
13
0
2008-08-08T23:24:02.933000
2010-06-26T19:04:41.087000
6,484
6,716
How do you mock a Sealed class?
Mocking sealed classes can be quite a pain. I currently favor an Adapter pattern to handle this, but something about just keeps feels weird. So, What is the best way you mock sealed classes? Java answers are more than welcome. In fact, I would anticipate that the Java community has been dealing with this longer and has a great deal to offer. But here are some of the.NET opinions: Why Duck Typing Matters for C# Develoepers Creating wrappers for sealed and other types for mocking Unit tests for WCF (and Moq)
My general rule of thumb is that objects that I need to mock should have a common interface too. I think this is right design-wise and makes tests a lot easier (and is usually what you get if you do TDD). More about this can be read in the Google Testing Blog latest post (See point 9). Also, I've been working mainly in Java in the past 4 years and I can say that I can count on one hand the number of times I've created a final (sealed) class. Another rule here is I should always have a good reason to seal a class, as opposed to sealing it by default.
How do you mock a Sealed class? Mocking sealed classes can be quite a pain. I currently favor an Adapter pattern to handle this, but something about just keeps feels weird. So, What is the best way you mock sealed classes? Java answers are more than welcome. In fact, I would anticipate that the Java community has been dealing with this longer and has a great deal to offer. But here are some of the.NET opinions: Why Duck Typing Matters for C# Develoepers Creating wrappers for sealed and other types for mocking Unit tests for WCF (and Moq)
TITLE: How do you mock a Sealed class? QUESTION: Mocking sealed classes can be quite a pain. I currently favor an Adapter pattern to handle this, but something about just keeps feels weird. So, What is the best way you mock sealed classes? Java answers are more than welcome. In fact, I would anticipate that the Java community has been dealing with this longer and has a great deal to offer. But here are some of the.NET opinions: Why Duck Typing Matters for C# Develoepers Creating wrappers for sealed and other types for mocking Unit tests for WCF (and Moq) ANSWER: My general rule of thumb is that objects that I need to mock should have a common interface too. I think this is right design-wise and makes tests a lot easier (and is usually what you get if you do TDD). More about this can be read in the Google Testing Blog latest post (See point 9). Also, I've been working mainly in Java in the past 4 years and I can say that I can count on one hand the number of times I've created a final (sealed) class. Another rule here is I should always have a good reason to seal a class, as opposed to sealing it by default.
[ "unit-testing", "language-agnostic", "tdd", "mocking" ]
78
14
59,907
10
0
2008-08-09T00:14:22.143000
2008-08-09T09:40:37.727000
6,499
6,531
What style do you use for creating a "class"?
There are a few ways to get class-like behavior in javascript, the most common seem to be prototype based like this: function Vector(x, y, x) { this.x = x; this.y = y; this.z = z; return this; } Vector.prototype.length = function () { return Math.sqrt(this.x * this.x... ); } and closure based approaches similar to function Vector(x, y, z) { this.length = function() { return Math.sqrt(x * x +...); } } For various reasons the latter is faster, but I've seen (and I frequently do write) the prototype version and was curious as to what other people do.
Assigning functions to the prototype is better (for public methods) because all instances of the class will share the same copy of the method. If you assign the function inside the constructor as in the second example, every time you create a new instance, the constructor creates a new copy of the length function and assigns it to just that one instance. However this latter technique is useful if you want each copy to have it's own copy, the main use of that being to do private/privileges methods which have access to private variables declared inside the constructor and inherited via the closure mechanism. Douglas Crockford has a good summary.
What style do you use for creating a "class"? There are a few ways to get class-like behavior in javascript, the most common seem to be prototype based like this: function Vector(x, y, x) { this.x = x; this.y = y; this.z = z; return this; } Vector.prototype.length = function () { return Math.sqrt(this.x * this.x... ); } and closure based approaches similar to function Vector(x, y, z) { this.length = function() { return Math.sqrt(x * x +...); } } For various reasons the latter is faster, but I've seen (and I frequently do write) the prototype version and was curious as to what other people do.
TITLE: What style do you use for creating a "class"? QUESTION: There are a few ways to get class-like behavior in javascript, the most common seem to be prototype based like this: function Vector(x, y, x) { this.x = x; this.y = y; this.z = z; return this; } Vector.prototype.length = function () { return Math.sqrt(this.x * this.x... ); } and closure based approaches similar to function Vector(x, y, z) { this.length = function() { return Math.sqrt(x * x +...); } } For various reasons the latter is faster, but I've seen (and I frequently do write) the prototype version and was curious as to what other people do. ANSWER: Assigning functions to the prototype is better (for public methods) because all instances of the class will share the same copy of the method. If you assign the function inside the constructor as in the second example, every time you create a new instance, the constructor creates a new copy of the length function and assigns it to just that one instance. However this latter technique is useful if you want each copy to have it's own copy, the main use of that being to do private/privileges methods which have access to private variables declared inside the constructor and inherited via the closure mechanism. Douglas Crockford has a good summary.
[ "javascript" ]
24
12
1,037
7
0
2008-08-09T00:56:15.040000
2008-08-09T02:05:33.840000
6,512
6,566
How to implement continuations?
I'm working on a Scheme interpreter written in C. Currently it uses the C runtime stack as its own stack, which is presenting a minor problem with implementing continuations. My current solution is manual copying of the C stack to the heap then copying it back when needed. Aside from not being standard C, this solution is hardly ideal. What is the simplest way to implement continuations for Scheme in C?
I remember reading an article that may be of help to you: Cheney on the M.T.A.:-) Some implementations of Scheme I know of, such as SISC, allocate their call frames on the heap. @ollie: You don't need to do the hoisting if all your call frames are on the heap. There's a tradeoff in performance, of course: the time to hoist, versus the overhead required to allocate all frames on the heap. Maybe it should be a tunable runtime parameter in the interpreter.:-P
How to implement continuations? I'm working on a Scheme interpreter written in C. Currently it uses the C runtime stack as its own stack, which is presenting a minor problem with implementing continuations. My current solution is manual copying of the C stack to the heap then copying it back when needed. Aside from not being standard C, this solution is hardly ideal. What is the simplest way to implement continuations for Scheme in C?
TITLE: How to implement continuations? QUESTION: I'm working on a Scheme interpreter written in C. Currently it uses the C runtime stack as its own stack, which is presenting a minor problem with implementing continuations. My current solution is manual copying of the C stack to the heap then copying it back when needed. Aside from not being standard C, this solution is hardly ideal. What is the simplest way to implement continuations for Scheme in C? ANSWER: I remember reading an article that may be of help to you: Cheney on the M.T.A.:-) Some implementations of Scheme I know of, such as SISC, allocate their call frames on the heap. @ollie: You don't need to do the hoisting if all your call frames are on the heap. There's a tradeoff in performance, of course: the time to hoist, versus the overhead required to allocate all frames on the heap. Maybe it should be a tunable runtime parameter in the interpreter.:-P
[ "c", "lisp", "scheme", "continuations" ]
54
19
10,784
12
0
2008-08-09T01:18:37.943000
2008-08-09T02:49:25.903000
6,530
6,534
Where should I put my log file for an asp.net application?
I have a ASP.NET application that we've written our own logging module for. My question is, where is the standard place to write a log file to? I.e. the website will be running as the anonymous user identity (e.g. IUSR on IIS7) and I need a place where I know it'll have permission to write to. Cheers,
App_Data folder on the root of the project. It isn't served to web requests; so other people can't snoop for it.
Where should I put my log file for an asp.net application? I have a ASP.NET application that we've written our own logging module for. My question is, where is the standard place to write a log file to? I.e. the website will be running as the anonymous user identity (e.g. IUSR on IIS7) and I need a place where I know it'll have permission to write to. Cheers,
TITLE: Where should I put my log file for an asp.net application? QUESTION: I have a ASP.NET application that we've written our own logging module for. My question is, where is the standard place to write a log file to? I.e. the website will be running as the anonymous user identity (e.g. IUSR on IIS7) and I need a place where I know it'll have permission to write to. Cheers, ANSWER: App_Data folder on the root of the project. It isn't served to web requests; so other people can't snoop for it.
[ "asp.net", "logging", "permissions" ]
11
7
4,696
6
0
2008-08-09T02:03:52.033000
2008-08-09T02:10:12.800000
6,547
6,565
Two marbles and a 100 story building
One of those classic programming interview questions... You are given two marbles, and told that they will break when dropped from some certain height (and presumably suffer no damage if dropped from below that height). You’re then taken to a 100 story building (presumably higher than the certain height), and asked to find the highest floor your can drop a marble from without breaking it as efficiently as possible. Extra info You must find the correct floor (not a possible range) The marbles are both guaranteed to break at the same floor Assume it takes zero time for you to change floors - only the number of marble drops counts Assume the correct floor is randomly distributed in the building
The interesting thing here is how you can do it in the least amount of drops possible. Going to the 50th floor and dropping the first would be disastrous if the breaking floor is the 49th, resulting in us having to do 50 drops. We should drop the first marble at floor n, where n is the max amount of drops required. If the marble breaks at floor n, we may have to make n-1 drops after that. If the marble doesn't break we go up to floor 2n-1 and if it breaks here we have to drop the second marble n-2 times in the worst case. We continue like this up to the 100th floor and try to break it at 3n-2, 4n-3.... and n+(n-1)+(n-2)+...1 <=100 n=14 Is the maximum drops required
Two marbles and a 100 story building One of those classic programming interview questions... You are given two marbles, and told that they will break when dropped from some certain height (and presumably suffer no damage if dropped from below that height). You’re then taken to a 100 story building (presumably higher than the certain height), and asked to find the highest floor your can drop a marble from without breaking it as efficiently as possible. Extra info You must find the correct floor (not a possible range) The marbles are both guaranteed to break at the same floor Assume it takes zero time for you to change floors - only the number of marble drops counts Assume the correct floor is randomly distributed in the building
TITLE: Two marbles and a 100 story building QUESTION: One of those classic programming interview questions... You are given two marbles, and told that they will break when dropped from some certain height (and presumably suffer no damage if dropped from below that height). You’re then taken to a 100 story building (presumably higher than the certain height), and asked to find the highest floor your can drop a marble from without breaking it as efficiently as possible. Extra info You must find the correct floor (not a possible range) The marbles are both guaranteed to break at the same floor Assume it takes zero time for you to change floors - only the number of marble drops counts Assume the correct floor is randomly distributed in the building ANSWER: The interesting thing here is how you can do it in the least amount of drops possible. Going to the 50th floor and dropping the first would be disastrous if the breaking floor is the 49th, resulting in us having to do 50 drops. We should drop the first marble at floor n, where n is the max amount of drops required. If the marble breaks at floor n, we may have to make n-1 drops after that. If the marble doesn't break we go up to floor 2n-1 and if it breaks here we have to drop the second marble n-2 times in the worst case. We continue like this up to the 100th floor and try to break it at 3n-2, 4n-3.... and n+(n-1)+(n-2)+...1 <=100 n=14 Is the maximum drops required
[ "algorithm", "puzzle" ]
40
55
21,719
10
0
2008-08-09T02:23:27.890000
2008-08-09T02:45:43.070000
6,557
6,567
In C#, why can't a List<string> object be stored in a List<object> variable
It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way. List sl = new List (); List ol; ol = sl; results in Cannot implicitly convert type System.Collections.Generic.List to System.Collections.Generic.List And then... List sl = new List (); List ol; ol = (List )sl; results in Cannot convert type System.Collections.Generic.List to System.Collections.Generic.List Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.
Think of it this way, if you were to do such a cast, and then add an object of type Foo to the list, the list of strings is no longer consistent. If you were to iterate the first reference, you would get a class cast exception because once you hit the Foo instance, the Foo could not be converted to string! As a side note, I think it would be more significant whether or not you can do the reverse cast: List ol = new List (); List sl; sl = (List )ol; I haven't used C# in a while, so I don't know if that is legal, but that sort of cast is actually (potentially) useful. In this case, you are going from a more general class (object) to a more specific class (string) that extends from the general one. In this way, if you add to the list of strings, you are not violating the list of objects. Does anybody know or can test if such a cast is legal in C#?
In C#, why can't a List<string> object be stored in a List<object> variable It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way. List sl = new List (); List ol; ol = sl; results in Cannot implicitly convert type System.Collections.Generic.List to System.Collections.Generic.List And then... List sl = new List (); List ol; ol = (List )sl; results in Cannot convert type System.Collections.Generic.List to System.Collections.Generic.List Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.
TITLE: In C#, why can't a List<string> object be stored in a List<object> variable QUESTION: It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way. List sl = new List (); List ol; ol = sl; results in Cannot implicitly convert type System.Collections.Generic.List to System.Collections.Generic.List And then... List sl = new List (); List ol; ol = (List )sl; results in Cannot convert type System.Collections.Generic.List to System.Collections.Generic.List Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution. ANSWER: Think of it this way, if you were to do such a cast, and then add an object of type Foo to the list, the list of strings is no longer consistent. If you were to iterate the first reference, you would get a class cast exception because once you hit the Foo instance, the Foo could not be converted to string! As a side note, I think it would be more significant whether or not you can do the reverse cast: List ol = new List (); List sl; sl = (List )ol; I haven't used C# in a while, so I don't know if that is legal, but that sort of cast is actually (potentially) useful. In this case, you are going from a more general class (object) to a more specific class (string) that extends from the general one. In this way, if you add to the list of strings, you are not violating the list of objects. Does anybody know or can test if such a cast is legal in C#?
[ "c#", ".net", "generics", "covariance", "type-safety" ]
86
39
77,817
14
0
2008-08-09T02:32:01.507000
2008-08-09T02:50:14.903000
6,578
6,614
Understanding reference counting with Cocoa and Objective-C
I'm just beginning to have a look at Objective-C and Cocoa with a view to playing with the iPhone SDK. I'm reasonably comfortable with C's malloc and free concept, but Cocoa's references counting scheme has me rather confused. I'm told it's very elegant once you understand it, but I'm just not over the hump yet. How do release, retain and autorelease work and what are the conventions about their use? (Or failing that, what did you read which helped you get it?)
Let's start with retain and release; autorelease is really just a special case once you understand the basic concepts. In Cocoa, each object keeps track of how many times it is being referenced (specifically, the NSObject base class implements this). By calling retain on an object, you are telling it that you want to up its reference count by one. By calling release, you tell the object you are letting go of it, and its reference count is decremented. If, after calling release, the reference count is now zero, then that object's memory is freed by the system. The basic way this differs from malloc and free is that any given object doesn't need to worry about other parts of the system crashing because you've freed memory they were using. Assuming everyone is playing along and retaining/releasing according to the rules, when one piece of code retains and then releases the object, any other piece of code also referencing the object will be unaffected. What can sometimes be confusing is knowing the circumstances under which you should call retain and release. My general rule of thumb is that if I want to hang on to an object for some length of time (if it's a member variable in a class, for instance), then I need to make sure the object's reference count knows about me. As described above, an object's reference count is incremented by calling retain. By convention, it is also incremented (set to 1, really) when the object is created with an "init" method. In either of these cases, it is my responsibility to call release on the object when I'm done with it. If I don't, there will be a memory leak. Example of object creation: NSString* s = [[NSString alloc] init]; // Ref count is 1 [s retain]; // Ref count is 2 - silly // to do this after init [s release]; // Ref count is back to 1 [s release]; // Ref count is 0, object is freed Now for autorelease. Autorelease is used as a convenient (and sometimes necessary) way to tell the system to free this object up after a little while. From a plumbing perspective, when autorelease is called, the current thread's NSAutoreleasePool is alerted of the call. The NSAutoreleasePool now knows that once it gets an opportunity (after the current iteration of the event loop), it can call release on the object. From our perspective as programmers, it takes care of calling release for us, so we don't have to (and in fact, we shouldn't). What's important to note is that (again, by convention) all object creation class methods return an autoreleased object. For example, in the following example, the variable "s" has a reference count of 1, but after the event loop completes, it will be destroyed. NSString* s = [NSString stringWithString:@"Hello World"]; If you want to hang onto that string, you'd need to call retain explicitly, and then explicitly release it when you're done. Consider the following (very contrived) bit of code, and you'll see a situation where autorelease is required: - (NSString*)createHelloWorldString { NSString* s = [[NSString alloc] initWithString:@"Hello World"]; // Now what? We want to return s, but we've upped its reference count. // The caller shouldn't be responsible for releasing it, since we're the // ones that created it. If we call release, however, the reference // count will hit zero and bad memory will be returned to the caller. // The answer is to call autorelease before returning the string. By // explicitly calling autorelease, we pass the responsibility for // releasing the string on to the thread's NSAutoreleasePool, which will // happen at some later time. The consequence is that the returned string // will still be valid for the caller of this function. return [s autorelease]; } I realize all of this is a bit confusing - at some point, though, it will click. Here are a few references to get you going: Apple's introduction to memory management. Cocoa Programming for Mac OS X (4th Edition), by Aaron Hillegas - a very well written book with lots of great examples. It reads like a tutorial. If you're truly diving in, you could head to Big Nerd Ranch. This is a training facility run by Aaron Hillegas - the author of the book mentioned above. I attended the Intro to Cocoa course there several years ago, and it was a great way to learn.
Understanding reference counting with Cocoa and Objective-C I'm just beginning to have a look at Objective-C and Cocoa with a view to playing with the iPhone SDK. I'm reasonably comfortable with C's malloc and free concept, but Cocoa's references counting scheme has me rather confused. I'm told it's very elegant once you understand it, but I'm just not over the hump yet. How do release, retain and autorelease work and what are the conventions about their use? (Or failing that, what did you read which helped you get it?)
TITLE: Understanding reference counting with Cocoa and Objective-C QUESTION: I'm just beginning to have a look at Objective-C and Cocoa with a view to playing with the iPhone SDK. I'm reasonably comfortable with C's malloc and free concept, but Cocoa's references counting scheme has me rather confused. I'm told it's very elegant once you understand it, but I'm just not over the hump yet. How do release, retain and autorelease work and what are the conventions about their use? (Or failing that, what did you read which helped you get it?) ANSWER: Let's start with retain and release; autorelease is really just a special case once you understand the basic concepts. In Cocoa, each object keeps track of how many times it is being referenced (specifically, the NSObject base class implements this). By calling retain on an object, you are telling it that you want to up its reference count by one. By calling release, you tell the object you are letting go of it, and its reference count is decremented. If, after calling release, the reference count is now zero, then that object's memory is freed by the system. The basic way this differs from malloc and free is that any given object doesn't need to worry about other parts of the system crashing because you've freed memory they were using. Assuming everyone is playing along and retaining/releasing according to the rules, when one piece of code retains and then releases the object, any other piece of code also referencing the object will be unaffected. What can sometimes be confusing is knowing the circumstances under which you should call retain and release. My general rule of thumb is that if I want to hang on to an object for some length of time (if it's a member variable in a class, for instance), then I need to make sure the object's reference count knows about me. As described above, an object's reference count is incremented by calling retain. By convention, it is also incremented (set to 1, really) when the object is created with an "init" method. In either of these cases, it is my responsibility to call release on the object when I'm done with it. If I don't, there will be a memory leak. Example of object creation: NSString* s = [[NSString alloc] init]; // Ref count is 1 [s retain]; // Ref count is 2 - silly // to do this after init [s release]; // Ref count is back to 1 [s release]; // Ref count is 0, object is freed Now for autorelease. Autorelease is used as a convenient (and sometimes necessary) way to tell the system to free this object up after a little while. From a plumbing perspective, when autorelease is called, the current thread's NSAutoreleasePool is alerted of the call. The NSAutoreleasePool now knows that once it gets an opportunity (after the current iteration of the event loop), it can call release on the object. From our perspective as programmers, it takes care of calling release for us, so we don't have to (and in fact, we shouldn't). What's important to note is that (again, by convention) all object creation class methods return an autoreleased object. For example, in the following example, the variable "s" has a reference count of 1, but after the event loop completes, it will be destroyed. NSString* s = [NSString stringWithString:@"Hello World"]; If you want to hang onto that string, you'd need to call retain explicitly, and then explicitly release it when you're done. Consider the following (very contrived) bit of code, and you'll see a situation where autorelease is required: - (NSString*)createHelloWorldString { NSString* s = [[NSString alloc] initWithString:@"Hello World"]; // Now what? We want to return s, but we've upped its reference count. // The caller shouldn't be responsible for releasing it, since we're the // ones that created it. If we call release, however, the reference // count will hit zero and bad memory will be returned to the caller. // The answer is to call autorelease before returning the string. By // explicitly calling autorelease, we pass the responsibility for // releasing the string on to the thread's NSAutoreleasePool, which will // happen at some later time. The consequence is that the returned string // will still be valid for the caller of this function. return [s autorelease]; } I realize all of this is a bit confusing - at some point, though, it will click. Here are a few references to get you going: Apple's introduction to memory management. Cocoa Programming for Mac OS X (4th Edition), by Aaron Hillegas - a very well written book with lots of great examples. It reads like a tutorial. If you're truly diving in, you could head to Big Nerd Ranch. This is a training facility run by Aaron Hillegas - the author of the book mentioned above. I attended the Intro to Cocoa course there several years ago, and it was a great way to learn.
[ "iphone", "objective-c", "cocoa", "memory" ]
125
151
36,506
15
0
2008-08-09T03:13:04
2008-08-09T04:40:49.250000
6,579
6,588
Which Agile software development methods have you had the most success with?
There are numerous Agile software development methods. Which ones have you used in practice to deliver a successful project, and how did the method contribute to that success?
I've been involved with quite a few organisations which claimed to work in an 'agile' way, and their processed usually seemed to be base on XP (extreme programming), but none of them ever followed anywhere near all the practices. That said, I can probably comment on a few of the XP practices Unit testing seems to prove very useful if it's done from the start of a project, but it seems very difficult to come into an existing code-base and start trying to add unit tests. If you get the opportunity to start from scratch, test driven development is a real help. Continuous integration seems to be a really good thing (or rather, the lack of it is really bad). That said, the organisations I've seen have usually been so small as to make any other approach seem foolish. User story cards are nice in that it's great to have a physical object to throw around for prioritisation, but they're not nearly detailed enough unless your developer really knows the domain, or you've got an onsite customer (which I've never actually seen). Standup meetings tend to be really useful for new team members to get to know everyone, and what they work on. The old hands very quickly slack off, and just say things like 'I'm still working on X', which they've been doing for the past week - It takes a strong leader to force them to delve into details. Refactoring is now a really misused term, but when you've got sufficient unit tests, it's really useful to conceptually separate the activity of 'changing the design of the existing code without changing the functionality' from 'adding new functionality'
Which Agile software development methods have you had the most success with? There are numerous Agile software development methods. Which ones have you used in practice to deliver a successful project, and how did the method contribute to that success?
TITLE: Which Agile software development methods have you had the most success with? QUESTION: There are numerous Agile software development methods. Which ones have you used in practice to deliver a successful project, and how did the method contribute to that success? ANSWER: I've been involved with quite a few organisations which claimed to work in an 'agile' way, and their processed usually seemed to be base on XP (extreme programming), but none of them ever followed anywhere near all the practices. That said, I can probably comment on a few of the XP practices Unit testing seems to prove very useful if it's done from the start of a project, but it seems very difficult to come into an existing code-base and start trying to add unit tests. If you get the opportunity to start from scratch, test driven development is a real help. Continuous integration seems to be a really good thing (or rather, the lack of it is really bad). That said, the organisations I've seen have usually been so small as to make any other approach seem foolish. User story cards are nice in that it's great to have a physical object to throw around for prioritisation, but they're not nearly detailed enough unless your developer really knows the domain, or you've got an onsite customer (which I've never actually seen). Standup meetings tend to be really useful for new team members to get to know everyone, and what they work on. The old hands very quickly slack off, and just say things like 'I'm still working on X', which they've been doing for the past week - It takes a strong leader to force them to delve into details. Refactoring is now a really misused term, but when you've got sufficient unit tests, it's really useful to conceptually separate the activity of 'changing the design of the existing code without changing the functionality' from 'adding new functionality'
[ "methods", "agile" ]
3
7
856
5
0
2008-08-09T03:19:59.117000
2008-08-09T03:39:44.600000
6,594
6,617
PHP4 to PHP5 Migration
What are some good steps to follow for a smooth migration from PHP4 to PHP5. What are some types of code that are likely to break?
I also once worked on an app which used PHP4's XML support quite heavily, and would have required quite a bit of work to move to PHP5. One of the other significant changes I was looking at at the time was the change of the default handling of function parameters. In PHP4 if I remember, they were pass-by-copy unless you specified otherwise, but in PHP5 is changed to pass-by-reference by default. In well written code, that probably won't make a big difference to you, but it could certainly cause problems. I think one other thing I found changed is that objects are no longer allowed to overwrite their 'this' field. I would say that was a really bad idea to begin with (and I think it may have not been an intentional feature in PHP4), but I certainly found a few parts of our system that relied on it. Hope some of that helps.
PHP4 to PHP5 Migration What are some good steps to follow for a smooth migration from PHP4 to PHP5. What are some types of code that are likely to break?
TITLE: PHP4 to PHP5 Migration QUESTION: What are some good steps to follow for a smooth migration from PHP4 to PHP5. What are some types of code that are likely to break? ANSWER: I also once worked on an app which used PHP4's XML support quite heavily, and would have required quite a bit of work to move to PHP5. One of the other significant changes I was looking at at the time was the change of the default handling of function parameters. In PHP4 if I remember, they were pass-by-copy unless you specified otherwise, but in PHP5 is changed to pass-by-reference by default. In well written code, that probably won't make a big difference to you, but it could certainly cause problems. I think one other thing I found changed is that objects are no longer allowed to overwrite their 'this' field. I would say that was a really bad idea to begin with (and I think it may have not been an intentional feature in PHP4), but I certainly found a few parts of our system that relied on it. Hope some of that helps.
[ "php", "migration" ]
11
8
2,251
4
0
2008-08-09T03:49:36.017000
2008-08-09T04:44:49.710000
6,607
6,620
Registry vs. INI file for storing user configurable application settings
I'm a new Windows programmer and I'm not sure where I should store user configurable application settings. I understand the need to provide a user friendly means for the user to change application settings, like an Edit | Settings form or similar. But where should I store the values after the user hits the Apply button on that form? What are the pros and cons of storing settings in the Windows registry vs. storing them in a local INI file or config file or similar?
Pros of config file: Easy to do. Don't need to know any Windows API calls. You just need to know the file I/O interface of your programming language. Portable. If you port your application to another OS, you don't need to change your settings format. User-editable. The user can edit the config file outside of the program executing. Pros of registry: Secure. The user can't accidentally delete the config file or corrupt the data unless he/she knows about regedit. And then the user is just asking for trouble. I'm no expert Windows programmer, but I'm sure that using the registry makes it easier to do other Windows-specific things (user-specific settings, network administration stuff like group policy, or whatever else). If you just need a simple way to store config information, I would recommend a config file, using INI or XML as the format. I suggest using the registry only if there is something specific you want to get out of using the registry.
Registry vs. INI file for storing user configurable application settings I'm a new Windows programmer and I'm not sure where I should store user configurable application settings. I understand the need to provide a user friendly means for the user to change application settings, like an Edit | Settings form or similar. But where should I store the values after the user hits the Apply button on that form? What are the pros and cons of storing settings in the Windows registry vs. storing them in a local INI file or config file or similar?
TITLE: Registry vs. INI file for storing user configurable application settings QUESTION: I'm a new Windows programmer and I'm not sure where I should store user configurable application settings. I understand the need to provide a user friendly means for the user to change application settings, like an Edit | Settings form or similar. But where should I store the values after the user hits the Apply button on that form? What are the pros and cons of storing settings in the Windows registry vs. storing them in a local INI file or config file or similar? ANSWER: Pros of config file: Easy to do. Don't need to know any Windows API calls. You just need to know the file I/O interface of your programming language. Portable. If you port your application to another OS, you don't need to change your settings format. User-editable. The user can edit the config file outside of the program executing. Pros of registry: Secure. The user can't accidentally delete the config file or corrupt the data unless he/she knows about regedit. And then the user is just asking for trouble. I'm no expert Windows programmer, but I'm sure that using the registry makes it easier to do other Windows-specific things (user-specific settings, network administration stuff like group policy, or whatever else). If you just need a simple way to store config information, I would recommend a config file, using INI or XML as the format. I suggest using the registry only if there is something specific you want to get out of using the registry.
[ "windows", "registry", "settings", "configuration-files", "ini" ]
55
45
26,415
13
0
2008-08-09T04:13:02.740000
2008-08-09T04:51:59.773000
6,612
6,655
Are there any decent free Java data plotting libraries out there?
On a recent Java project, we needed a free Java based real-time data plotting utility. After much searching, we found this tool called the Scientific Graphics Toolkit or SGT from NOAA. It seemed pretty robust, but we found out that it wasn't terribly configurable. Or at least not configurable enough to meet our needs. We ended up digging very deeply into the Java code and reverse engineering the code and changing it all around to make the plot tool look and act the way we wanted it to look and act. Of course, this killed any chance for future upgrades from NOAA. So what free or cheap Java based data plotting tools or libraries do you use? Followup: Thanks for the JFreeChart suggestions. I checked out their website and it looks like a very nice data charting and plotting utility. I should have made it clear in my original question that I was looking specifically to plot real-time data. I corrected my question above to make that point clear. It appears that JFreeChart support for live data is marginal at best, though. Any other suggestions out there?
I've had success using JFreeChart on multiple projects. It is very configurable. JFreeChart is open source, but they charge for the developer guide. If you're doing something simple, the sample code is probably good enough. Otherwise, $50 for the developer guide is a pretty good bargain. With respect to "real-time" data, I've also used JFreeChart for these sorts of applications. Unfortunately, I had to create some custom data models with appropriate synchronization mechanisms to avoid race conditions. However, it wasn't terribly difficult and JFreeChart would still be my first choice. However, as the FAQ suggests, JFreeChart might not give you the best performance if that is a big concern.
Are there any decent free Java data plotting libraries out there? On a recent Java project, we needed a free Java based real-time data plotting utility. After much searching, we found this tool called the Scientific Graphics Toolkit or SGT from NOAA. It seemed pretty robust, but we found out that it wasn't terribly configurable. Or at least not configurable enough to meet our needs. We ended up digging very deeply into the Java code and reverse engineering the code and changing it all around to make the plot tool look and act the way we wanted it to look and act. Of course, this killed any chance for future upgrades from NOAA. So what free or cheap Java based data plotting tools or libraries do you use? Followup: Thanks for the JFreeChart suggestions. I checked out their website and it looks like a very nice data charting and plotting utility. I should have made it clear in my original question that I was looking specifically to plot real-time data. I corrected my question above to make that point clear. It appears that JFreeChart support for live data is marginal at best, though. Any other suggestions out there?
TITLE: Are there any decent free Java data plotting libraries out there? QUESTION: On a recent Java project, we needed a free Java based real-time data plotting utility. After much searching, we found this tool called the Scientific Graphics Toolkit or SGT from NOAA. It seemed pretty robust, but we found out that it wasn't terribly configurable. Or at least not configurable enough to meet our needs. We ended up digging very deeply into the Java code and reverse engineering the code and changing it all around to make the plot tool look and act the way we wanted it to look and act. Of course, this killed any chance for future upgrades from NOAA. So what free or cheap Java based data plotting tools or libraries do you use? Followup: Thanks for the JFreeChart suggestions. I checked out their website and it looks like a very nice data charting and plotting utility. I should have made it clear in my original question that I was looking specifically to plot real-time data. I corrected my question above to make that point clear. It appears that JFreeChart support for live data is marginal at best, though. Any other suggestions out there? ANSWER: I've had success using JFreeChart on multiple projects. It is very configurable. JFreeChart is open source, but they charge for the developer guide. If you're doing something simple, the sample code is probably good enough. Otherwise, $50 for the developer guide is a pretty good bargain. With respect to "real-time" data, I've also used JFreeChart for these sorts of applications. Unfortunately, I had to create some custom data models with appropriate synchronization mechanisms to avoid race conditions. However, it wasn't terribly difficult and JFreeChart would still be my first choice. However, as the FAQ suggests, JFreeChart might not give you the best performance if that is a big concern.
[ "java", "plot", "configuration" ]
45
18
32,553
16
0
2008-08-09T04:29:42.190000
2008-08-09T06:23:19.140000
6,613
15,811
What rule engine should I use?
What are some of the best or most popular rule engines? I haven't settled on a programming language, so tell me the rule engine and what programming languages it supports.
I am one of the authors of Drools, I will avoid pimping my wares. But some other options are Jess (not open source) but uses the clips syntax (which we also support a subset of) - which is kinda a lisp dialect. It really depends what you want it for, Haley have strong Natural language tech (and they recently aquired RuleBurst - who has also interesting natural language tech which could deal with word documents with embedded rules - eg legal documentation). RuleBurst was able to target.Net runtimes as well (there is a Drools.net "port" available as well - I haven't seen what it has been up to lately, alas, not enough time). Ok I will put my pimp bling away now... sorry about that.
What rule engine should I use? What are some of the best or most popular rule engines? I haven't settled on a programming language, so tell me the rule engine and what programming languages it supports.
TITLE: What rule engine should I use? QUESTION: What are some of the best or most popular rule engines? I haven't settled on a programming language, so tell me the rule engine and what programming languages it supports. ANSWER: I am one of the authors of Drools, I will avoid pimping my wares. But some other options are Jess (not open source) but uses the clips syntax (which we also support a subset of) - which is kinda a lisp dialect. It really depends what you want it for, Haley have strong Natural language tech (and they recently aquired RuleBurst - who has also interesting natural language tech which could deal with word documents with embedded rules - eg legal documentation). RuleBurst was able to target.Net runtimes as well (there is a Drools.net "port" available as well - I haven't seen what it has been up to lately, alas, not enough time). Ok I will put my pimp bling away now... sorry about that.
[ "language-agnostic", "rule-engine" ]
18
10
24,997
8
0
2008-08-09T04:34:29.467000
2008-08-19T06:51:46.643000
6,623
27,317
sgen.exe fails during build
After changing the output directory of a visual studio project it started to fail to build with an error very much like: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\sgen.exe /assembly:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryCaseManagement\obj\Release\EASDiscoveryCaseManagement.dll /proxytypes /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Common\target\win_x32\release\results\EASDiscovery.Common.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Export\target\win_x32\release\results\EASDiscovery.Export.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\ItemCache\target\win_x32\release\results\EasDiscovery.ItemCache.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\RetrievalEngine\target\win_x32\release\results\EasDiscovery.RetrievalEngine.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryJobs\target\win_x32\release\results\EASDiscoveryJobs.dll /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Shared.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.Misc.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinChart.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDataSource.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDock.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinEditors.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinGrid.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinListView.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinMaskedEdit.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinStatusBar.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTabControl.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinToolbars.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTree.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.v8.1.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.Common.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.WinForms.dll" /reference:C:\p4root\Zantaz\trunk\EASDiscovery\PreviewControl\target\win_x32\release\results\PreviewControl.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\Quartz\src\Quartz\target\win_x32\release\results\Scheduler.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.Services.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /compiler:/delaysign- Error: The specified module could not be found. (Exception from HRESULT: 0x8007007E) C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets(1902,9): error MSB6006: "sgen.exe" exited with code 1. I changed the output directory to target/win_x32/release/results but the path in sgen doesn't seem to have been updated. There seems to be no reference in the project to what path is passed into sgen so I'm unsure how to fix it. As a workaround I have disabled the serialization generation but it would be nice to fix the underlying problem. Has anybody else seen this?
see msdn for the options to sgen.exe [you have the command line, you can play with it manually... delete your.XmlSerializers.dll or use /force though] Today I also ran across how to more manually specify the sgen options. I wanted this to not use the /proxy switch, but it appears it can let you specify the output directory. I don't know enough about msbuild to make it awesome, but this should get you started [open your.csproj/.vbproj in your non-visual studio editor of choice, look at the bottom and you should be able to figure out how/where this goes] [the below code has had UseProxyTypes set to true for your convenience]
sgen.exe fails during build After changing the output directory of a visual studio project it started to fail to build with an error very much like: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\sgen.exe /assembly:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryCaseManagement\obj\Release\EASDiscoveryCaseManagement.dll /proxytypes /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Common\target\win_x32\release\results\EASDiscovery.Common.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Export\target\win_x32\release\results\EASDiscovery.Export.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\ItemCache\target\win_x32\release\results\EasDiscovery.ItemCache.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\RetrievalEngine\target\win_x32\release\results\EasDiscovery.RetrievalEngine.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryJobs\target\win_x32\release\results\EASDiscoveryJobs.dll /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Shared.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.Misc.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinChart.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDataSource.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDock.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinEditors.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinGrid.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinListView.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinMaskedEdit.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinStatusBar.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTabControl.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinToolbars.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTree.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.v8.1.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.Common.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.WinForms.dll" /reference:C:\p4root\Zantaz\trunk\EASDiscovery\PreviewControl\target\win_x32\release\results\PreviewControl.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\Quartz\src\Quartz\target\win_x32\release\results\Scheduler.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.Services.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /compiler:/delaysign- Error: The specified module could not be found. (Exception from HRESULT: 0x8007007E) C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets(1902,9): error MSB6006: "sgen.exe" exited with code 1. I changed the output directory to target/win_x32/release/results but the path in sgen doesn't seem to have been updated. There seems to be no reference in the project to what path is passed into sgen so I'm unsure how to fix it. As a workaround I have disabled the serialization generation but it would be nice to fix the underlying problem. Has anybody else seen this?
TITLE: sgen.exe fails during build QUESTION: After changing the output directory of a visual studio project it started to fail to build with an error very much like: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\sgen.exe /assembly:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryCaseManagement\obj\Release\EASDiscoveryCaseManagement.dll /proxytypes /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Common\target\win_x32\release\results\EASDiscovery.Common.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Export\target\win_x32\release\results\EASDiscovery.Export.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\ItemCache\target\win_x32\release\results\EasDiscovery.ItemCache.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\RetrievalEngine\target\win_x32\release\results\EasDiscovery.RetrievalEngine.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryJobs\target\win_x32\release\results\EASDiscoveryJobs.dll /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Shared.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.Misc.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinChart.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDataSource.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDock.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinEditors.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinGrid.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinListView.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinMaskedEdit.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinStatusBar.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTabControl.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinToolbars.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTree.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for.NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.v8.1.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.Common.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.WinForms.dll" /reference:C:\p4root\Zantaz\trunk\EASDiscovery\PreviewControl\target\win_x32\release\results\PreviewControl.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\Quartz\src\Quartz\target\win_x32\release\results\Scheduler.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.Services.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /compiler:/delaysign- Error: The specified module could not be found. (Exception from HRESULT: 0x8007007E) C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets(1902,9): error MSB6006: "sgen.exe" exited with code 1. I changed the output directory to target/win_x32/release/results but the path in sgen doesn't seem to have been updated. There seems to be no reference in the project to what path is passed into sgen so I'm unsure how to fix it. As a workaround I have disabled the serialization generation but it would be nice to fix the underlying problem. Has anybody else seen this? ANSWER: see msdn for the options to sgen.exe [you have the command line, you can play with it manually... delete your.XmlSerializers.dll or use /force though] Today I also ran across how to more manually specify the sgen options. I wanted this to not use the /proxy switch, but it appears it can let you specify the output directory. I don't know enough about msbuild to make it awesome, but this should get you started [open your.csproj/.vbproj in your non-visual studio editor of choice, look at the bottom and you should be able to figure out how/where this goes] [the below code has had UseProxyTypes set to true for your convenience]
[ "c#", "visual-studio", "msbuild" ]
18
9
29,113
4
0
2008-08-09T04:57:00.577000
2008-08-26T02:49:28.977000
6,628
6,649
PHP array indexing: $array[$index] vs $array["$index"] vs $array["{$index}"]
What is the difference, if any, between these methods of indexing into a PHP array: $array[$index] $array["$index"] $array["{$index}"] I'm interested in both the performance and functional differences. Update: (In response to @Jeremy) I'm not sure that's right. I ran this code: $array = array(100, 200, 300); print_r($array); $idx = 0; $array[$idx] = 123; print_r($array); $array["$idx"] = 456; print_r($array); $array["{$idx}"] = 789; print_r($array); And got this output: Array ( [0] => 100 [1] => 200 [2] => 300 ) Array ( [0] => 123 [1] => 200 [2] => 300 ) Array ( [0] => 456 [1] => 200 [2] => 300 ) Array ( [0] => 789 [1] => 200 [2] => 300 )
see @svec and @jeremy above. All array indices are of type 'int' first, then type 'string', and will be cast to that as PHP sees fit. Performance wise, $index should be faster than "$index" and "{$index}" (which are the same). Once you start a double-quote string, PHP will go into interpolation mode and treat it as a string first, but looking for variable markers ($, {}, etc) to replace from the local scope. This is why in most discussions, true 'static' strings should always be single quotes unless you need the escape-shortcuts like "\n" or "\t", because PHP will not need to try to interpolate the string at runtime and the full string can be compiled statically. In this case, doublequoting will first copy the $index into that string, then return the string, where directly using $index will just return the string.
PHP array indexing: $array[$index] vs $array["$index"] vs $array["{$index}"] What is the difference, if any, between these methods of indexing into a PHP array: $array[$index] $array["$index"] $array["{$index}"] I'm interested in both the performance and functional differences. Update: (In response to @Jeremy) I'm not sure that's right. I ran this code: $array = array(100, 200, 300); print_r($array); $idx = 0; $array[$idx] = 123; print_r($array); $array["$idx"] = 456; print_r($array); $array["{$idx}"] = 789; print_r($array); And got this output: Array ( [0] => 100 [1] => 200 [2] => 300 ) Array ( [0] => 123 [1] => 200 [2] => 300 ) Array ( [0] => 456 [1] => 200 [2] => 300 ) Array ( [0] => 789 [1] => 200 [2] => 300 )
TITLE: PHP array indexing: $array[$index] vs $array["$index"] vs $array["{$index}"] QUESTION: What is the difference, if any, between these methods of indexing into a PHP array: $array[$index] $array["$index"] $array["{$index}"] I'm interested in both the performance and functional differences. Update: (In response to @Jeremy) I'm not sure that's right. I ran this code: $array = array(100, 200, 300); print_r($array); $idx = 0; $array[$idx] = 123; print_r($array); $array["$idx"] = 456; print_r($array); $array["{$idx}"] = 789; print_r($array); And got this output: Array ( [0] => 100 [1] => 200 [2] => 300 ) Array ( [0] => 123 [1] => 200 [2] => 300 ) Array ( [0] => 456 [1] => 200 [2] => 300 ) Array ( [0] => 789 [1] => 200 [2] => 300 ) ANSWER: see @svec and @jeremy above. All array indices are of type 'int' first, then type 'string', and will be cast to that as PHP sees fit. Performance wise, $index should be faster than "$index" and "{$index}" (which are the same). Once you start a double-quote string, PHP will go into interpolation mode and treat it as a string first, but looking for variable markers ($, {}, etc) to replace from the local scope. This is why in most discussions, true 'static' strings should always be single quotes unless you need the escape-shortcuts like "\n" or "\t", because PHP will not need to try to interpolate the string at runtime and the full string can be compiled statically. In this case, doublequoting will first copy the $index into that string, then return the string, where directly using $index will just return the string.
[ "php", "syntax" ]
34
34
87,726
7
0
2008-08-09T05:01:38.867000
2008-08-09T05:55:24.187000
6,633
6,694
Making code work with register_globals turned off
I have inherited some legacy PHP code what was written back when it was standard practice to use register_globals (As of PHP 4.2.0, this directive defaults to off, released 22. Apr 2002). We know now that it is bad for security to have it enabled. The problem is how do I find all the places in the code where I need to use $_GET or $_POST? My only thought was to set the error reporting to warn about uninitialized variables and then test each part of the site. Is there an easier way? Will I have to test each code path in the site or will PHP give a warning on a file basis?
If you set error reporting to E_ALL, it warns in the error log about undefined variables complete with filename and line number (assuming you are logging to a file). However, it will warn only if when it comes across an undefined variable, so I think you will have to test each code path. Running php from the command line doesn't seem to help also. There is a debugging tool named xdebug, haven't tried it, but maybe that can be useful?
Making code work with register_globals turned off I have inherited some legacy PHP code what was written back when it was standard practice to use register_globals (As of PHP 4.2.0, this directive defaults to off, released 22. Apr 2002). We know now that it is bad for security to have it enabled. The problem is how do I find all the places in the code where I need to use $_GET or $_POST? My only thought was to set the error reporting to warn about uninitialized variables and then test each part of the site. Is there an easier way? Will I have to test each code path in the site or will PHP give a warning on a file basis?
TITLE: Making code work with register_globals turned off QUESTION: I have inherited some legacy PHP code what was written back when it was standard practice to use register_globals (As of PHP 4.2.0, this directive defaults to off, released 22. Apr 2002). We know now that it is bad for security to have it enabled. The problem is how do I find all the places in the code where I need to use $_GET or $_POST? My only thought was to set the error reporting to warn about uninitialized variables and then test each part of the site. Is there an easier way? Will I have to test each code path in the site or will PHP give a warning on a file basis? ANSWER: If you set error reporting to E_ALL, it warns in the error log about undefined variables complete with filename and line number (assuming you are logging to a file). However, it will warn only if when it comes across an undefined variable, so I think you will have to test each code path. Running php from the command line doesn't seem to help also. There is a debugging tool named xdebug, haven't tried it, but maybe that can be useful?
[ "php", "register-globals" ]
13
6
2,324
4
0
2008-08-09T05:13:55.877000
2008-08-09T08:11:55.487000
6,642
6,645
Preferred way to use favicons?
I was trying to add a favicon to a website earlier and looked for a better way to implement this than to dump a favicon.ico file in the root of the website. I found this nice little guide: How to Add a Favicon. However, the preferred method did not work in IE (7) and the second method is the old fashioned way (which I resigned myself to use). Is there a third method that works across all the most popular browsers?
This is what I always use: The second one is for IE. The first one is for other browsers.
Preferred way to use favicons? I was trying to add a favicon to a website earlier and looked for a better way to implement this than to dump a favicon.ico file in the root of the website. I found this nice little guide: How to Add a Favicon. However, the preferred method did not work in IE (7) and the second method is the old fashioned way (which I resigned myself to use). Is there a third method that works across all the most popular browsers?
TITLE: Preferred way to use favicons? QUESTION: I was trying to add a favicon to a website earlier and looked for a better way to implement this than to dump a favicon.ico file in the root of the website. I found this nice little guide: How to Add a Favicon. However, the preferred method did not work in IE (7) and the second method is the old fashioned way (which I resigned myself to use). Is there a third method that works across all the most popular browsers? ANSWER: This is what I always use: The second one is for IE. The first one is for other browsers.
[ "browser", "compatibility" ]
9
15
4,341
6
0
2008-08-09T05:41:40.830000
2008-08-09T05:48:15.433000
6,658
6,671
JUnit vs TestNG
At work we are currently still using JUnit 3 to run our tests. We have been considering switching over to JUnit 4 for new tests being written but I have been keeping an eye on TestNG for a while now. What experiences have you all had with either JUnit 4 or TestNG, and which seems to work better for very large numbers of tests? Having flexibility in writing tests is also important to us since our functional tests cover a wide aspect and need to be written in a variety of ways to get results. Old tests will not be re-written as they do their job just fine. What I would like to see in new tests though is flexibility in the way the test can be written, natural assertions, grouping, and easily distributed test executions.
I've used both, but I have to agree with Justin Standard that you shouldn't really consider rewriting your existing tests to any new format. Regardless of the decision, it is pretty trivial to run both. TestNG strives to be much more configurable than JUnit, but in the end they both work equally well. TestNG has a neat feature where you can mark tests as a particular group, and then easily run all tests of a specific group, or exclude tests of a particular group. Thus you can mark tests that run slowly as in the "slow" group and then ignore them when you want quick results. A suggestion from their documentation is to mark some subset as "checkin" tests which should be run whenever you check new files in. I never saw such a feature in JUnit, but then again, if you don't have it, you don't REALLY miss it. For all its claims of high configuration, I did run into a corner case the a couple weeks ago where I couldn't do what I wanted to do... I wish I could remember what it is, but I wanted to bring it up so you know that it's not perfect. The biggest advantage TestNG has is annotations... which JUnit added in version 4 anyways.
JUnit vs TestNG At work we are currently still using JUnit 3 to run our tests. We have been considering switching over to JUnit 4 for new tests being written but I have been keeping an eye on TestNG for a while now. What experiences have you all had with either JUnit 4 or TestNG, and which seems to work better for very large numbers of tests? Having flexibility in writing tests is also important to us since our functional tests cover a wide aspect and need to be written in a variety of ways to get results. Old tests will not be re-written as they do their job just fine. What I would like to see in new tests though is flexibility in the way the test can be written, natural assertions, grouping, and easily distributed test executions.
TITLE: JUnit vs TestNG QUESTION: At work we are currently still using JUnit 3 to run our tests. We have been considering switching over to JUnit 4 for new tests being written but I have been keeping an eye on TestNG for a while now. What experiences have you all had with either JUnit 4 or TestNG, and which seems to work better for very large numbers of tests? Having flexibility in writing tests is also important to us since our functional tests cover a wide aspect and need to be written in a variety of ways to get results. Old tests will not be re-written as they do their job just fine. What I would like to see in new tests though is flexibility in the way the test can be written, natural assertions, grouping, and easily distributed test executions. ANSWER: I've used both, but I have to agree with Justin Standard that you shouldn't really consider rewriting your existing tests to any new format. Regardless of the decision, it is pretty trivial to run both. TestNG strives to be much more configurable than JUnit, but in the end they both work equally well. TestNG has a neat feature where you can mark tests as a particular group, and then easily run all tests of a specific group, or exclude tests of a particular group. Thus you can mark tests that run slowly as in the "slow" group and then ignore them when you want quick results. A suggestion from their documentation is to mark some subset as "checkin" tests which should be run whenever you check new files in. I never saw such a feature in JUnit, but then again, if you don't have it, you don't REALLY miss it. For all its claims of high configuration, I did run into a corner case the a couple weeks ago where I couldn't do what I wanted to do... I wish I could remember what it is, but I wanted to bring it up so you know that it's not perfect. The biggest advantage TestNG has is annotations... which JUnit added in version 4 anyways.
[ "java", "testing", "junit", "testng" ]
126
67
40,956
12
0
2008-08-09T06:31:25.283000
2008-08-09T07:00:34.087000
6,661
6,662
Reference that lists available JavaScript events?
I'm aware of things like onchange, onmousedown and onmouseup but is there a good reference somewhere that lists all of them complete with possibly a list of the elements that they cover?
W3Schools seems to have a good Javascript events reference: HTML DOM Events
Reference that lists available JavaScript events? I'm aware of things like onchange, onmousedown and onmouseup but is there a good reference somewhere that lists all of them complete with possibly a list of the elements that they cover?
TITLE: Reference that lists available JavaScript events? QUESTION: I'm aware of things like onchange, onmousedown and onmouseup but is there a good reference somewhere that lists all of them complete with possibly a list of the elements that they cover? ANSWER: W3Schools seems to have a good Javascript events reference: HTML DOM Events
[ "javascript", "browser", "client-side" ]
24
11
2,911
5
0
2008-08-09T06:40:52.987000
2008-08-09T06:42:20.003000
6,666
7,005
Web Services -- WCF vs. ASMX ("Standard")
I am working on a new project. Is there any benefit with going with a WCF web service over a regular old fashion web service? Visual Studio offers templates for both. What are the differences? Pros and cons?
What is a "regular old fashioned web service?" An ASMX service, or are you using WSE as well? ASMX services are not naturally interoperable, don't support WS-* specs, and ASMX is a technology that is aging very quickly. WSE (Web Service Enhancements) services DO add support for WS-* and can be made to be interoperable, but WCF is meant to replace WSE, so you should take the time to learn it. I would say that unless your application is a quick an dirty one-off, you will gain immense flexibility and end up with a better design if you choose WCF. WCF does have a learning curve beyond a [WebMethod] attribute, but the learning curve is over-exaggerated in my opinion, and it is exponentially more powerful and future proof than legacy ASMX services. Unless your time line simply cannot tolerate the learning curve, you would be doing yourself a huge favor learning WCF instead of just sticking with ASP.NET Web Services. Applications will only continue to become more and more distributed and interconnected, and WCF is the future of distributed computing on the Microsoft platform. Here is a comparison between the two.
Web Services -- WCF vs. ASMX ("Standard") I am working on a new project. Is there any benefit with going with a WCF web service over a regular old fashion web service? Visual Studio offers templates for both. What are the differences? Pros and cons?
TITLE: Web Services -- WCF vs. ASMX ("Standard") QUESTION: I am working on a new project. Is there any benefit with going with a WCF web service over a regular old fashion web service? Visual Studio offers templates for both. What are the differences? Pros and cons? ANSWER: What is a "regular old fashioned web service?" An ASMX service, or are you using WSE as well? ASMX services are not naturally interoperable, don't support WS-* specs, and ASMX is a technology that is aging very quickly. WSE (Web Service Enhancements) services DO add support for WS-* and can be made to be interoperable, but WCF is meant to replace WSE, so you should take the time to learn it. I would say that unless your application is a quick an dirty one-off, you will gain immense flexibility and end up with a better design if you choose WCF. WCF does have a learning curve beyond a [WebMethod] attribute, but the learning curve is over-exaggerated in my opinion, and it is exponentially more powerful and future proof than legacy ASMX services. Unless your time line simply cannot tolerate the learning curve, you would be doing yourself a huge favor learning WCF instead of just sticking with ASP.NET Web Services. Applications will only continue to become more and more distributed and interconnected, and WCF is the future of distributed computing on the Microsoft platform. Here is a comparison between the two.
[ ".net", "wcf", "web-services", "visual-studio", "asmx" ]
34
33
11,870
7
0
2008-08-09T06:50:22.703000
2008-08-10T02:28:42.683000
6,681
6,704
ASP.NET Web Service Results, Proxy Classes and Type Conversion
I'm still new to the ASP.NET world, so I could be way off base here, but so far this is to the best of my (limited) knowledge! Let's say I have a standard business object "Contact" in the Business namespace. I write a Web Service to retrieve a Contact's info from a database and return it. I then write a client application to request said details. Now, I also then create a utility method that takes a "Contact" and does some magic with it, like Utils.BuyContactNewHat() say. Which of course takes the Contact of type Business.Contact. I then go back to my client application and want to utilise the BuyContactNewHat method, so I add a reference to my Utils namespace and there it is. However, a problem arises with: Contact c = MyWebService.GetContact("Rob); Utils.BuyContactNewHat(c); // << Error Here Since the return type of GetContact is of MyWebService.Contact and not Business.Contact as expected. I understand why this is because when accessing a web service, you are actually programming against the proxy class generated by the WSDL. So, is there an "easier" way to deal with this type of mismatch? I was considering perhaps trying to create a generic converter class that uses reflection to ensure two objects have the same structure than simply transferring the values across from one to the other.
You are on the right track. To get the data from the proxy object back into one of your own objects, you have to do left-hand-right-hand code. i.e. copy property values. I'll bet you that there is already a generic method out there that uses reflection. Some people will use something other than a web service (.net remoting) if they just want to get a business object across the wire. Or they'll use binary serialization. I'm guessing you are using the web service for a reason, so you'll have to do property copying.
ASP.NET Web Service Results, Proxy Classes and Type Conversion I'm still new to the ASP.NET world, so I could be way off base here, but so far this is to the best of my (limited) knowledge! Let's say I have a standard business object "Contact" in the Business namespace. I write a Web Service to retrieve a Contact's info from a database and return it. I then write a client application to request said details. Now, I also then create a utility method that takes a "Contact" and does some magic with it, like Utils.BuyContactNewHat() say. Which of course takes the Contact of type Business.Contact. I then go back to my client application and want to utilise the BuyContactNewHat method, so I add a reference to my Utils namespace and there it is. However, a problem arises with: Contact c = MyWebService.GetContact("Rob); Utils.BuyContactNewHat(c); // << Error Here Since the return type of GetContact is of MyWebService.Contact and not Business.Contact as expected. I understand why this is because when accessing a web service, you are actually programming against the proxy class generated by the WSDL. So, is there an "easier" way to deal with this type of mismatch? I was considering perhaps trying to create a generic converter class that uses reflection to ensure two objects have the same structure than simply transferring the values across from one to the other.
TITLE: ASP.NET Web Service Results, Proxy Classes and Type Conversion QUESTION: I'm still new to the ASP.NET world, so I could be way off base here, but so far this is to the best of my (limited) knowledge! Let's say I have a standard business object "Contact" in the Business namespace. I write a Web Service to retrieve a Contact's info from a database and return it. I then write a client application to request said details. Now, I also then create a utility method that takes a "Contact" and does some magic with it, like Utils.BuyContactNewHat() say. Which of course takes the Contact of type Business.Contact. I then go back to my client application and want to utilise the BuyContactNewHat method, so I add a reference to my Utils namespace and there it is. However, a problem arises with: Contact c = MyWebService.GetContact("Rob); Utils.BuyContactNewHat(c); // << Error Here Since the return type of GetContact is of MyWebService.Contact and not Business.Contact as expected. I understand why this is because when accessing a web service, you are actually programming against the proxy class generated by the WSDL. So, is there an "easier" way to deal with this type of mismatch? I was considering perhaps trying to create a generic converter class that uses reflection to ensure two objects have the same structure than simply transferring the values across from one to the other. ANSWER: You are on the right track. To get the data from the proxy object back into one of your own objects, you have to do left-hand-right-hand code. i.e. copy property values. I'll bet you that there is already a generic method out there that uses reflection. Some people will use something other than a web service (.net remoting) if they just want to get a business object across the wire. Or they'll use binary serialization. I'm guessing you are using the web service for a reason, so you'll have to do property copying.
[ "c#", "asp.net", "web-services" ]
12
5
4,986
3
0
2008-08-09T07:34:01.523000
2008-08-09T08:58:24.707000
6,703
6,748
When is OOP better suited for?
Since I started studying object-oriented programming, I frequently read articles/blogs saying functions are better, or not all problems should be modeled as objects. From your personal programming adventures, when do you think a problem is better solved by OOP?
There is no hard and fast rule. A problem is better solved with OOP when you are better at solving problems and thinking in an OO mentality. Object Orientation is just another tool which has come along through trying to make computing a better tool for solving problems. However, it can allow for better code reuse, and can also lead to neater code. But quite often these highly praised qualities are, in-relity, of little real value. Applying OO techniques to an existing functional application could really cause a lot of problems. The skill lies in learning many different techniques and applying the most appropriate to the problem at hand. OO is often quoted as a Nirvana-like solution to the software development, however there are many times when it is not appropriate to be applied to the issue at hand. It can, quite often, lead to over-engineering of a problem to reach the perfect solution, when often it is really not necessary. In essence, OOP is not really Object Oriented Programming, but mapping Object Oriented Thinking to a programming language capable of supporting OO Techniques. OO techniques can be supported by languages which are not inherently OO, and there are techniques you can use within functional languages to take advantage of the benefits. As an example, I have been developing OO software for about 20 years now, so I tend to think in OO terms when solving problems, irrespective of the language I am writing in. Currently I am implementing polymorphism using Perl 5.6, which does not natively support it. I have chosen to do this as it will make maintenance and extension of the code a simple configuration task, rather than a development issue. Not sure if this is clear. There are people who are hard in the OO court, and there are people who are hard in the Functional court. And then there are people who have tried both and try to take the best from each. Neither is perfect, but both have some very good traits that you can utilise no matter what the language. If you are trying to learn OOP, don't just concentrate on OOP, but try to utilise Object Oriented Analysis and general OO principles to the whole spectrum of the problem solution.
When is OOP better suited for? Since I started studying object-oriented programming, I frequently read articles/blogs saying functions are better, or not all problems should be modeled as objects. From your personal programming adventures, when do you think a problem is better solved by OOP?
TITLE: When is OOP better suited for? QUESTION: Since I started studying object-oriented programming, I frequently read articles/blogs saying functions are better, or not all problems should be modeled as objects. From your personal programming adventures, when do you think a problem is better solved by OOP? ANSWER: There is no hard and fast rule. A problem is better solved with OOP when you are better at solving problems and thinking in an OO mentality. Object Orientation is just another tool which has come along through trying to make computing a better tool for solving problems. However, it can allow for better code reuse, and can also lead to neater code. But quite often these highly praised qualities are, in-relity, of little real value. Applying OO techniques to an existing functional application could really cause a lot of problems. The skill lies in learning many different techniques and applying the most appropriate to the problem at hand. OO is often quoted as a Nirvana-like solution to the software development, however there are many times when it is not appropriate to be applied to the issue at hand. It can, quite often, lead to over-engineering of a problem to reach the perfect solution, when often it is really not necessary. In essence, OOP is not really Object Oriented Programming, but mapping Object Oriented Thinking to a programming language capable of supporting OO Techniques. OO techniques can be supported by languages which are not inherently OO, and there are techniques you can use within functional languages to take advantage of the benefits. As an example, I have been developing OO software for about 20 years now, so I tend to think in OO terms when solving problems, irrespective of the language I am writing in. Currently I am implementing polymorphism using Perl 5.6, which does not natively support it. I have chosen to do this as it will make maintenance and extension of the code a simple configuration task, rather than a development issue. Not sure if this is clear. There are people who are hard in the OO court, and there are people who are hard in the Functional court. And then there are people who have tried both and try to take the best from each. Neither is perfect, but both have some very good traits that you can utilise no matter what the language. If you are trying to learn OOP, don't just concentrate on OOP, but try to utilise Object Oriented Analysis and general OO principles to the whole spectrum of the problem solution.
[ "oop" ]
30
31
18,170
16
0
2008-08-09T08:51:27.107000
2008-08-09T12:44:59.070000
6,719
6,720
Master Pages for large web sites
I've just been learning about master pages in ASP.NET 2.0. They sound great, but how well do they work in practice? Does anybody have experience of using them for a large web site?
I'm pretty sure I've only used master pages in the context of ASP.NET MVC so I'm not sure if it differs from web forms but in my experience they are not only excellent but I couldn't imagine not using them. Master pages are code inheritance to web pages.
Master Pages for large web sites I've just been learning about master pages in ASP.NET 2.0. They sound great, but how well do they work in practice? Does anybody have experience of using them for a large web site?
TITLE: Master Pages for large web sites QUESTION: I've just been learning about master pages in ASP.NET 2.0. They sound great, but how well do they work in practice? Does anybody have experience of using them for a large web site? ANSWER: I'm pretty sure I've only used master pages in the context of ASP.NET MVC so I'm not sure if it differs from web forms but in my experience they are not only excellent but I couldn't imagine not using them. Master pages are code inheritance to web pages.
[ "asp.net", ".net", "master-pages", "asp.net-2.0" ]
5
6
1,322
6
0
2008-08-09T09:51:37.533000
2008-08-09T09:55:02.660000
6,729
6,738
Icons: How does a developer with no design skill make his/her application icons look pretty?
I probably spend far too much time trying to make my visual interfaces look good, and while I'm pretty adept at finding the right match between usability and style one area I am hopeless at is making nice looking icons. How do you people overcome this (I'm sure common) problem? I'm thinking of things like images on buttons and perhaps most important of all, the actual application icon. Do you rely on third party designers, in or out of house? Or do you know of some hidden website that offers lots of icons for us to use? I've tried Google but I seem to find either expensive packages that are very specific, millions of Star Trek icons or icons that look abysmal at 16x16 which is my preferred size on in-application buttons. Any help/advice appreciated.
Good icons are hard to design. I have tried to design my own, and have used in-house graphics designers as well. However, building a good icon set takes a lot of work, even for the graphic designer. I believe your best solution is to buy/find a set of icons for use in your projects. The silk icon set is a good, free set and can be found at FamFamFam. There are over 1000 icons in this set, and it is very popular. If you are looking for something "different", you can purchase icon sets for a couple hundred bucks. Considering the cost of having a designer create them for you, or doing them yourself, the cost of these sets is cheap! Here's a few icon designers I've come across of the web: Icon Factory Icon Experience Icon Buffet
Icons: How does a developer with no design skill make his/her application icons look pretty? I probably spend far too much time trying to make my visual interfaces look good, and while I'm pretty adept at finding the right match between usability and style one area I am hopeless at is making nice looking icons. How do you people overcome this (I'm sure common) problem? I'm thinking of things like images on buttons and perhaps most important of all, the actual application icon. Do you rely on third party designers, in or out of house? Or do you know of some hidden website that offers lots of icons for us to use? I've tried Google but I seem to find either expensive packages that are very specific, millions of Star Trek icons or icons that look abysmal at 16x16 which is my preferred size on in-application buttons. Any help/advice appreciated.
TITLE: Icons: How does a developer with no design skill make his/her application icons look pretty? QUESTION: I probably spend far too much time trying to make my visual interfaces look good, and while I'm pretty adept at finding the right match between usability and style one area I am hopeless at is making nice looking icons. How do you people overcome this (I'm sure common) problem? I'm thinking of things like images on buttons and perhaps most important of all, the actual application icon. Do you rely on third party designers, in or out of house? Or do you know of some hidden website that offers lots of icons for us to use? I've tried Google but I seem to find either expensive packages that are very specific, millions of Star Trek icons or icons that look abysmal at 16x16 which is my preferred size on in-application buttons. Any help/advice appreciated. ANSWER: Good icons are hard to design. I have tried to design my own, and have used in-house graphics designers as well. However, building a good icon set takes a lot of work, even for the graphic designer. I believe your best solution is to buy/find a set of icons for use in your projects. The silk icon set is a good, free set and can be found at FamFamFam. There are over 1000 icons in this set, and it is very popular. If you are looking for something "different", you can purchase icon sets for a couple hundred bucks. Considering the cost of having a designer create them for you, or doing them yourself, the cost of these sets is cheap! Here's a few icon designers I've come across of the web: Icon Factory Icon Experience Icon Buffet
[ "user-interface", "icons" ]
60
47
5,933
19
0
2008-08-09T11:18:58.527000
2008-08-09T12:04:18.780000
6,732
6,766
Why doesn't my favicon display for my web site?
I have a website that I've just uploaded onto the Internet. When I browse to the site using Firefox 3.0.1 on Ubuntu I don't see the favicon; Firefox 3.0.1 on WinXP does display it. Why isn't the favicon displaying under Ubuntu? It's a favicon.ico file in the root directory, not referenced in the meta tags; would it work better as a GIF?
Previously, there was no favicon. The browser cached the lack of favicon. Clear the Firefox cache, and all is well.
Why doesn't my favicon display for my web site? I have a website that I've just uploaded onto the Internet. When I browse to the site using Firefox 3.0.1 on Ubuntu I don't see the favicon; Firefox 3.0.1 on WinXP does display it. Why isn't the favicon displaying under Ubuntu? It's a favicon.ico file in the root directory, not referenced in the meta tags; would it work better as a GIF?
TITLE: Why doesn't my favicon display for my web site? QUESTION: I have a website that I've just uploaded onto the Internet. When I browse to the site using Firefox 3.0.1 on Ubuntu I don't see the favicon; Firefox 3.0.1 on WinXP does display it. Why isn't the favicon displaying under Ubuntu? It's a favicon.ico file in the root directory, not referenced in the meta tags; would it work better as a GIF? ANSWER: Previously, there was no favicon. The browser cached the lack of favicon. Clear the Firefox cache, and all is well.
[ "firefox", "ubuntu", "favicon" ]
1
8
3,889
2
0
2008-08-09T11:30:09.520000
2008-08-09T13:24:01.067000
6,765
6,902
Java + SQL Server - a viable solution?
I'm going to start a new project - rewriting an existing system (PHP + SQL Server) from scratch because of some very serious limitations by design. We have some quite good knowledge of SQL Server (currently we're using SQL Server 2000 in existing system) and we would like to employ its newer version (2008 I guess) in our new project. I am really fond of technologies that Java offers - particularly Spring Framework and Wicket and I am quite familiar with Java from others projects and assignments before. Therefore, we consider using Java and Microsoft SQL Server. There are two JDBC drivers for SQL Server - jTDS and Microsoft's one - http://msdn.microsoft.com/en-us/data/aa937724.aspx. I think we should test both of them. Are there any limitations in such solution I should know of? Has someone experience with such a technology combination?
I've worked on a project using MSQL Server in conjunction with a Java Stack. It works very well and as long, since JDBC shouldn't really care about your database. We used ehcache together with Hibernate and had problems with the MS JDBC Driver, so we switched to jtds and it works really good. It's quite a while ago, so you still might wanna give the MS driver a chance...
Java + SQL Server - a viable solution? I'm going to start a new project - rewriting an existing system (PHP + SQL Server) from scratch because of some very serious limitations by design. We have some quite good knowledge of SQL Server (currently we're using SQL Server 2000 in existing system) and we would like to employ its newer version (2008 I guess) in our new project. I am really fond of technologies that Java offers - particularly Spring Framework and Wicket and I am quite familiar with Java from others projects and assignments before. Therefore, we consider using Java and Microsoft SQL Server. There are two JDBC drivers for SQL Server - jTDS and Microsoft's one - http://msdn.microsoft.com/en-us/data/aa937724.aspx. I think we should test both of them. Are there any limitations in such solution I should know of? Has someone experience with such a technology combination?
TITLE: Java + SQL Server - a viable solution? QUESTION: I'm going to start a new project - rewriting an existing system (PHP + SQL Server) from scratch because of some very serious limitations by design. We have some quite good knowledge of SQL Server (currently we're using SQL Server 2000 in existing system) and we would like to employ its newer version (2008 I guess) in our new project. I am really fond of technologies that Java offers - particularly Spring Framework and Wicket and I am quite familiar with Java from others projects and assignments before. Therefore, we consider using Java and Microsoft SQL Server. There are two JDBC drivers for SQL Server - jTDS and Microsoft's one - http://msdn.microsoft.com/en-us/data/aa937724.aspx. I think we should test both of them. Are there any limitations in such solution I should know of? Has someone experience with such a technology combination? ANSWER: I've worked on a project using MSQL Server in conjunction with a Java Stack. It works very well and as long, since JDBC shouldn't really care about your database. We used ehcache together with Hibernate and had problems with the MS JDBC Driver, so we switched to jtds and it works really good. It's quite a while ago, so you still might wanna give the MS driver a chance...
[ "java", "sql-server" ]
12
8
3,031
6
0
2008-08-09T13:23:40.617000
2008-08-09T20:18:15.240000
6,778
26,040
How to make a Flash movie with a transparent background
This page from Adobe says to add a "wmode" parameter and set its value to "transparent": http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_1420 This works flawlessly in IE. The background renders correctly in Firefox and Safari, however as soon as you use the browser's scroll bar then mouse over the Flash control you must click once to activate the control. You can see this behavior if you try to hit the play button in Adobe's example. Anyone know a way around this?
You know you can set the background color when you're embedding? The following attributes are optional when defining the object and/or embed tags. For object, all attributes are defined in param tags unless otherwise specified: bgcolor - [ hexadecimal RGB value] in the format #RRGGBB. Specifies the background color of the movie. Use this attribute to override the background color setting specified in the Flash file. This attribute does not affect the background color of the HTML page. Cut 'n paste from http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_12701&sliceId=1
How to make a Flash movie with a transparent background This page from Adobe says to add a "wmode" parameter and set its value to "transparent": http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_1420 This works flawlessly in IE. The background renders correctly in Firefox and Safari, however as soon as you use the browser's scroll bar then mouse over the Flash control you must click once to activate the control. You can see this behavior if you try to hit the play button in Adobe's example. Anyone know a way around this?
TITLE: How to make a Flash movie with a transparent background QUESTION: This page from Adobe says to add a "wmode" parameter and set its value to "transparent": http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_1420 This works flawlessly in IE. The background renders correctly in Firefox and Safari, however as soon as you use the browser's scroll bar then mouse over the Flash control you must click once to activate the control. You can see this behavior if you try to hit the play button in Adobe's example. Anyone know a way around this? ANSWER: You know you can set the background color when you're embedding? The following attributes are optional when defining the object and/or embed tags. For object, all attributes are defined in param tags unless otherwise specified: bgcolor - [ hexadecimal RGB value] in the format #RRGGBB. Specifies the background color of the movie. Use this attribute to override the background color setting specified in the Flash file. This attribute does not affect the background color of the HTML page. Cut 'n paste from http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_12701&sliceId=1
[ "flash", "firefox", "safari" ]
4
1
4,181
5
0
2008-08-09T13:54:29.837000
2008-08-25T13:38:11.063000
6,785
6,824
Is String.Format as efficient as StringBuilder
Suppose I have a stringbuilder in C# that does this: StringBuilder sb = new StringBuilder(); string cat = "cat"; sb.Append("the ").Append(cat).(" in the hat"); string s = sb.ToString(); would that be as efficient or any more efficient as having: string cat = "cat"; string s = String.Format("The {0} in the hat", cat); If so, why? EDIT After some interesting answers, I realised I probably should have been a little clearer in what I was asking. I wasn't so much asking for which was quicker at concatenating a string, but which is quicker at injecting one string into another. In both cases above I want to inject one or more strings into the middle of a predefined template string. Sorry for the confusion
NOTE: This answer was written when.NET 2.0 was the current version. This may no longer apply to later versions. String.Format uses a StringBuilder internally: public static string Format(IFormatProvider provider, string format, params object[] args) { if ((format == null) || (args == null)) { throw new ArgumentNullException((format == null)? "format": "args"); } StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8)); builder.AppendFormat(provider, format, args); return builder.ToString(); } The above code is a snippet from mscorlib, so the question becomes "is StringBuilder.Append() faster than StringBuilder.AppendFormat() "? Without benchmarking I'd probably say that the code sample above would run more quickly using.Append(). But it's a guess, try benchmarking and/or profiling the two to get a proper comparison. This chap, Jerry Dixon, did some benchmarking: http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm Updated: Sadly the link above has since died. However there's still a copy on the Way Back Machine: http://web.archive.org/web/20090417100252/http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm At the end of the day it depends whether your string formatting is going to be called repetitively, i.e. you're doing some serious text processing over 100's of megabytes of text, or whether it's being called when a user clicks a button now and again. Unless you're doing some huge batch processing job I'd stick with String.Format, it aids code readability. If you suspect a perf bottleneck then stick a profiler on your code and see where it really is.
Is String.Format as efficient as StringBuilder Suppose I have a stringbuilder in C# that does this: StringBuilder sb = new StringBuilder(); string cat = "cat"; sb.Append("the ").Append(cat).(" in the hat"); string s = sb.ToString(); would that be as efficient or any more efficient as having: string cat = "cat"; string s = String.Format("The {0} in the hat", cat); If so, why? EDIT After some interesting answers, I realised I probably should have been a little clearer in what I was asking. I wasn't so much asking for which was quicker at concatenating a string, but which is quicker at injecting one string into another. In both cases above I want to inject one or more strings into the middle of a predefined template string. Sorry for the confusion
TITLE: Is String.Format as efficient as StringBuilder QUESTION: Suppose I have a stringbuilder in C# that does this: StringBuilder sb = new StringBuilder(); string cat = "cat"; sb.Append("the ").Append(cat).(" in the hat"); string s = sb.ToString(); would that be as efficient or any more efficient as having: string cat = "cat"; string s = String.Format("The {0} in the hat", cat); If so, why? EDIT After some interesting answers, I realised I probably should have been a little clearer in what I was asking. I wasn't so much asking for which was quicker at concatenating a string, but which is quicker at injecting one string into another. In both cases above I want to inject one or more strings into the middle of a predefined template string. Sorry for the confusion ANSWER: NOTE: This answer was written when.NET 2.0 was the current version. This may no longer apply to later versions. String.Format uses a StringBuilder internally: public static string Format(IFormatProvider provider, string format, params object[] args) { if ((format == null) || (args == null)) { throw new ArgumentNullException((format == null)? "format": "args"); } StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8)); builder.AppendFormat(provider, format, args); return builder.ToString(); } The above code is a snippet from mscorlib, so the question becomes "is StringBuilder.Append() faster than StringBuilder.AppendFormat() "? Without benchmarking I'd probably say that the code sample above would run more quickly using.Append(). But it's a guess, try benchmarking and/or profiling the two to get a proper comparison. This chap, Jerry Dixon, did some benchmarking: http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm Updated: Sadly the link above has since died. However there's still a copy on the Way Back Machine: http://web.archive.org/web/20090417100252/http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm At the end of the day it depends whether your string formatting is going to be called repetitively, i.e. you're doing some serious text processing over 100's of megabytes of text, or whether it's being called when a user clicks a button now and again. Unless you're doing some huge batch processing job I'd stick with String.Format, it aids code readability. If you suspect a perf bottleneck then stick a profiler on your code and see where it really is.
[ "c#", "vb.net", "performance", "stringbuilder", "string.format" ]
165
148
74,490
12
0
2008-08-09T14:24:05.703000
2008-08-09T15:57:15.970000
6,812
6,821
Mapping my custom keys in Debian
I have a Microsoft keyboard with a series of non-standard buttons such as "Mail", "Search", "Web/Home" etc. It would be nice to be able to bind these keys so they execute arbitrary programs. Does anybody know how to do this in Debian Etch?
I can't say for certain because I'm not using Debian but if you're using Gnome the easiest way is to run gnome-keybinding-properties (System > Preferences > Keyboard Shortcuts) Instead of typing a shortcut such as Ctrl + M, hit the button on your keyboard. If you would prefer to do this via command line or with a different desktop environment, this may help: Unusual keys and keyboards
Mapping my custom keys in Debian I have a Microsoft keyboard with a series of non-standard buttons such as "Mail", "Search", "Web/Home" etc. It would be nice to be able to bind these keys so they execute arbitrary programs. Does anybody know how to do this in Debian Etch?
TITLE: Mapping my custom keys in Debian QUESTION: I have a Microsoft keyboard with a series of non-standard buttons such as "Mail", "Search", "Web/Home" etc. It would be nice to be able to bind these keys so they execute arbitrary programs. Does anybody know how to do this in Debian Etch? ANSWER: I can't say for certain because I'm not using Debian but if you're using Gnome the easiest way is to run gnome-keybinding-properties (System > Preferences > Keyboard Shortcuts) Instead of typing a shortcut such as Ctrl + M, hit the button on your keyboard. If you would prefer to do this via command line or with a different desktop environment, this may help: Unusual keys and keyboards
[ "linux", "keyboard", "debian" ]
3
2
6,170
5
0
2008-08-09T15:23:13.620000
2008-08-09T15:52:39.443000
6,816
6,840
Class file name must end with .class exception in Java search
I have a problem using the Java search function in Eclipse on a particular project. When using the Java search on one particular project, I get an error message saying Class file name must end with.class (see stack trace below). This does not seem to be happening on all projects, just one particular one, so perhaps there's something I should try to get rebuilt? I have already tried Project -> Clean... and Closing Eclipse, deleting all the built class files and restarting Eclipse to no avail. The only reference I've been able to find on Google for the problem is at http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx, but unfortunately his solution (closing, deleting class files, restarting) did not work for me. If anyone can suggest something to try, or there's any more info I can gather which might help track it's down, I'd greatly appreciate the pointers. Version: 3.4.0 Build id: I20080617-2000 Also just found this thread - http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html - which indicates the same problem may occur when the project name contains a period. Unfortunately, that's not the case in my setup, so I'm still stuck. Caused by: java.lang.IllegalArgumentException: Class file name must end with.class at org.eclipse.jdt.internal.core.PackageFragment.getClassFile(PackageFragment.java:182) at org.eclipse.jdt.internal.core.util.HandleFactory.createOpenable(HandleFactory.java:109) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:1177) at org.eclipse.jdt.internal.core.search.JavaSearchParticipant.locateMatches(JavaSearchParticipant.java:94) at org.eclipse.jdt.internal.core.search.BasicSearchEngine.findMatches(BasicSearchEngine.java:223) at org.eclipse.jdt.internal.core.search.BasicSearchEngine.search(BasicSearchEngine.java:506) at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:551) at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.internalSearch(RefactoringSearchEngine.java:142) at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.search(RefactoringSearchEngine.java:129) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.initializeReferences(RenameTypeProcessor.java:594) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.doCheckFinalConditions(RenameTypeProcessor.java:522) at org.eclipse.jdt.internal.corext.refactoring.rename.JavaRenameProcessor.checkFinalConditions(JavaRenameProcessor.java:45) at org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring.checkFinalConditions(ProcessorBasedRefactoring.java:225) at org.eclipse.ltk.core.refactoring.Refactoring.checkAllConditions(Refactoring.java:160) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:77) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:39) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:709) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1800) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:4650) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:92) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121) Update Thanks McDowell, closing and opening the project seems to have fixed it (at least for now).
Two more general-purpose mechanisms for fixing some of Eclipse's idiosyncrasies: Close and open the project Delete the project (but not from disk!) and reimport it as an existing project Failing that, bugs.eclipse.org might provide the answer. If the workspace is caching something broken, you may be able to delete it by poking around in workspace/.metadata/.plugins. Most of that stuff is fairly transient (though backup and watch for deleted preferences).
Class file name must end with .class exception in Java search I have a problem using the Java search function in Eclipse on a particular project. When using the Java search on one particular project, I get an error message saying Class file name must end with.class (see stack trace below). This does not seem to be happening on all projects, just one particular one, so perhaps there's something I should try to get rebuilt? I have already tried Project -> Clean... and Closing Eclipse, deleting all the built class files and restarting Eclipse to no avail. The only reference I've been able to find on Google for the problem is at http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx, but unfortunately his solution (closing, deleting class files, restarting) did not work for me. If anyone can suggest something to try, or there's any more info I can gather which might help track it's down, I'd greatly appreciate the pointers. Version: 3.4.0 Build id: I20080617-2000 Also just found this thread - http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html - which indicates the same problem may occur when the project name contains a period. Unfortunately, that's not the case in my setup, so I'm still stuck. Caused by: java.lang.IllegalArgumentException: Class file name must end with.class at org.eclipse.jdt.internal.core.PackageFragment.getClassFile(PackageFragment.java:182) at org.eclipse.jdt.internal.core.util.HandleFactory.createOpenable(HandleFactory.java:109) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:1177) at org.eclipse.jdt.internal.core.search.JavaSearchParticipant.locateMatches(JavaSearchParticipant.java:94) at org.eclipse.jdt.internal.core.search.BasicSearchEngine.findMatches(BasicSearchEngine.java:223) at org.eclipse.jdt.internal.core.search.BasicSearchEngine.search(BasicSearchEngine.java:506) at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:551) at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.internalSearch(RefactoringSearchEngine.java:142) at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.search(RefactoringSearchEngine.java:129) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.initializeReferences(RenameTypeProcessor.java:594) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.doCheckFinalConditions(RenameTypeProcessor.java:522) at org.eclipse.jdt.internal.corext.refactoring.rename.JavaRenameProcessor.checkFinalConditions(JavaRenameProcessor.java:45) at org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring.checkFinalConditions(ProcessorBasedRefactoring.java:225) at org.eclipse.ltk.core.refactoring.Refactoring.checkAllConditions(Refactoring.java:160) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:77) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:39) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:709) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1800) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:4650) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:92) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121) Update Thanks McDowell, closing and opening the project seems to have fixed it (at least for now).
TITLE: Class file name must end with .class exception in Java search QUESTION: I have a problem using the Java search function in Eclipse on a particular project. When using the Java search on one particular project, I get an error message saying Class file name must end with.class (see stack trace below). This does not seem to be happening on all projects, just one particular one, so perhaps there's something I should try to get rebuilt? I have already tried Project -> Clean... and Closing Eclipse, deleting all the built class files and restarting Eclipse to no avail. The only reference I've been able to find on Google for the problem is at http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx, but unfortunately his solution (closing, deleting class files, restarting) did not work for me. If anyone can suggest something to try, or there's any more info I can gather which might help track it's down, I'd greatly appreciate the pointers. Version: 3.4.0 Build id: I20080617-2000 Also just found this thread - http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html - which indicates the same problem may occur when the project name contains a period. Unfortunately, that's not the case in my setup, so I'm still stuck. Caused by: java.lang.IllegalArgumentException: Class file name must end with.class at org.eclipse.jdt.internal.core.PackageFragment.getClassFile(PackageFragment.java:182) at org.eclipse.jdt.internal.core.util.HandleFactory.createOpenable(HandleFactory.java:109) at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:1177) at org.eclipse.jdt.internal.core.search.JavaSearchParticipant.locateMatches(JavaSearchParticipant.java:94) at org.eclipse.jdt.internal.core.search.BasicSearchEngine.findMatches(BasicSearchEngine.java:223) at org.eclipse.jdt.internal.core.search.BasicSearchEngine.search(BasicSearchEngine.java:506) at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:551) at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.internalSearch(RefactoringSearchEngine.java:142) at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.search(RefactoringSearchEngine.java:129) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.initializeReferences(RenameTypeProcessor.java:594) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.doCheckFinalConditions(RenameTypeProcessor.java:522) at org.eclipse.jdt.internal.corext.refactoring.rename.JavaRenameProcessor.checkFinalConditions(JavaRenameProcessor.java:45) at org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring.checkFinalConditions(ProcessorBasedRefactoring.java:225) at org.eclipse.ltk.core.refactoring.Refactoring.checkAllConditions(Refactoring.java:160) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:77) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:39) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:709) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1800) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:4650) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:92) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121) Update Thanks McDowell, closing and opening the project seems to have fixed it (at least for now). ANSWER: Two more general-purpose mechanisms for fixing some of Eclipse's idiosyncrasies: Close and open the project Delete the project (but not from disk!) and reimport it as an existing project Failing that, bugs.eclipse.org might provide the answer. If the workspace is caching something broken, you may be able to delete it by poking around in workspace/.metadata/.plugins. Most of that stuff is fairly transient (though backup and watch for deleted preferences).
[ "java", "eclipse", "search" ]
67
62
26,455
6
0
2008-08-09T15:40:30.357000
2008-08-09T16:31:32.623000
6,817
6,929
Scaling multithreaded applications on multicored machines
I'm working on a project were we need more performance. Over time we've continued to evolve the design to work more in parallel(both threaded and distributed). Then latest step has been to move part of it onto a new machine with 16 cores. I'm finding that we need to rethink how we do things to scale to that many cores in a shared memory model. For example the standard memory allocator isn't good enough. What resources would people recommend? So far I've found Sutter's column Dr. Dobbs to be a good start. I just got The Art of Multiprocessor Programming and The O'Reilly book on Intel Threading Building Blocks
A couple of other books that are going to be helpful are: Synchronization Algorithms and Concurrent Programming Patterns for Parallel Programming Communicating Sequential Processes by C. A. R. Hoare (a classic, free PDF at that link) Also, consider relying less on sharing state between concurrent processes. You'll scale much, much better if you can avoid it because you'll be able to parcel out independent units of work without having to do as much synchronization between them. Even if you need to share some state, see if you can partition the shared state from the actual processing. That will let you do as much of the processing in parallel, independently from the integration of the completed units of work back into the shared state. Obviously this doesn't work if you have dependencies among units of work, but it's worth investigating instead of just assuming that the state is always going to be shared.
Scaling multithreaded applications on multicored machines I'm working on a project were we need more performance. Over time we've continued to evolve the design to work more in parallel(both threaded and distributed). Then latest step has been to move part of it onto a new machine with 16 cores. I'm finding that we need to rethink how we do things to scale to that many cores in a shared memory model. For example the standard memory allocator isn't good enough. What resources would people recommend? So far I've found Sutter's column Dr. Dobbs to be a good start. I just got The Art of Multiprocessor Programming and The O'Reilly book on Intel Threading Building Blocks
TITLE: Scaling multithreaded applications on multicored machines QUESTION: I'm working on a project were we need more performance. Over time we've continued to evolve the design to work more in parallel(both threaded and distributed). Then latest step has been to move part of it onto a new machine with 16 cores. I'm finding that we need to rethink how we do things to scale to that many cores in a shared memory model. For example the standard memory allocator isn't good enough. What resources would people recommend? So far I've found Sutter's column Dr. Dobbs to be a good start. I just got The Art of Multiprocessor Programming and The O'Reilly book on Intel Threading Building Blocks ANSWER: A couple of other books that are going to be helpful are: Synchronization Algorithms and Concurrent Programming Patterns for Parallel Programming Communicating Sequential Processes by C. A. R. Hoare (a classic, free PDF at that link) Also, consider relying less on sharing state between concurrent processes. You'll scale much, much better if you can avoid it because you'll be able to parcel out independent units of work without having to do as much synchronization between them. Even if you need to share some state, see if you can partition the shared state from the actual processing. That will let you do as much of the processing in parallel, independently from the integration of the completed units of work back into the shared state. Obviously this doesn't work if you have dependencies among units of work, but it's worth investigating instead of just assuming that the state is always going to be shared.
[ "performance", "multithreading", "scalability", "malloc" ]
6
6
1,579
8
0
2008-08-09T15:42:17.840000
2008-08-09T22:13:12.233000
6,847
6,862
Defensive programming
When writing code do you consciously program defensively to ensure high program quality and to avoid the possibility of your code being exploited maliciously, e.g. through buffer overflow exploits or code injection? What's the "minimum" level of quality you'll always apply to your code?
In my line of work, our code has to be top quality. So, we focus on two main things: Testing Code reviews Those bring home the money.
Defensive programming When writing code do you consciously program defensively to ensure high program quality and to avoid the possibility of your code being exploited maliciously, e.g. through buffer overflow exploits or code injection? What's the "minimum" level of quality you'll always apply to your code?
TITLE: Defensive programming QUESTION: When writing code do you consciously program defensively to ensure high program quality and to avoid the possibility of your code being exploited maliciously, e.g. through buffer overflow exploits or code injection? What's the "minimum" level of quality you'll always apply to your code? ANSWER: In my line of work, our code has to be top quality. So, we focus on two main things: Testing Code reviews Those bring home the money.
[ "security", "defensive-programming" ]
11
12
2,777
14
0
2008-08-09T17:02:56.663000
2008-08-09T18:00:26.907000
6,859
6,863
Developing addins for World of Warcraft - Getting started?
As a long time World of Warcraft player, and a passionate developer I have decided that I would like to combine the two and set about developing some addins. Not only to improve my gameplay experience but as a great opportunity to learn something new. Does anyone have any advice on how to go about starting out? Is there an IDE one can use? How does one go about testing? Are there any ready made libraries available? Or would I get a better learning experience by ignoring the libraries and building from scratch? How do I oneshot Hogger? Would love to hear your advice, experiences and views.
This article explains how to start pretty well. Your first bookmark is possibly the US Interface Forum, especially the Stickies for that: http://us.battle.net/wow/en/forum/1011693/ Then, grab some simple addons to learn how XML and LUA interacts. The WoWWiki HOWTO List is a good point here as well. One important thing to keep in mind: World of Warcraft is available in many languages. If you have a EU Account, you got an excellent testing bed by simply downloading the language Packs for Spanish, German and French. If you're an US Guy, check if you can get the Latin America version. That way, you can test it against another language version. Once you made 1 or 2 really small and simple addons just to learn how to use it, have a look at the various frameworks. WowAce is a popular one, but there are others. Just keep one thing in mind: Making an Addon is work. Maintaining one is even more work. With each new Patch, there may be breaking changes, and the next Addon will surely cause a big Exodus of Addons, just like Patch 2.0.1 did.
Developing addins for World of Warcraft - Getting started? As a long time World of Warcraft player, and a passionate developer I have decided that I would like to combine the two and set about developing some addins. Not only to improve my gameplay experience but as a great opportunity to learn something new. Does anyone have any advice on how to go about starting out? Is there an IDE one can use? How does one go about testing? Are there any ready made libraries available? Or would I get a better learning experience by ignoring the libraries and building from scratch? How do I oneshot Hogger? Would love to hear your advice, experiences and views.
TITLE: Developing addins for World of Warcraft - Getting started? QUESTION: As a long time World of Warcraft player, and a passionate developer I have decided that I would like to combine the two and set about developing some addins. Not only to improve my gameplay experience but as a great opportunity to learn something new. Does anyone have any advice on how to go about starting out? Is there an IDE one can use? How does one go about testing? Are there any ready made libraries available? Or would I get a better learning experience by ignoring the libraries and building from scratch? How do I oneshot Hogger? Would love to hear your advice, experiences and views. ANSWER: This article explains how to start pretty well. Your first bookmark is possibly the US Interface Forum, especially the Stickies for that: http://us.battle.net/wow/en/forum/1011693/ Then, grab some simple addons to learn how XML and LUA interacts. The WoWWiki HOWTO List is a good point here as well. One important thing to keep in mind: World of Warcraft is available in many languages. If you have a EU Account, you got an excellent testing bed by simply downloading the language Packs for Spanish, German and French. If you're an US Guy, check if you can get the Latin America version. That way, you can test it against another language version. Once you made 1 or 2 really small and simple addons just to learn how to use it, have a look at the various frameworks. WowAce is a popular one, but there are others. Just keep one thing in mind: Making an Addon is work. Maintaining one is even more work. With each new Patch, there may be breaking changes, and the next Addon will surely cause a big Exodus of Addons, just like Patch 2.0.1 did.
[ "plugins", "lua", "add-on", "world-of-warcraft" ]
18
28
2,430
4
0
2008-08-09T17:51:09.313000
2008-08-09T18:01:57.497000
6,890
7,101
How to wait for thread complete before continuing?
I have some code for starting a thread on the.NET CF 2.0: ThreadStart tStart = new ThreadStart(MyMethod); Thread t = new Thread(tStart); t.Start(); If I call this inside a loop the items completely out of order. How do introduce a wait after t.Start(), so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads?
How much order do you need to impose on the threads? If you just need all of the work started in the loop to finish before the code continues, but you don't care about the order the work within the loop finishes, then calling Join is the answer. To add more detail to Kevin Kenny's answer, you should call Join outside the loop. This means you will need a collection to hold references to the threads you started: // Start all of the threads. List startedThreads = new List (); foreach (...) { Thread thread = new Thread(new ThreadStart(MyMethod)); thread.Start(); startedThreads.Add(thread); } // Wait for all of the threads to finish. foreach (Thread thread in startedThreads) { thread.Join(); } In contrast, if you called Join inside the loop, the result would basically be the same as not using threads at all. Each iteration of the loop body would create and start a thread but then immediately Join it and wait for it to finish. If the individual threads produce some result (write a message in a log, for example) then the messages may still appear out of order because there's no coordination between the threads. It is possible to get the threads to output their results in order by coordinating them with a Monitor.
How to wait for thread complete before continuing? I have some code for starting a thread on the.NET CF 2.0: ThreadStart tStart = new ThreadStart(MyMethod); Thread t = new Thread(tStart); t.Start(); If I call this inside a loop the items completely out of order. How do introduce a wait after t.Start(), so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads?
TITLE: How to wait for thread complete before continuing? QUESTION: I have some code for starting a thread on the.NET CF 2.0: ThreadStart tStart = new ThreadStart(MyMethod); Thread t = new Thread(tStart); t.Start(); If I call this inside a loop the items completely out of order. How do introduce a wait after t.Start(), so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads? ANSWER: How much order do you need to impose on the threads? If you just need all of the work started in the loop to finish before the code continues, but you don't care about the order the work within the loop finishes, then calling Join is the answer. To add more detail to Kevin Kenny's answer, you should call Join outside the loop. This means you will need a collection to hold references to the threads you started: // Start all of the threads. List startedThreads = new List (); foreach (...) { Thread thread = new Thread(new ThreadStart(MyMethod)); thread.Start(); startedThreads.Add(thread); } // Wait for all of the threads to finish. foreach (Thread thread in startedThreads) { thread.Join(); } In contrast, if you called Join inside the loop, the result would basically be the same as not using threads at all. Each iteration of the loop body would create and start a thread but then immediately Join it and wait for it to finish. If the individual threads produce some result (write a message in a log, for example) then the messages may still appear out of order because there's no coordination between the threads. It is possible to get the threads to output their results in order by coordinating them with a Monitor.
[ "c#", "multithreading", "compact-framework" ]
13
16
19,738
3
0
2008-08-09T20:00:37.647000
2008-08-10T08:37:28.383000
6,891
6,916
Performance Considerations for throwing Exceptions
I have come across the following type of code many a times, and I wonder if this is a good practice (from Performance perspective) or not: try {... // some code } catch (Exception ex) {... // Do something throw new CustomException(ex); } Basically, what the coder is doing is that they are encompassing the exception in a custom exception and throwing that again. How does this differ in Performance from the following two: try {... // some code } catch (Exception ex) {.. // Do something throw ex; } or try {... // some code } catch (Exception ex) {.. // Do something throw; } Putting aside any functional or coding best practice arguments, is there any performance difference between the 3 approaches?
@Brad Tutterow The exception is not being lost in the first case, it is being passed in to the constructor. I will agree with you on the rest though, the second approach is a very bad idea because of the loss of stack trace. When I worked with.NET, I ran into many cases where other programmers did just that, and it frustrated me to no end when I needed to see the true cause of an exception, only to find it being rethrown from a huge try block where I now have no idea where the problem originated. I also second Brad's comment that you shouldn't worry about the performance. This kind of micro optimization is a HORRIBLE idea. Unless you are talking about throwing an exception in every iteration of a for loop that is running for a long time, you will more than likely not run into performance issues by the way of your exception usage. Always optimize performance when you have metrics that indicate you NEED to optimize performance, and then hit the spots that are proven to be the culprit. It is much better to have readable code with easy debugging capabilities (IE not hiding the stack trace) rather than make something run a nanosecond faster. A final note about wrapping exceptions into a custom exception... this can be a very useful construct, especially when dealing with UIs. You can wrap every known and reasonable exceptional case into some base custom exception (or one that extends from said base exception), and then the UI can just catch this base exception. When caught, the exception will need to provide means of displaying information to the user, say a ReadableMessage property, or something along those lines. Thus, any time the UI misses an exception, it is because of a bug you need to fix, and anytime it catches an exception, it is a known error condition that can and should be handled properly by the UI.
Performance Considerations for throwing Exceptions I have come across the following type of code many a times, and I wonder if this is a good practice (from Performance perspective) or not: try {... // some code } catch (Exception ex) {... // Do something throw new CustomException(ex); } Basically, what the coder is doing is that they are encompassing the exception in a custom exception and throwing that again. How does this differ in Performance from the following two: try {... // some code } catch (Exception ex) {.. // Do something throw ex; } or try {... // some code } catch (Exception ex) {.. // Do something throw; } Putting aside any functional or coding best practice arguments, is there any performance difference between the 3 approaches?
TITLE: Performance Considerations for throwing Exceptions QUESTION: I have come across the following type of code many a times, and I wonder if this is a good practice (from Performance perspective) or not: try {... // some code } catch (Exception ex) {... // Do something throw new CustomException(ex); } Basically, what the coder is doing is that they are encompassing the exception in a custom exception and throwing that again. How does this differ in Performance from the following two: try {... // some code } catch (Exception ex) {.. // Do something throw ex; } or try {... // some code } catch (Exception ex) {.. // Do something throw; } Putting aside any functional or coding best practice arguments, is there any performance difference between the 3 approaches? ANSWER: @Brad Tutterow The exception is not being lost in the first case, it is being passed in to the constructor. I will agree with you on the rest though, the second approach is a very bad idea because of the loss of stack trace. When I worked with.NET, I ran into many cases where other programmers did just that, and it frustrated me to no end when I needed to see the true cause of an exception, only to find it being rethrown from a huge try block where I now have no idea where the problem originated. I also second Brad's comment that you shouldn't worry about the performance. This kind of micro optimization is a HORRIBLE idea. Unless you are talking about throwing an exception in every iteration of a for loop that is running for a long time, you will more than likely not run into performance issues by the way of your exception usage. Always optimize performance when you have metrics that indicate you NEED to optimize performance, and then hit the spots that are proven to be the culprit. It is much better to have readable code with easy debugging capabilities (IE not hiding the stack trace) rather than make something run a nanosecond faster. A final note about wrapping exceptions into a custom exception... this can be a very useful construct, especially when dealing with UIs. You can wrap every known and reasonable exceptional case into some base custom exception (or one that extends from said base exception), and then the UI can just catch this base exception. When caught, the exception will need to provide means of displaying information to the user, say a ReadableMessage property, or something along those lines. Thus, any time the UI misses an exception, it is because of a bug you need to fix, and anytime it catches an exception, it is a known error condition that can and should be handled properly by the UI.
[ ".net", "exception", "optimization", "performance" ]
9
11
2,163
8
0
2008-08-09T20:01:09.050000
2008-08-09T21:17:35.057000
6,899
6,980
How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?
To illustrate, assume that I have two tables as follows: VehicleID Name 1 Chuck 2 Larry LocationID VehicleID City 1 1 New York 2 1 Seattle 3 1 Vancouver 4 2 Los Angeles 5 2 Houston I want to write a query to return the following results: VehicleID Name Locations 1 Chuck New York, Seattle, Vancouver 2 Larry Los Angeles, Houston I know that this can be done using server side cursors, ie: DECLARE @VehicleID int DECLARE @VehicleName varchar(100) DECLARE @LocationCity varchar(100) DECLARE @Locations varchar(4000) DECLARE @Results TABLE ( VehicleID int Name varchar(100) Locations varchar(4000) ) DECLARE VehiclesCursor CURSOR FOR SELECT [VehicleID], [Name] FROM [Vehicles] OPEN VehiclesCursor FETCH NEXT FROM VehiclesCursor INTO @VehicleID, @VehicleName WHILE @@FETCH_STATUS = 0 BEGIN SET @Locations = '' DECLARE LocationsCursor CURSOR FOR SELECT [City] FROM [Locations] WHERE [VehicleID] = @VehicleID OPEN LocationsCursor FETCH NEXT FROM LocationsCursor INTO @LocationCity WHILE @@FETCH_STATUS = 0 BEGIN SET @Locations = @Locations + @LocationCity FETCH NEXT FROM LocationsCursor INTO @LocationCity END CLOSE LocationsCursor DEALLOCATE LocationsCursor INSERT INTO @Results (VehicleID, Name, Locations) SELECT @VehicleID, @Name, @Locations END CLOSE VehiclesCursor DEALLOCATE VehiclesCursor SELECT * FROM @Results However, as you can see, this requires a great deal of code. What I would like is a generic function that would allow me to do something like this: SELECT VehicleID, Name, JOIN(SELECT City FROM Locations WHERE VehicleID = Vehicles.VehicleID, ', ') AS Locations FROM Vehicles Is this possible? Or something similar?
If you're using SQL Server 2005, you could use the FOR XML PATH command. SELECT [VehicleID], [Name], (STUFF((SELECT CAST(', ' + [City] AS VARCHAR(MAX)) FROM [Location] WHERE (VehicleID = Vehicle.VehicleID) FOR XML PATH ('')), 1, 2, '')) AS Locations FROM [Vehicle] It's a lot easier than using a cursor, and seems to work fairly well. Update For anyone still using this method with newer versions of SQL Server, there is another way of doing it which is a bit easier and more performant using the STRING_AGG method that has been available since SQL Server 2017. SELECT [VehicleID],[Name],(SELECT STRING_AGG([City], ', ') FROM [Location] WHERE VehicleID = V.VehicleID) AS Locations FROM [Vehicle] V This also allows a different separator to be specified as the second parameter, providing a little more flexibility over the former method.
How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field? To illustrate, assume that I have two tables as follows: VehicleID Name 1 Chuck 2 Larry LocationID VehicleID City 1 1 New York 2 1 Seattle 3 1 Vancouver 4 2 Los Angeles 5 2 Houston I want to write a query to return the following results: VehicleID Name Locations 1 Chuck New York, Seattle, Vancouver 2 Larry Los Angeles, Houston I know that this can be done using server side cursors, ie: DECLARE @VehicleID int DECLARE @VehicleName varchar(100) DECLARE @LocationCity varchar(100) DECLARE @Locations varchar(4000) DECLARE @Results TABLE ( VehicleID int Name varchar(100) Locations varchar(4000) ) DECLARE VehiclesCursor CURSOR FOR SELECT [VehicleID], [Name] FROM [Vehicles] OPEN VehiclesCursor FETCH NEXT FROM VehiclesCursor INTO @VehicleID, @VehicleName WHILE @@FETCH_STATUS = 0 BEGIN SET @Locations = '' DECLARE LocationsCursor CURSOR FOR SELECT [City] FROM [Locations] WHERE [VehicleID] = @VehicleID OPEN LocationsCursor FETCH NEXT FROM LocationsCursor INTO @LocationCity WHILE @@FETCH_STATUS = 0 BEGIN SET @Locations = @Locations + @LocationCity FETCH NEXT FROM LocationsCursor INTO @LocationCity END CLOSE LocationsCursor DEALLOCATE LocationsCursor INSERT INTO @Results (VehicleID, Name, Locations) SELECT @VehicleID, @Name, @Locations END CLOSE VehiclesCursor DEALLOCATE VehiclesCursor SELECT * FROM @Results However, as you can see, this requires a great deal of code. What I would like is a generic function that would allow me to do something like this: SELECT VehicleID, Name, JOIN(SELECT City FROM Locations WHERE VehicleID = Vehicles.VehicleID, ', ') AS Locations FROM Vehicles Is this possible? Or something similar?
TITLE: How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field? QUESTION: To illustrate, assume that I have two tables as follows: VehicleID Name 1 Chuck 2 Larry LocationID VehicleID City 1 1 New York 2 1 Seattle 3 1 Vancouver 4 2 Los Angeles 5 2 Houston I want to write a query to return the following results: VehicleID Name Locations 1 Chuck New York, Seattle, Vancouver 2 Larry Los Angeles, Houston I know that this can be done using server side cursors, ie: DECLARE @VehicleID int DECLARE @VehicleName varchar(100) DECLARE @LocationCity varchar(100) DECLARE @Locations varchar(4000) DECLARE @Results TABLE ( VehicleID int Name varchar(100) Locations varchar(4000) ) DECLARE VehiclesCursor CURSOR FOR SELECT [VehicleID], [Name] FROM [Vehicles] OPEN VehiclesCursor FETCH NEXT FROM VehiclesCursor INTO @VehicleID, @VehicleName WHILE @@FETCH_STATUS = 0 BEGIN SET @Locations = '' DECLARE LocationsCursor CURSOR FOR SELECT [City] FROM [Locations] WHERE [VehicleID] = @VehicleID OPEN LocationsCursor FETCH NEXT FROM LocationsCursor INTO @LocationCity WHILE @@FETCH_STATUS = 0 BEGIN SET @Locations = @Locations + @LocationCity FETCH NEXT FROM LocationsCursor INTO @LocationCity END CLOSE LocationsCursor DEALLOCATE LocationsCursor INSERT INTO @Results (VehicleID, Name, Locations) SELECT @VehicleID, @Name, @Locations END CLOSE VehiclesCursor DEALLOCATE VehiclesCursor SELECT * FROM @Results However, as you can see, this requires a great deal of code. What I would like is a generic function that would allow me to do something like this: SELECT VehicleID, Name, JOIN(SELECT City FROM Locations WHERE VehicleID = Vehicles.VehicleID, ', ') AS Locations FROM Vehicles Is this possible? Or something similar? ANSWER: If you're using SQL Server 2005, you could use the FOR XML PATH command. SELECT [VehicleID], [Name], (STUFF((SELECT CAST(', ' + [City] AS VARCHAR(MAX)) FROM [Location] WHERE (VehicleID = Vehicle.VehicleID) FOR XML PATH ('')), 1, 2, '')) AS Locations FROM [Vehicle] It's a lot easier than using a cursor, and seems to work fairly well. Update For anyone still using this method with newer versions of SQL Server, there is another way of doing it which is a bit easier and more performant using the STRING_AGG method that has been available since SQL Server 2017. SELECT [VehicleID],[Name],(SELECT STRING_AGG([City], ', ') FROM [Location] WHERE VehicleID = V.VehicleID) AS Locations FROM [Vehicle] V This also allows a different separator to be specified as the second parameter, providing a little more flexibility over the former method.
[ "sql", "sql-server", "string-concatenation" ]
214
282
173,541
13
0
2008-08-09T20:11:18.467000
2008-08-10T01:05:00.980000
6,904
2,401,184
Getting DirectoryNotFoundException when trying to Connect to Device with CoreCon API
I'm trying to use the CoreCon API in Visual Studio 2008 to programmatically launch device emulators. When I call device.Connect(), I inexplicably get a DirectoryNotFoundException. I get it if I try it in PowerShell or in C# Console Application. Here's the code I'm using: static void Main(string[] args) { DatastoreManager dm = new DatastoreManager(1033); Collection platforms = dm.GetPlatforms(); foreach (var p in platforms) { Console.WriteLine("{0} {1}", p.Name, p.Id); } Platform platform = platforms[3]; Console.WriteLine("Selected {0}", platform.Name); Device device = platform.GetDevices()[0]; device.Connect(); Console.WriteLine("Device Connected"); SystemInfo info = device.GetSystemInfo(); Console.WriteLine("System OS Version:{0}.{1}.{2}",info.OSMajor, info.OSMinor, info.OSBuildNo); Console.ReadLine(); } Does anyone know why I'm getting this error? I'm running this on WinXP 32-bit, plain jane Visual Studio 2008 Pro. I imagine it's some config issue since I can't do it from a Console app or PowerShell. Here's the stack trace: System.IO.DirectoryNotFoundException was unhandled Message="The system cannot find the path specified.\r\n" Source="Device Connection Manager" StackTrace: at Microsoft.VisualStudio.DeviceConnectivity.Interop.ConManServerClass.ConnectDevice() at Microsoft.SmartDevice.Connectivity.Device.Connect() at ConsoleApplication1.Program.Main(String[] args) in C:\Documents and Settings\Thomas\Local Settings\Application Data\Temporary Projects\ConsoleApplication1\Program.cs:line 23 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()
It can be found at:\Program files\Common Files\Microsoft Shared\CoreCon\1.0\Bin. This is the path where you can get this dll, so add this dll to your project.
Getting DirectoryNotFoundException when trying to Connect to Device with CoreCon API I'm trying to use the CoreCon API in Visual Studio 2008 to programmatically launch device emulators. When I call device.Connect(), I inexplicably get a DirectoryNotFoundException. I get it if I try it in PowerShell or in C# Console Application. Here's the code I'm using: static void Main(string[] args) { DatastoreManager dm = new DatastoreManager(1033); Collection platforms = dm.GetPlatforms(); foreach (var p in platforms) { Console.WriteLine("{0} {1}", p.Name, p.Id); } Platform platform = platforms[3]; Console.WriteLine("Selected {0}", platform.Name); Device device = platform.GetDevices()[0]; device.Connect(); Console.WriteLine("Device Connected"); SystemInfo info = device.GetSystemInfo(); Console.WriteLine("System OS Version:{0}.{1}.{2}",info.OSMajor, info.OSMinor, info.OSBuildNo); Console.ReadLine(); } Does anyone know why I'm getting this error? I'm running this on WinXP 32-bit, plain jane Visual Studio 2008 Pro. I imagine it's some config issue since I can't do it from a Console app or PowerShell. Here's the stack trace: System.IO.DirectoryNotFoundException was unhandled Message="The system cannot find the path specified.\r\n" Source="Device Connection Manager" StackTrace: at Microsoft.VisualStudio.DeviceConnectivity.Interop.ConManServerClass.ConnectDevice() at Microsoft.SmartDevice.Connectivity.Device.Connect() at ConsoleApplication1.Program.Main(String[] args) in C:\Documents and Settings\Thomas\Local Settings\Application Data\Temporary Projects\ConsoleApplication1\Program.cs:line 23 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()
TITLE: Getting DirectoryNotFoundException when trying to Connect to Device with CoreCon API QUESTION: I'm trying to use the CoreCon API in Visual Studio 2008 to programmatically launch device emulators. When I call device.Connect(), I inexplicably get a DirectoryNotFoundException. I get it if I try it in PowerShell or in C# Console Application. Here's the code I'm using: static void Main(string[] args) { DatastoreManager dm = new DatastoreManager(1033); Collection platforms = dm.GetPlatforms(); foreach (var p in platforms) { Console.WriteLine("{0} {1}", p.Name, p.Id); } Platform platform = platforms[3]; Console.WriteLine("Selected {0}", platform.Name); Device device = platform.GetDevices()[0]; device.Connect(); Console.WriteLine("Device Connected"); SystemInfo info = device.GetSystemInfo(); Console.WriteLine("System OS Version:{0}.{1}.{2}",info.OSMajor, info.OSMinor, info.OSBuildNo); Console.ReadLine(); } Does anyone know why I'm getting this error? I'm running this on WinXP 32-bit, plain jane Visual Studio 2008 Pro. I imagine it's some config issue since I can't do it from a Console app or PowerShell. Here's the stack trace: System.IO.DirectoryNotFoundException was unhandled Message="The system cannot find the path specified.\r\n" Source="Device Connection Manager" StackTrace: at Microsoft.VisualStudio.DeviceConnectivity.Interop.ConManServerClass.ConnectDevice() at Microsoft.SmartDevice.Connectivity.Device.Connect() at ConsoleApplication1.Program.Main(String[] args) in C:\Documents and Settings\Thomas\Local Settings\Application Data\Temporary Projects\ConsoleApplication1\Program.cs:line 23 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() ANSWER: It can be found at:\Program files\Common Files\Microsoft Shared\CoreCon\1.0\Bin. This is the path where you can get this dll, so add this dll to your project.
[ "c#", "visual-studio", "windows-mobile", "compact-framework", "corecon" ]
4
1
1,898
4
0
2008-08-09T20:22:19.490000
2010-03-08T12:20:52.483000
6,913
6,981
How do I best share an embeddable form in VB6?
Is there a good way to create a form in VB6 that can easily be embedded inside other forms? On a few occasions recently, I've wanted to design and code a Form object that I could plug into several other "parent" forms. My goal is to create a centralized piece of code for managing several UI components in a particular way, and then be able to use that (both the UI layout and the logic) in more than one place. I'm certainly willing to use code (rather than the Design View) to load the child form. The best I've come up with so far is to pull all of the interesting logic for the child form into a Class Module, and have each parent form lay out the UI (in a Picture control, perhaps) and pass that Picture object into the class module. The class then knows how to operate on the picture, and it assumes that all its expected pieces have been laid out appropriately. This approach has several downsides, and I'd like something a bit more elegant.
Take a look at VB6 UserControls; I think they are exactly what you need. You can create a UserControl within your project, add controls and code to that control, and then insert it onto a form just like standard VB6 controls. I've used UserControls to share UI layouts on many occasions and it works great.
How do I best share an embeddable form in VB6? Is there a good way to create a form in VB6 that can easily be embedded inside other forms? On a few occasions recently, I've wanted to design and code a Form object that I could plug into several other "parent" forms. My goal is to create a centralized piece of code for managing several UI components in a particular way, and then be able to use that (both the UI layout and the logic) in more than one place. I'm certainly willing to use code (rather than the Design View) to load the child form. The best I've come up with so far is to pull all of the interesting logic for the child form into a Class Module, and have each parent form lay out the UI (in a Picture control, perhaps) and pass that Picture object into the class module. The class then knows how to operate on the picture, and it assumes that all its expected pieces have been laid out appropriately. This approach has several downsides, and I'd like something a bit more elegant.
TITLE: How do I best share an embeddable form in VB6? QUESTION: Is there a good way to create a form in VB6 that can easily be embedded inside other forms? On a few occasions recently, I've wanted to design and code a Form object that I could plug into several other "parent" forms. My goal is to create a centralized piece of code for managing several UI components in a particular way, and then be able to use that (both the UI layout and the logic) in more than one place. I'm certainly willing to use code (rather than the Design View) to load the child form. The best I've come up with so far is to pull all of the interesting logic for the child form into a Class Module, and have each parent form lay out the UI (in a Picture control, perhaps) and pass that Picture object into the class module. The class then knows how to operate on the picture, and it assumes that all its expected pieces have been laid out appropriately. This approach has several downsides, and I'd like something a bit more elegant. ANSWER: Take a look at VB6 UserControls; I think they are exactly what you need. You can create a UserControl within your project, add controls and code to that control, and then insert it onto a form just like standard VB6 controls. I've used UserControls to share UI layouts on many occasions and it works great.
[ "forms", "vb6", "code-reuse" ]
6
9
629
1
0
2008-08-09T21:05:40.027000
2008-08-10T01:05:59.560000
6,915
6,955
How do you lazily construct a singleton object thread-safely?
Is there a way to implement a singleton object in C++ that is: Lazily constructed in a thread-safe manner (two threads might simultaneously be the first user of the singleton - it should still only be constructed once). Doesn't rely on static variables being constructed beforehand (so the singleton object is itself safe to use during the construction of static variables). (I don't know my C++ well enough, but is it the case that integral and constant static variables are initialized before any code is executed (ie, even before static constructors are executed - their values may already be "initialized" in the program image)? If so - perhaps this can be exploited to implement a singleton mutex - which can in turn be used to guard the creation of the real singleton..)
Basically, you're asking for synchronized creation of a singleton, without using any synchronization (previously-constructed variables). In general, no, this is not possible. You need something available for synchronization. As for your other question, yes, static variables which can be statically initialized (i.e. no runtime code necessary) are guaranteed to be initialized before other code is executed. This makes it possible to use a statically-initialized mutex to synchronize creation of the singleton. From the 2003 revision of the C++ standard: Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place. Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit. If you know that you will be using this singleton during the initialization of other static objects, I think you'll find that synchronization is a non-issue. To the best of my knowledge, all major compilers initialize static objects in a single thread, so thread-safety during static initialization. You can declare your singleton pointer to be NULL, and then check to see if it's been initialized before you use it. However, this assumes that you know that you'll use this singleton during static initialization. This is also not guaranteed by the standard, so if you want to be completely safe, use a statically-initialized mutex. Edit: Chris's suggestion to use an atomic compare-and-swap would certainly work. If portability is not an issue (and creating additional temporary singletons is not a problem), then it is a slightly lower overhead solution.
How do you lazily construct a singleton object thread-safely? Is there a way to implement a singleton object in C++ that is: Lazily constructed in a thread-safe manner (two threads might simultaneously be the first user of the singleton - it should still only be constructed once). Doesn't rely on static variables being constructed beforehand (so the singleton object is itself safe to use during the construction of static variables). (I don't know my C++ well enough, but is it the case that integral and constant static variables are initialized before any code is executed (ie, even before static constructors are executed - their values may already be "initialized" in the program image)? If so - perhaps this can be exploited to implement a singleton mutex - which can in turn be used to guard the creation of the real singleton..)
TITLE: How do you lazily construct a singleton object thread-safely? QUESTION: Is there a way to implement a singleton object in C++ that is: Lazily constructed in a thread-safe manner (two threads might simultaneously be the first user of the singleton - it should still only be constructed once). Doesn't rely on static variables being constructed beforehand (so the singleton object is itself safe to use during the construction of static variables). (I don't know my C++ well enough, but is it the case that integral and constant static variables are initialized before any code is executed (ie, even before static constructors are executed - their values may already be "initialized" in the program image)? If so - perhaps this can be exploited to implement a singleton mutex - which can in turn be used to guard the creation of the real singleton..) ANSWER: Basically, you're asking for synchronized creation of a singleton, without using any synchronization (previously-constructed variables). In general, no, this is not possible. You need something available for synchronization. As for your other question, yes, static variables which can be statically initialized (i.e. no runtime code necessary) are guaranteed to be initialized before other code is executed. This makes it possible to use a statically-initialized mutex to synchronize creation of the singleton. From the 2003 revision of the C++ standard: Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place. Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit. If you know that you will be using this singleton during the initialization of other static objects, I think you'll find that synchronization is a non-issue. To the best of my knowledge, all major compilers initialize static objects in a single thread, so thread-safety during static initialization. You can declare your singleton pointer to be NULL, and then check to see if it's been initialized before you use it. However, this assumes that you know that you'll use this singleton during static initialization. This is also not guaranteed by the standard, so if you want to be completely safe, use a statically-initialized mutex. Edit: Chris's suggestion to use an atomic compare-and-swap would certainly work. If portability is not an issue (and creating additional temporary singletons is not a problem), then it is a slightly lower overhead solution.
[ "c++", "multithreading", "thread-safety", "singleton", "lazy-initialization" ]
38
14
28,110
9
0
2008-08-09T21:16:29.193000
2008-08-09T23:52:40.253000
6,926
7,039
Beginning Shader Development
I want to get started doing some game development using Microsoft's XNA. Part of that is Shader development, but I have no idea how to get started. I know that nVidia's FX Composer is a great tool to develop shaders, but I did not find much useful and updated content on how to actually get started. What tutorials would you recommend?
Development of shaders in XNA (which obviously uses DirectX) requires knowledge of HLSL or shader assembly. I'd recommend getting familiar with the former before diving into the latter. Before writing any shaders, it's a good idea to get solid understanding of the shader pipeline, and attempt to get your mind around what is possible when using programmable shaders. When you're familiar with the life of a pixel (from source data all the way through to the screen) then understanding examples of shaders becomes a lot easier. Next make an attempt to write your own HLSL which does what the Fixed T&L pipeline used to do, just to get you hands dirty. This is the equivalent of a "hello world" program in vertex/pixel shader world. When you're able to do that and you understand what you've written you're ready to go onto the more fun stuff. As a next step you might want to simulate basic sepcular lighting in one of your shaders from a single light source. You can then adapt this down the track to use multiple lights. Play with colours, and movement of lights. This will help get familiar with the use of shader constants as well. When you have a couple of basic shaders together, you should attempt to make it so that your game/engine uses multiple/different shaders on different objects. Start adding some other bits like basic bump or normal maps. When you get to this stage, the world is your oyster. You can start diving into some funky effectcs, and even consider using the GPU for more than it was originally intended. For those who are a little more advanced, there are a couple of good books that are available for free online which have some great information from Nvidia here and here. Don't forget that there's an excellent series of books called ShaderX which covers some awesome shader stuff. There's 1, 2, 3, 4, 5 and 6 already in print, and 7 is coming soon. Good luck. If you get some shaders going, I'd love to see them:)
Beginning Shader Development I want to get started doing some game development using Microsoft's XNA. Part of that is Shader development, but I have no idea how to get started. I know that nVidia's FX Composer is a great tool to develop shaders, but I did not find much useful and updated content on how to actually get started. What tutorials would you recommend?
TITLE: Beginning Shader Development QUESTION: I want to get started doing some game development using Microsoft's XNA. Part of that is Shader development, but I have no idea how to get started. I know that nVidia's FX Composer is a great tool to develop shaders, but I did not find much useful and updated content on how to actually get started. What tutorials would you recommend? ANSWER: Development of shaders in XNA (which obviously uses DirectX) requires knowledge of HLSL or shader assembly. I'd recommend getting familiar with the former before diving into the latter. Before writing any shaders, it's a good idea to get solid understanding of the shader pipeline, and attempt to get your mind around what is possible when using programmable shaders. When you're familiar with the life of a pixel (from source data all the way through to the screen) then understanding examples of shaders becomes a lot easier. Next make an attempt to write your own HLSL which does what the Fixed T&L pipeline used to do, just to get you hands dirty. This is the equivalent of a "hello world" program in vertex/pixel shader world. When you're able to do that and you understand what you've written you're ready to go onto the more fun stuff. As a next step you might want to simulate basic sepcular lighting in one of your shaders from a single light source. You can then adapt this down the track to use multiple lights. Play with colours, and movement of lights. This will help get familiar with the use of shader constants as well. When you have a couple of basic shaders together, you should attempt to make it so that your game/engine uses multiple/different shaders on different objects. Start adding some other bits like basic bump or normal maps. When you get to this stage, the world is your oyster. You can start diving into some funky effectcs, and even consider using the GPU for more than it was originally intended. For those who are a little more advanced, there are a couple of good books that are available for free online which have some great information from Nvidia here and here. Don't forget that there's an excellent series of books called ShaderX which covers some awesome shader stuff. There's 1, 2, 3, 4, 5 and 6 already in print, and 7 is coming soon. Good luck. If you get some shaders going, I'd love to see them:)
[ "shader" ]
19
31
5,893
9
0
2008-08-09T21:57:07.427000
2008-08-10T04:21:32.333000
6,932
3,011,043
Transcoding audio and video
What is the best way to transcode audio and video to show on the web? I need to do it programmatically. I'd like to do something like YouTube or Google Video where users can upload whatever format they want, and I encode it to flv, mp3, and/or mp4. I could do it on our server, but I would rather use an EC2 instance or even a web service. We have a Windows 2008 server.
I strongly recommend ffmpeg. On Windows, I have found this site to host good binaries.
Transcoding audio and video What is the best way to transcode audio and video to show on the web? I need to do it programmatically. I'd like to do something like YouTube or Google Video where users can upload whatever format they want, and I encode it to flv, mp3, and/or mp4. I could do it on our server, but I would rather use an EC2 instance or even a web service. We have a Windows 2008 server.
TITLE: Transcoding audio and video QUESTION: What is the best way to transcode audio and video to show on the web? I need to do it programmatically. I'd like to do something like YouTube or Google Video where users can upload whatever format they want, and I encode it to flv, mp3, and/or mp4. I could do it on our server, but I would rather use an EC2 instance or even a web service. We have a Windows 2008 server. ANSWER: I strongly recommend ffmpeg. On Windows, I have found this site to host good binaries.
[ "audio", "video", "mp3", "flv", "mp4" ]
4
3
2,775
8
0
2008-08-09T22:19:59.580000
2010-06-10T01:13:18.793000
6,937
6,940
Visual Studio and dual/multiple monitors: how do I get optimized use out of my monitors?
Ultramon is a great program for dual monitors (stretching screen across monitors), but I was wondering if there is any way do to something in Visual Studio like have one tab of code open on one monitor and a second tab of code open on the second monitor with only one instance of Visual Studio running? Or are there any other suggestions on getting most bang for buck on dual monitors and Visual Studio?
Personally, I have my windows set up so that one my main monitor, I have the main visual studio monitor, so therefore my code window, maximized, with only the toolbox docked, on the left. This means the code window takes up as much space as possible, while keeping the left hand edge of the code close to the middle of the screen, where my eyes naturally look. My main monitor is a wide screen, so I find that gives me more than enough room for my code. My secondary monitor has a second window, which contains the tool windows that I use. So I have solution explorer, error list, task list (//todo: comments), output window, find results etc. all taking up as much space as they like on my secondary monitor. When debugging, the solution explorer moves the main monitor, and the watch, autos and locals windows take its place. I find this gives me a very large area to write code, and really helps usage of all of those additional windows, by giving them more real estate than they'd usually have. Update: In response to everyone talking about using the second monitor for documentation or running the app, I wholeheartedly agree, and forgot to mention how I do that. I use PowerMenu alot to acheive this. Basically I can right-click on any window and set Always On Top. So while i'm debugging, i want to see my output window, but then if I have to refer to some documentation, I just flick to Mozilla (on the second monitor), set it on top, and go back to visual studio. I find this lets me manage the tool windows without having to either shuffle them around a lot, or take up valuable space in the code window.
Visual Studio and dual/multiple monitors: how do I get optimized use out of my monitors? Ultramon is a great program for dual monitors (stretching screen across monitors), but I was wondering if there is any way do to something in Visual Studio like have one tab of code open on one monitor and a second tab of code open on the second monitor with only one instance of Visual Studio running? Or are there any other suggestions on getting most bang for buck on dual monitors and Visual Studio?
TITLE: Visual Studio and dual/multiple monitors: how do I get optimized use out of my monitors? QUESTION: Ultramon is a great program for dual monitors (stretching screen across monitors), but I was wondering if there is any way do to something in Visual Studio like have one tab of code open on one monitor and a second tab of code open on the second monitor with only one instance of Visual Studio running? Or are there any other suggestions on getting most bang for buck on dual monitors and Visual Studio? ANSWER: Personally, I have my windows set up so that one my main monitor, I have the main visual studio monitor, so therefore my code window, maximized, with only the toolbox docked, on the left. This means the code window takes up as much space as possible, while keeping the left hand edge of the code close to the middle of the screen, where my eyes naturally look. My main monitor is a wide screen, so I find that gives me more than enough room for my code. My secondary monitor has a second window, which contains the tool windows that I use. So I have solution explorer, error list, task list (//todo: comments), output window, find results etc. all taking up as much space as they like on my secondary monitor. When debugging, the solution explorer moves the main monitor, and the watch, autos and locals windows take its place. I find this gives me a very large area to write code, and really helps usage of all of those additional windows, by giving them more real estate than they'd usually have. Update: In response to everyone talking about using the second monitor for documentation or running the app, I wholeheartedly agree, and forgot to mention how I do that. I use PowerMenu alot to acheive this. Basically I can right-click on any window and set Always On Top. So while i'm debugging, i want to see my output window, but then if I have to refer to some documentation, I just flick to Mozilla (on the second monitor), set it on top, and go back to visual studio. I find this lets me manage the tool windows without having to either shuffle them around a lot, or take up valuable space in the code window.
[ "visual-studio", "monitor", "multiple-monitors" ]
48
60
92,053
11
0
2008-08-09T22:55:26.857000
2008-08-09T23:00:20.670000
6,957
7,458
Has anybody used Google Performance Tools?
Looking for feedback on: http://code.google.com/p/google-perftools/wiki/GooglePerformanceTools
There's a pretty good post that I read a while back that outlines some testing and analysis of GPT in a variety of scenarios
Has anybody used Google Performance Tools? Looking for feedback on: http://code.google.com/p/google-perftools/wiki/GooglePerformanceTools
TITLE: Has anybody used Google Performance Tools? QUESTION: Looking for feedback on: http://code.google.com/p/google-perftools/wiki/GooglePerformanceTools ANSWER: There's a pretty good post that I read a while back that outlines some testing and analysis of GPT in a variety of scenarios
[ "performance", "multithreading", "malloc", "google-perftools" ]
5
4
1,732
2
0
2008-08-10T00:01:18.770000
2008-08-11T00:53:54.403000
6,973
6,987
Invalid Resource File
When attempting to compile my C# project, I get the following error: 'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file. Having gone through many Google searches, I have determined that this is usually caused by a 256x256 image inside an icon used by the project. I've gone through all the icons and removed the 256x256 versions, but the error persists. Any ideas on how to get rid of this? @Mike: It showed up mysteriously one night. I've searched the csproj file, but there's no mention of a CSC97.tmp (I also checked the solution file, but I had no luck there either). In case it helps, I've posted the contents of the csproj file on pastebin. @Derek: No problem. Here's the compiler output. ------ Build started: Project: Infralution.Licensing, Configuration: Debug Any CPU ------ Infralution.Licensing -> C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll ------ Build started: Project: CleanerMenu, Configuration: Debug Any CPU ------ C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /main:CleanerMenu.Program /reference:"C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll" /reference:..\NotificationBar.dll /reference:..\PSTaskDialog.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:obj\Debug\Interop.IWshRuntimeLibrary.dll /debug+ /debug:full /optimize- /out:obj\Debug\CleanerMenu.exe /resource:obj\Debug\CleanerMenu.Form1.resources /resource:obj\Debug\CleanerMenu.frmAbout.resources /resource:obj\Debug\CleanerMenu.ModalProgressWindow.resources /resource:obj\Debug\CleanerMenu.Properties.Resources.resources /resource:obj\Debug\CleanerMenu.ShortcutPropertiesViewer.resources /resource:obj\Debug\CleanerMenu.LocalizedStrings.resources /resource:obj\Debug\CleanerMenu.UpdatedLicenseForm.resources /target:winexe /win32icon:CleanerMenu.ico ErrorHandler.cs Form1.cs Form1.Designer.cs frmAbout.cs frmAbout.Designer.cs Licensing.cs ModalProgressWindow.cs ModalProgressWindow.Designer.cs Program.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs Scanner.cs ShortcutPropertiesViewer.cs ShortcutPropertiesViewer.Designer.cs LocalizedStrings.Designer.cs UpdatedLicenseForm.cs UpdatedLicenseForm.Designer.cs error CS1583: 'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file Compile complete -- 1 errors, 0 warnings ------ Skipped Build: Project: CleanerMenu Installer, Configuration: Debug ------ Project not selected to build for this solution configuration ========== Build: 1 succeeded or up-to-date, 1 failed, 1 skipped ========== I have also uploaded the icon I am using. You can view it here. @Mike: Thanks! After removing everything but the 32x32 image, everything worked great. Now I can go back and add the other sizes one-by-one to see which one is causing me grief.:) @Derek: Since I first got the error, I'd done a complete reinstall of Windows (and along with it, the SDK.) It wasn't the main reason for the reinstall, but I had a slim hope that it would fix the problem. Now if only I can figure out why it previously worked with all the other sizes...
I don't know if this will help, but from this forum: Add an.ico file to the application section of the properties page, and recieved the error thats been described, when I checked the Icon file with an icon editor, it turn out that the file had more than one version of the image ie (16 x 16, 24 x 24, 32 x 32, 48 x 48 vista compressed), I removed the other formats that I didnt want resaved the file (just with 32x 32) and the application now compiles without error. Try opening the icon in an icon editor and see if you see other formats like described (also, try removing the icon and seeing if the project will build again, just to verify the icon is causing it).
Invalid Resource File When attempting to compile my C# project, I get the following error: 'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file. Having gone through many Google searches, I have determined that this is usually caused by a 256x256 image inside an icon used by the project. I've gone through all the icons and removed the 256x256 versions, but the error persists. Any ideas on how to get rid of this? @Mike: It showed up mysteriously one night. I've searched the csproj file, but there's no mention of a CSC97.tmp (I also checked the solution file, but I had no luck there either). In case it helps, I've posted the contents of the csproj file on pastebin. @Derek: No problem. Here's the compiler output. ------ Build started: Project: Infralution.Licensing, Configuration: Debug Any CPU ------ Infralution.Licensing -> C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll ------ Build started: Project: CleanerMenu, Configuration: Debug Any CPU ------ C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /main:CleanerMenu.Program /reference:"C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll" /reference:..\NotificationBar.dll /reference:..\PSTaskDialog.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:obj\Debug\Interop.IWshRuntimeLibrary.dll /debug+ /debug:full /optimize- /out:obj\Debug\CleanerMenu.exe /resource:obj\Debug\CleanerMenu.Form1.resources /resource:obj\Debug\CleanerMenu.frmAbout.resources /resource:obj\Debug\CleanerMenu.ModalProgressWindow.resources /resource:obj\Debug\CleanerMenu.Properties.Resources.resources /resource:obj\Debug\CleanerMenu.ShortcutPropertiesViewer.resources /resource:obj\Debug\CleanerMenu.LocalizedStrings.resources /resource:obj\Debug\CleanerMenu.UpdatedLicenseForm.resources /target:winexe /win32icon:CleanerMenu.ico ErrorHandler.cs Form1.cs Form1.Designer.cs frmAbout.cs frmAbout.Designer.cs Licensing.cs ModalProgressWindow.cs ModalProgressWindow.Designer.cs Program.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs Scanner.cs ShortcutPropertiesViewer.cs ShortcutPropertiesViewer.Designer.cs LocalizedStrings.Designer.cs UpdatedLicenseForm.cs UpdatedLicenseForm.Designer.cs error CS1583: 'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file Compile complete -- 1 errors, 0 warnings ------ Skipped Build: Project: CleanerMenu Installer, Configuration: Debug ------ Project not selected to build for this solution configuration ========== Build: 1 succeeded or up-to-date, 1 failed, 1 skipped ========== I have also uploaded the icon I am using. You can view it here. @Mike: Thanks! After removing everything but the 32x32 image, everything worked great. Now I can go back and add the other sizes one-by-one to see which one is causing me grief.:) @Derek: Since I first got the error, I'd done a complete reinstall of Windows (and along with it, the SDK.) It wasn't the main reason for the reinstall, but I had a slim hope that it would fix the problem. Now if only I can figure out why it previously worked with all the other sizes...
TITLE: Invalid Resource File QUESTION: When attempting to compile my C# project, I get the following error: 'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file. Having gone through many Google searches, I have determined that this is usually caused by a 256x256 image inside an icon used by the project. I've gone through all the icons and removed the 256x256 versions, but the error persists. Any ideas on how to get rid of this? @Mike: It showed up mysteriously one night. I've searched the csproj file, but there's no mention of a CSC97.tmp (I also checked the solution file, but I had no luck there either). In case it helps, I've posted the contents of the csproj file on pastebin. @Derek: No problem. Here's the compiler output. ------ Build started: Project: Infralution.Licensing, Configuration: Debug Any CPU ------ Infralution.Licensing -> C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll ------ Build started: Project: CleanerMenu, Configuration: Debug Any CPU ------ C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /main:CleanerMenu.Program /reference:"C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll" /reference:..\NotificationBar.dll /reference:..\PSTaskDialog.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:obj\Debug\Interop.IWshRuntimeLibrary.dll /debug+ /debug:full /optimize- /out:obj\Debug\CleanerMenu.exe /resource:obj\Debug\CleanerMenu.Form1.resources /resource:obj\Debug\CleanerMenu.frmAbout.resources /resource:obj\Debug\CleanerMenu.ModalProgressWindow.resources /resource:obj\Debug\CleanerMenu.Properties.Resources.resources /resource:obj\Debug\CleanerMenu.ShortcutPropertiesViewer.resources /resource:obj\Debug\CleanerMenu.LocalizedStrings.resources /resource:obj\Debug\CleanerMenu.UpdatedLicenseForm.resources /target:winexe /win32icon:CleanerMenu.ico ErrorHandler.cs Form1.cs Form1.Designer.cs frmAbout.cs frmAbout.Designer.cs Licensing.cs ModalProgressWindow.cs ModalProgressWindow.Designer.cs Program.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs Scanner.cs ShortcutPropertiesViewer.cs ShortcutPropertiesViewer.Designer.cs LocalizedStrings.Designer.cs UpdatedLicenseForm.cs UpdatedLicenseForm.Designer.cs error CS1583: 'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file Compile complete -- 1 errors, 0 warnings ------ Skipped Build: Project: CleanerMenu Installer, Configuration: Debug ------ Project not selected to build for this solution configuration ========== Build: 1 succeeded or up-to-date, 1 failed, 1 skipped ========== I have also uploaded the icon I am using. You can view it here. @Mike: Thanks! After removing everything but the 32x32 image, everything worked great. Now I can go back and add the other sizes one-by-one to see which one is causing me grief.:) @Derek: Since I first got the error, I'd done a complete reinstall of Windows (and along with it, the SDK.) It wasn't the main reason for the reinstall, but I had a slim hope that it would fix the problem. Now if only I can figure out why it previously worked with all the other sizes... ANSWER: I don't know if this will help, but from this forum: Add an.ico file to the application section of the properties page, and recieved the error thats been described, when I checked the Icon file with an icon editor, it turn out that the file had more than one version of the image ie (16 x 16, 24 x 24, 32 x 32, 48 x 48 vista compressed), I removed the other formats that I didnt want resaved the file (just with 32x 32) and the application now compiles without error. Try opening the icon in an icon editor and see if you see other formats like described (also, try removing the icon and seeing if the project will build again, just to verify the icon is causing it).
[ "c#", "visual-studio", "resources" ]
12
6
14,241
5
0
2008-08-10T00:50:16.283000
2008-08-10T01:32:19.740000
7,015
7,020
Multicore Text File Parsing
I have a quad core machine and would like to write some code to parse a text file that takes advantage of all four cores. The text file basically contains one record per line. Multithreading isn't my forte so I'm wondering if anyone could give me some patterns that I might be able to use to parse the file in an optimal manner. My first thoughts are to read all the lines into some sort of queue and then spin up threads to pull the lines off the queue and process them, but that means the queue would have to exist in memory and these are fairly large files so I'm not so keen on that idea. My next thoughts are to have some sort of controller that will read in a line and assign it a thread to parse, but I'm not sure if the controller will end up being a bottleneck if the threads are processing the lines faster than it can read and assign them. I know there's probably another simpler solution than both of these but at the moment I'm just not seeing it.
I'd go with your original idea. If you are concerned that the queue might get too large implement a buffer-zone for it (i.e. If is gets above 100 lines the stop reading the file and if it gets below 20 then start reading again. You'd need to do some testing to find the optimal barriers). Make it so that any of the threads can potentially be the "reader thread" as it has to lock the queue to pull an item out anyway it can also check to see if the "low buffer region" has been hit and start reading again. While it's doing this the other threads can read out the rest of the queue. Or if you prefer, have one reader thread assign the lines to three other processor threads (via their own queues) and implement a work-stealing strategy. I've never done this so I don't know how hard it is.
Multicore Text File Parsing I have a quad core machine and would like to write some code to parse a text file that takes advantage of all four cores. The text file basically contains one record per line. Multithreading isn't my forte so I'm wondering if anyone could give me some patterns that I might be able to use to parse the file in an optimal manner. My first thoughts are to read all the lines into some sort of queue and then spin up threads to pull the lines off the queue and process them, but that means the queue would have to exist in memory and these are fairly large files so I'm not so keen on that idea. My next thoughts are to have some sort of controller that will read in a line and assign it a thread to parse, but I'm not sure if the controller will end up being a bottleneck if the threads are processing the lines faster than it can read and assign them. I know there's probably another simpler solution than both of these but at the moment I'm just not seeing it.
TITLE: Multicore Text File Parsing QUESTION: I have a quad core machine and would like to write some code to parse a text file that takes advantage of all four cores. The text file basically contains one record per line. Multithreading isn't my forte so I'm wondering if anyone could give me some patterns that I might be able to use to parse the file in an optimal manner. My first thoughts are to read all the lines into some sort of queue and then spin up threads to pull the lines off the queue and process them, but that means the queue would have to exist in memory and these are fairly large files so I'm not so keen on that idea. My next thoughts are to have some sort of controller that will read in a line and assign it a thread to parse, but I'm not sure if the controller will end up being a bottleneck if the threads are processing the lines faster than it can read and assign them. I know there's probably another simpler solution than both of these but at the moment I'm just not seeing it. ANSWER: I'd go with your original idea. If you are concerned that the queue might get too large implement a buffer-zone for it (i.e. If is gets above 100 lines the stop reading the file and if it gets below 20 then start reading again. You'd need to do some testing to find the optimal barriers). Make it so that any of the threads can potentially be the "reader thread" as it has to lock the queue to pull an item out anyway it can also check to see if the "low buffer region" has been hit and start reading again. While it's doing this the other threads can read out the rest of the queue. Or if you prefer, have one reader thread assign the lines to three other processor threads (via their own queues) and implement a work-stealing strategy. I've never done this so I don't know how hard it is.
[ "c#", "multithreading" ]
10
9
2,995
7
0
2008-08-10T03:07:39.157000
2008-08-10T03:19:36.623000
7,031
7,087
Login Script with hidden buttons
I have been using PHP and JavaScript for building my dad's website. He wants to incorporate a login system into his website, and I have the design for the system using PHP. My problem is how do I show buttons if the person is logged in?­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ For Example - You have Home, Products, About Us, and Contact. I want to have buttons for Dealer, Distributor, and maybe other information if the user is logged in. So I will have Home, Products, About Us, Contacts, Dealer (if dealer login), Distributor (if distributor login), and so forth. Would JavaScript be a good way to do this or would PHP, or maybe even both? Using JavaScript to show and hide buttons, and PHP to check to see which buttons to show. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
Regarding security, you cannot trust what comes from the client: The visitor can see all your code (HTML and Javascript, not PHP) and try stuff The visitor may not even use a browser; it's trivially easy to send a request with a script This means hiding the buttons is good User Interface design (because you can't use them if you are not logged in). But it's not a security feature. The security feature is checking, on the server, that the visitor is logged in before each action that requires it. If you don't intend to show the buttons, it's not useful to send the HTML and images to the browser and then hide them with Javascript. I would check with PHP.
Login Script with hidden buttons I have been using PHP and JavaScript for building my dad's website. He wants to incorporate a login system into his website, and I have the design for the system using PHP. My problem is how do I show buttons if the person is logged in?­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ For Example - You have Home, Products, About Us, and Contact. I want to have buttons for Dealer, Distributor, and maybe other information if the user is logged in. So I will have Home, Products, About Us, Contacts, Dealer (if dealer login), Distributor (if distributor login), and so forth. Would JavaScript be a good way to do this or would PHP, or maybe even both? Using JavaScript to show and hide buttons, and PHP to check to see which buttons to show. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: Login Script with hidden buttons QUESTION: I have been using PHP and JavaScript for building my dad's website. He wants to incorporate a login system into his website, and I have the design for the system using PHP. My problem is how do I show buttons if the person is logged in?­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ For Example - You have Home, Products, About Us, and Contact. I want to have buttons for Dealer, Distributor, and maybe other information if the user is logged in. So I will have Home, Products, About Us, Contacts, Dealer (if dealer login), Distributor (if distributor login), and so forth. Would JavaScript be a good way to do this or would PHP, or maybe even both? Using JavaScript to show and hide buttons, and PHP to check to see which buttons to show. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: Regarding security, you cannot trust what comes from the client: The visitor can see all your code (HTML and Javascript, not PHP) and try stuff The visitor may not even use a browser; it's trivially easy to send a request with a script This means hiding the buttons is good User Interface design (because you can't use them if you are not logged in). But it's not a security feature. The security feature is checking, on the server, that the visitor is logged in before each action that requires it. If you don't intend to show the buttons, it's not useful to send the HTML and images to the browser and then hide them with Javascript. I would check with PHP.
[ "javascript", "php" ]
24
20
6,009
6
0
2008-08-10T04:00:06.773000
2008-08-10T07:59:22.890000
7,034
2,366,237
Graph visualization library in JavaScript
I have a data structure that represents a directed graph, and I want to render that dynamically on an HTML page. These graphs will usually be just a few nodes, maybe ten at the very upper end, so my guess is that performance isn't going to be a big deal. Ideally, I'd like to be able to hook it in with jQuery so that users can tweak the layout manually by dragging the nodes around. Note: I'm not looking for a charting library.
I've just put together what you may be looking for: http://www.graphdracula.net It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this: var g = new Graph(); g.addEdge("strawberry", "cherry"); g.addEdge("cherry", "apple"); g.addEdge("id34", "cherry"); I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask! You may want to have a look at other projects, too! Below are two meta-comparisons: SocialCompare has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones. DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph": Here's a list of similar projects (some have been already mentioned here): Pure JavaScript Libraries vis.js supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. MIT licensed and developed by a Dutch firm specializing in research on self-organizing networks. Cytoscape.js - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by @maxkfranz (see his answer below ) with help from several universities and other organizations. The JavaScript InfoVis Toolkit - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the Hyperbolic Tree. Built by Twitter dataviz architect Nicolas Garcia Belmonte and bought by Sencha in 2010. D3.js Powerful multi-purpose JS visualization library, the successor of Protovis. See the force-directed graph example, and other graph examples in the gallery. Plotly's JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython here, human interaction example here, and JS Embed API. sigma.js Lightweight but powerful library for drawing graphs jsPlumb jQuery plug-in for creating interactive connected graphs Springy - a force-directed graph layout algorithm JS Graph It - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines. RaphaelJS's Graffle - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that. JointJS Core - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package mxGraph Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in draw.io. Commercial libraries GoJS Interactive graph drawing and layout library yFiles for HTML Commercial graph drawing and layout library KeyLines Commercial JS network visualization toolkit ZoomCharts Commercial multi-purpose visualization library Syncfusion JavaScript Diagram Commercial diagram library for drawing and visualization. Abandoned libraries Cytoscape Web Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js) Canviz JS renderer for Graphviz graphs. Abandoned in Sep 2013. arbor.js Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several semi-maintained forks exist. jssvggraph "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012. jsdot Client side graph drawing application. Abandoned in 2011. Protovis Graphical Toolkit for Visualization (JavaScript). Replaced by d3. Moo Wheel Interactive JS representation for connections and relations (2008) JSViz 2007-era graph visualization script dagre Graph layout for JavaScript Non-Javascript Libraries Graphviz Sophisticated graph visualization language Graphviz has been compiled to Javascript using Emscripten here with an online interactive demo here Flare Beautiful and powerful Flash based graph drawing NodeBox Python Graph Visualization Processing.js Javascript port of the Processing library by John Resig
Graph visualization library in JavaScript I have a data structure that represents a directed graph, and I want to render that dynamically on an HTML page. These graphs will usually be just a few nodes, maybe ten at the very upper end, so my guess is that performance isn't going to be a big deal. Ideally, I'd like to be able to hook it in with jQuery so that users can tweak the layout manually by dragging the nodes around. Note: I'm not looking for a charting library.
TITLE: Graph visualization library in JavaScript QUESTION: I have a data structure that represents a directed graph, and I want to render that dynamically on an HTML page. These graphs will usually be just a few nodes, maybe ten at the very upper end, so my guess is that performance isn't going to be a big deal. Ideally, I'd like to be able to hook it in with jQuery so that users can tweak the layout manually by dragging the nodes around. Note: I'm not looking for a charting library. ANSWER: I've just put together what you may be looking for: http://www.graphdracula.net It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this: var g = new Graph(); g.addEdge("strawberry", "cherry"); g.addEdge("cherry", "apple"); g.addEdge("id34", "cherry"); I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask! You may want to have a look at other projects, too! Below are two meta-comparisons: SocialCompare has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones. DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph": Here's a list of similar projects (some have been already mentioned here): Pure JavaScript Libraries vis.js supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. MIT licensed and developed by a Dutch firm specializing in research on self-organizing networks. Cytoscape.js - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by @maxkfranz (see his answer below ) with help from several universities and other organizations. The JavaScript InfoVis Toolkit - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the Hyperbolic Tree. Built by Twitter dataviz architect Nicolas Garcia Belmonte and bought by Sencha in 2010. D3.js Powerful multi-purpose JS visualization library, the successor of Protovis. See the force-directed graph example, and other graph examples in the gallery. Plotly's JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython here, human interaction example here, and JS Embed API. sigma.js Lightweight but powerful library for drawing graphs jsPlumb jQuery plug-in for creating interactive connected graphs Springy - a force-directed graph layout algorithm JS Graph It - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines. RaphaelJS's Graffle - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that. JointJS Core - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package mxGraph Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in draw.io. Commercial libraries GoJS Interactive graph drawing and layout library yFiles for HTML Commercial graph drawing and layout library KeyLines Commercial JS network visualization toolkit ZoomCharts Commercial multi-purpose visualization library Syncfusion JavaScript Diagram Commercial diagram library for drawing and visualization. Abandoned libraries Cytoscape Web Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js) Canviz JS renderer for Graphviz graphs. Abandoned in Sep 2013. arbor.js Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several semi-maintained forks exist. jssvggraph "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012. jsdot Client side graph drawing application. Abandoned in 2011. Protovis Graphical Toolkit for Visualization (JavaScript). Replaced by d3. Moo Wheel Interactive JS representation for connections and relations (2008) JSViz 2007-era graph visualization script dagre Graph layout for JavaScript Non-Javascript Libraries Graphviz Sophisticated graph visualization language Graphviz has been compiled to Javascript using Emscripten here with an online interactive demo here Flare Beautiful and powerful Flash based graph drawing NodeBox Python Graph Visualization Processing.js Javascript port of the Processing library by John Resig
[ "javascript", "jquery", "data-structures", "graph-layout" ]
523
1,004
502,741
4
0
2008-08-10T04:07:52.423000
2010-03-02T19:48:15.093000
7,035
7,068
How to show a GUI message box from a bash script in linux?
I'm writing a few little bash scripts under Ubuntu linux. I want to be able to run them from the GUI without needing a terminal window to enter any input or view any output. So far the only input required is a password for sudo - and gksudo handles that fine. But I haven't found an easy way to show a message box yet. Is there some kind of 'gkmessage' command available? I'd prefer something present in a default Ubuntu install, but I don't mind installing a new package if necessary.
I believe Zenity will do what you want. It's specifically designed for displaying GTK dialogs from the command line, and it's available as an Ubuntu package.
How to show a GUI message box from a bash script in linux? I'm writing a few little bash scripts under Ubuntu linux. I want to be able to run them from the GUI without needing a terminal window to enter any input or view any output. So far the only input required is a password for sudo - and gksudo handles that fine. But I haven't found an easy way to show a message box yet. Is there some kind of 'gkmessage' command available? I'd prefer something present in a default Ubuntu install, but I don't mind installing a new package if necessary.
TITLE: How to show a GUI message box from a bash script in linux? QUESTION: I'm writing a few little bash scripts under Ubuntu linux. I want to be able to run them from the GUI without needing a terminal window to enter any input or view any output. So far the only input required is a password for sudo - and gksudo handles that fine. But I haven't found an easy way to show a message box yet. Is there some kind of 'gkmessage' command available? I'd prefer something present in a default Ubuntu install, but I don't mind installing a new package if necessary. ANSWER: I believe Zenity will do what you want. It's specifically designed for displaying GTK dialogs from the command line, and it's available as an Ubuntu package.
[ "linux", "bash", "scripting", "ubuntu", "gtk" ]
184
168
224,245
14
0
2008-08-10T04:07:55.043000
2008-08-10T06:40:47.603000
7,074
7,077
What is the difference between String and string in C#?
What are the differences between these two, and which one should I use? string s = "Hello world!"; String s = "Hello world!";
string is an alias in C# for System.String. So technically, there is no difference. It's like int vs. System.Int32. As far as guidelines, it's generally recommended to use string any time you're referring to an object. e.g. string place = "world"; Likewise, I think it's generally recommended to use String if you need to refer specifically to the class. e.g. string greet = String.Format("Hello {0}!", place); This is the style that Microsoft tends to use in their examples. It appears that the guidance in this area may have changed, as StyleCop now enforces the use of the C# specific aliases.
What is the difference between String and string in C#? What are the differences between these two, and which one should I use? string s = "Hello world!"; String s = "Hello world!";
TITLE: What is the difference between String and string in C#? QUESTION: What are the differences between these two, and which one should I use? string s = "Hello world!"; String s = "Hello world!"; ANSWER: string is an alias in C# for System.String. So technically, there is no difference. It's like int vs. System.Int32. As far as guidelines, it's generally recommended to use string any time you're referring to an object. e.g. string place = "world"; Likewise, I think it's generally recommended to use String if you need to refer specifically to the class. e.g. string greet = String.Format("Hello {0}!", place); This is the style that Microsoft tends to use in their examples. It appears that the guidance in this area may have changed, as StyleCop now enforces the use of the C# specific aliases.
[ "c#", ".net", "string", "types", "alias" ]
7,529
7,062
1,308,690
68
0
2008-08-10T07:18:02.320000
2008-08-10T07:22:02.030000
7,084
13,858
When should I use type abstraction in embedded systems
I've worked on a number of different embedded systems. They have all used typedef s (or #defines ) for types such as UINT32. This is a good technique as it drives home the size of the type to the programmer and makes you more conscious of chances for overflow etc. But on some systems you know that the compiler and processor won't change for the life of the project. So what should influence your decision to create and enforce project-specific types? EDIT I think I managed to lose the gist of my question, and maybe it's really two. With embedded programming you may need types of specific size for interfaces and also to cope with restricted resources such as RAM. This can't be avoided, but you can choose to use the basic types from the compiler. For everything else the types have less importance. You need to be careful not to cause overflow and may need to watch out for register and stack usage. Which may lead you to UINT16, UCHAR. Using types such as UCHAR can add compiler 'fluff' however. Because registers are typically larger, some compilers may add code to force the result into the type. i++; can become ADD REG,1 AND REG, 0xFF which is unecessary. So I think my question should have been:- given the constraints of embedded software what is the best policy to set for a project which will have many people working on it - not all of whom will be of the same level of experience.
I use type abstraction very rarely. Here are my arguments, sorted in increasing order of subjectivity: Local variables are different from struct members and arrays in the sense that you want them to fit in a register. On a 32b/64b target, a local int16_t can make code slower compared to a local int since the compiler will have to add operations to /force/ overflow according to the semantics of int16_t. While C99 defines an intfast_t typedef, AFAIK a plain int will fit in a register just as well, and it sure is a shorter name. Organizations which like these typedefs almost invariably end up with several of them ( INT32, int32_t, INT32_T, ad infinitum). Organizations using built-in types are thus better off, in a way, having just one set of names. I wish people used the typedefs from stdint.h or windows.h or anything existing; and when a target doesn't have that.h file, how hard is it to add one? The typedefs can theoretically aid portability, but I, for one, never gained a thing from them. Is there a useful system you can port from a 32b target to a 16b one? Is there a 16b system that isn't trivial to port to a 32b target? Moreover, if most vars are ints, you'll actually gain something from the 32 bits on the new target, but if they are int16_t, you won't. And the places which are hard to port tend to require manual inspection anyway; before you try a port, you don't know where they are. Now, if someone thinks it's so easy to port things if you have typedefs all over the place - when time comes to port, which happens to few systems, write a script converting all names in the code base. This should work according to the "no manual inspection required" logic, and it postpones the effort to the point in time where it actually gives benefit. Now if portability may be a theoretical benefit of the typedefs, readability sure goes down the drain. Just look at stdint.h: {int,uint}{max,fast,least}{8,16,32,64}_t. Lots of types. A program has lots of variables; is it really that easy to understand which need to be int_fast16_t and which need to be uint_least32_t? How many times are we silently converting between them, making them entirely pointless? (I particularly like BOOL/Bool/eBool/boolean/bool/int conversions. Every program written by an orderly organization mandating typedefs is littered with that). Of course in C++ we could make the type system more strict, by wrapping numbers in template class instantiations with overloaded operators and stuff. This means that you'll now get error messages of the form "class Number has no operator+ overload for argument of type class Number, candidates are..." I don't call this "readability", either. Your chances of implementing these wrapper classes correctly are microscopic, and most of the time you'll wait for the innumerable template instantiations to compile.
When should I use type abstraction in embedded systems I've worked on a number of different embedded systems. They have all used typedef s (or #defines ) for types such as UINT32. This is a good technique as it drives home the size of the type to the programmer and makes you more conscious of chances for overflow etc. But on some systems you know that the compiler and processor won't change for the life of the project. So what should influence your decision to create and enforce project-specific types? EDIT I think I managed to lose the gist of my question, and maybe it's really two. With embedded programming you may need types of specific size for interfaces and also to cope with restricted resources such as RAM. This can't be avoided, but you can choose to use the basic types from the compiler. For everything else the types have less importance. You need to be careful not to cause overflow and may need to watch out for register and stack usage. Which may lead you to UINT16, UCHAR. Using types such as UCHAR can add compiler 'fluff' however. Because registers are typically larger, some compilers may add code to force the result into the type. i++; can become ADD REG,1 AND REG, 0xFF which is unecessary. So I think my question should have been:- given the constraints of embedded software what is the best policy to set for a project which will have many people working on it - not all of whom will be of the same level of experience.
TITLE: When should I use type abstraction in embedded systems QUESTION: I've worked on a number of different embedded systems. They have all used typedef s (or #defines ) for types such as UINT32. This is a good technique as it drives home the size of the type to the programmer and makes you more conscious of chances for overflow etc. But on some systems you know that the compiler and processor won't change for the life of the project. So what should influence your decision to create and enforce project-specific types? EDIT I think I managed to lose the gist of my question, and maybe it's really two. With embedded programming you may need types of specific size for interfaces and also to cope with restricted resources such as RAM. This can't be avoided, but you can choose to use the basic types from the compiler. For everything else the types have less importance. You need to be careful not to cause overflow and may need to watch out for register and stack usage. Which may lead you to UINT16, UCHAR. Using types such as UCHAR can add compiler 'fluff' however. Because registers are typically larger, some compilers may add code to force the result into the type. i++; can become ADD REG,1 AND REG, 0xFF which is unecessary. So I think my question should have been:- given the constraints of embedded software what is the best policy to set for a project which will have many people working on it - not all of whom will be of the same level of experience. ANSWER: I use type abstraction very rarely. Here are my arguments, sorted in increasing order of subjectivity: Local variables are different from struct members and arrays in the sense that you want them to fit in a register. On a 32b/64b target, a local int16_t can make code slower compared to a local int since the compiler will have to add operations to /force/ overflow according to the semantics of int16_t. While C99 defines an intfast_t typedef, AFAIK a plain int will fit in a register just as well, and it sure is a shorter name. Organizations which like these typedefs almost invariably end up with several of them ( INT32, int32_t, INT32_T, ad infinitum). Organizations using built-in types are thus better off, in a way, having just one set of names. I wish people used the typedefs from stdint.h or windows.h or anything existing; and when a target doesn't have that.h file, how hard is it to add one? The typedefs can theoretically aid portability, but I, for one, never gained a thing from them. Is there a useful system you can port from a 32b target to a 16b one? Is there a 16b system that isn't trivial to port to a 32b target? Moreover, if most vars are ints, you'll actually gain something from the 32 bits on the new target, but if they are int16_t, you won't. And the places which are hard to port tend to require manual inspection anyway; before you try a port, you don't know where they are. Now, if someone thinks it's so easy to port things if you have typedefs all over the place - when time comes to port, which happens to few systems, write a script converting all names in the code base. This should work according to the "no manual inspection required" logic, and it postpones the effort to the point in time where it actually gives benefit. Now if portability may be a theoretical benefit of the typedefs, readability sure goes down the drain. Just look at stdint.h: {int,uint}{max,fast,least}{8,16,32,64}_t. Lots of types. A program has lots of variables; is it really that easy to understand which need to be int_fast16_t and which need to be uint_least32_t? How many times are we silently converting between them, making them entirely pointless? (I particularly like BOOL/Bool/eBool/boolean/bool/int conversions. Every program written by an orderly organization mandating typedefs is littered with that). Of course in C++ we could make the type system more strict, by wrapping numbers in template class instantiations with overloaded operators and stuff. This means that you'll now get error messages of the form "class Number has no operator+ overload for argument of type class Number, candidates are..." I don't call this "readability", either. Your chances of implementing these wrapper classes correctly are microscopic, and most of the time you'll wait for the innumerable template instantiations to compile.
[ "c", "embedded" ]
22
18
2,634
9
0
2008-08-10T07:50:54.250000
2008-08-17T19:15:31.027000
7,089
7,098
Creating rounded corners using CSS
How can I create rounded corners using CSS?
Since CSS3 was introduced, the best way to add rounded corners using CSS is by using the border-radius property. You can read the spec on the property, or get some useful implementation information on MDN: If you are using a browser that doesn't implement border-radius (Chrome pre-v4, Firefox pre-v4, IE8, Opera pre-v10.5, Safari pre-v5), then the links below detail a whole bunch of different approaches. Find one that suits your site and coding style, and go with it. CSS Design: Creating Custom Corners & Borders CSS Rounded Corners 'Roundup' 25 Rounded Corners Techniques with CSS
Creating rounded corners using CSS How can I create rounded corners using CSS?
TITLE: Creating rounded corners using CSS QUESTION: How can I create rounded corners using CSS? ANSWER: Since CSS3 was introduced, the best way to add rounded corners using CSS is by using the border-radius property. You can read the spec on the property, or get some useful implementation information on MDN: If you are using a browser that doesn't implement border-radius (Chrome pre-v4, Firefox pre-v4, IE8, Opera pre-v10.5, Safari pre-v5), then the links below detail a whole bunch of different approaches. Find one that suits your site and coding style, and go with it. CSS Design: Creating Custom Corners & Borders CSS Rounded Corners 'Roundup' 25 Rounded Corners Techniques with CSS
[ "cross-browser", "rounded-corners", "css" ]
257
105
73,904
21
0
2008-08-10T08:08:21.657000
2008-08-10T08:27:50.540000
7,095
7,105
Is the C# static constructor thread safe?
In other words, is this Singleton implementation thread safe: public class Singleton { private static Singleton instance; private Singleton() { } static Singleton() { instance = new Singleton(); } public static Singleton Instance { get { return instance; } } }
Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors The implementation shown is thread safe for the initial construction, that is, no locking or null testing is required for constructing the Singleton object. However, this does not mean that any use of the instance will be synchronised. There are a variety of ways that this can be done; I've shown one below. public class Singleton { private static Singleton instance; // Added a static mutex for synchronising use of instance. private static System.Threading.Mutex mutex; private Singleton() { } static Singleton() { instance = new Singleton(); mutex = new System.Threading.Mutex(); } public static Singleton Acquire() { mutex.WaitOne(); return instance; } // Each call to Acquire() requires a call to Release() public static void Release() { mutex.ReleaseMutex(); } }
Is the C# static constructor thread safe? In other words, is this Singleton implementation thread safe: public class Singleton { private static Singleton instance; private Singleton() { } static Singleton() { instance = new Singleton(); } public static Singleton Instance { get { return instance; } } }
TITLE: Is the C# static constructor thread safe? QUESTION: In other words, is this Singleton implementation thread safe: public class Singleton { private static Singleton instance; private Singleton() { } static Singleton() { instance = new Singleton(); } public static Singleton Instance { get { return instance; } } } ANSWER: Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors The implementation shown is thread safe for the initial construction, that is, no locking or null testing is required for constructing the Singleton object. However, this does not mean that any use of the instance will be synchronised. There are a variety of ways that this can be done; I've shown one below. public class Singleton { private static Singleton instance; // Added a static mutex for synchronising use of instance. private static System.Threading.Mutex mutex; private Singleton() { } static Singleton() { instance = new Singleton(); mutex = new System.Threading.Mutex(); } public static Singleton Acquire() { mutex.WaitOne(); return instance; } // Each call to Acquire() requires a call to Release() public static void Release() { mutex.ReleaseMutex(); } }
[ "c#", "multithreading", "singleton" ]
265
201
70,246
11
0
2008-08-10T08:23:55.573000
2008-08-10T08:46:48.413000
7,118
7,129
Debugging JavaScript in Internet Explorer and Safari
Currently, I don't really have a good method of debugging JavaScript in Internet Explorer and Safari. In Firefox, you can use Firebug's logging feature and command Line functions. However, this doesn't help me when I move to other browsers.
For Safari you need to enable the "Develop" menu via Preferences (in Safari 3.1; see the entry in Apple's Safari development FAQ ) or via $ defaults write com.apple.Safari IncludeDebugMenu 1 at the terminal in Mac OS X. Then from the Develop menu choose Show Web Inspector and click on the Console link. Your script can write to the console using window.console.log. For Internet Explorer, Visual Studio is really the best script debugger but the Microsoft Script Debugger is okay if you don't have Visual Studio. This post on the IE team blog walks you through installing it and connecting to Internet Explorer. Internet Explorer 8 looks like it will have a very fancy script debugger, so if you're feeling really adventurous you could install the Internet Explorer 8 beta and give that a whirl.
Debugging JavaScript in Internet Explorer and Safari Currently, I don't really have a good method of debugging JavaScript in Internet Explorer and Safari. In Firefox, you can use Firebug's logging feature and command Line functions. However, this doesn't help me when I move to other browsers.
TITLE: Debugging JavaScript in Internet Explorer and Safari QUESTION: Currently, I don't really have a good method of debugging JavaScript in Internet Explorer and Safari. In Firefox, you can use Firebug's logging feature and command Line functions. However, this doesn't help me when I move to other browsers. ANSWER: For Safari you need to enable the "Develop" menu via Preferences (in Safari 3.1; see the entry in Apple's Safari development FAQ ) or via $ defaults write com.apple.Safari IncludeDebugMenu 1 at the terminal in Mac OS X. Then from the Develop menu choose Show Web Inspector and click on the Console link. Your script can write to the console using window.console.log. For Internet Explorer, Visual Studio is really the best script debugger but the Microsoft Script Debugger is okay if you don't have Visual Studio. This post on the IE team blog walks you through installing it and connecting to Internet Explorer. Internet Explorer 8 looks like it will have a very fancy script debugger, so if you're feeling really adventurous you could install the Internet Explorer 8 beta and give that a whirl.
[ "javascript", "internet-explorer", "safari" ]
18
13
7,100
9
0
2008-08-10T09:07:19.853000
2008-08-10T09:24:56.197000
7,174
7,303
How can I improve the edit-compile-test loop when developing a SharePoint workflow?
Recently I had to develop a SharePoint workflow, and I found the experience quite honestly the most painful programming task I've ever had to tackle. One big problem I had was the problems I encountered when I had to step through it in the debugger. There's an article on how to debug a SharePoint workflow here that tells you how to set breakpoints etc. This involves copying the.pdb file into the GAC alongside the.dll file containing your workflow. You have to do this from a command prompt (or a batch file) because Windows Explorer doesn't let you view the relevant subdirectory of c:\windows\assembly. However, if you do this, the next time you try to deploy the workflow from within Visual Studio, it complains that it can't be deployed because "the file may not be signed" and if you attempt to copy the new version of the dll into the GAC, it tells you that the.dll file is locked. I've found that some of the time, you can get round this by doing an iisreset, but on other occasions you have to restart Visual Studio and there have been frequent times when I've even had to reboot the computer altogether because some mystery process has locked the file. When I don't use the debugger, on the other hand, everything works just fine. Does anyone know of a simpler way of debugging workflows than this?
The SharePoint team is currently working on MOSS extensions for VS 2008 which will allow this type of functionality. This was available in VS 2005 with MOSS extensions, but has to be run off Windows Server with a full MOSS installation and the correct permissions set.
How can I improve the edit-compile-test loop when developing a SharePoint workflow? Recently I had to develop a SharePoint workflow, and I found the experience quite honestly the most painful programming task I've ever had to tackle. One big problem I had was the problems I encountered when I had to step through it in the debugger. There's an article on how to debug a SharePoint workflow here that tells you how to set breakpoints etc. This involves copying the.pdb file into the GAC alongside the.dll file containing your workflow. You have to do this from a command prompt (or a batch file) because Windows Explorer doesn't let you view the relevant subdirectory of c:\windows\assembly. However, if you do this, the next time you try to deploy the workflow from within Visual Studio, it complains that it can't be deployed because "the file may not be signed" and if you attempt to copy the new version of the dll into the GAC, it tells you that the.dll file is locked. I've found that some of the time, you can get round this by doing an iisreset, but on other occasions you have to restart Visual Studio and there have been frequent times when I've even had to reboot the computer altogether because some mystery process has locked the file. When I don't use the debugger, on the other hand, everything works just fine. Does anyone know of a simpler way of debugging workflows than this?
TITLE: How can I improve the edit-compile-test loop when developing a SharePoint workflow? QUESTION: Recently I had to develop a SharePoint workflow, and I found the experience quite honestly the most painful programming task I've ever had to tackle. One big problem I had was the problems I encountered when I had to step through it in the debugger. There's an article on how to debug a SharePoint workflow here that tells you how to set breakpoints etc. This involves copying the.pdb file into the GAC alongside the.dll file containing your workflow. You have to do this from a command prompt (or a batch file) because Windows Explorer doesn't let you view the relevant subdirectory of c:\windows\assembly. However, if you do this, the next time you try to deploy the workflow from within Visual Studio, it complains that it can't be deployed because "the file may not be signed" and if you attempt to copy the new version of the dll into the GAC, it tells you that the.dll file is locked. I've found that some of the time, you can get round this by doing an iisreset, but on other occasions you have to restart Visual Studio and there have been frequent times when I've even had to reboot the computer altogether because some mystery process has locked the file. When I don't use the debugger, on the other hand, everything works just fine. Does anyone know of a simpler way of debugging workflows than this? ANSWER: The SharePoint team is currently working on MOSS extensions for VS 2008 which will allow this type of functionality. This was available in VS 2005 with MOSS extensions, but has to be run off Windows Server with a full MOSS installation and the correct permissions set.
[ "sharepoint", "workflow" ]
4
2
1,174
6
0
2008-08-10T12:12:09.213000
2008-08-10T19:41:26.890000
7,180
7,188
Animation in .NET
What is a good way to perform animation using.NET? I would prefer not to use Flash if possible, so am looking for suggestions of ways which will work to implement different types of animation on a new site I am producing. The new site is for a magician, so I want to provide animated buttons (Cards turning over, etc.) and also embed video. Is it possible to do this without using Flash or is this the only real solution? I would like to keep it as cross-platform and standard as possible.
Silverlight springs to mind as an obvious choice if you want to do animation using.NET on the web. It may not cover all platforms but will work in IE and FireFox and on the Mac.
Animation in .NET What is a good way to perform animation using.NET? I would prefer not to use Flash if possible, so am looking for suggestions of ways which will work to implement different types of animation on a new site I am producing. The new site is for a magician, so I want to provide animated buttons (Cards turning over, etc.) and also embed video. Is it possible to do this without using Flash or is this the only real solution? I would like to keep it as cross-platform and standard as possible.
TITLE: Animation in .NET QUESTION: What is a good way to perform animation using.NET? I would prefer not to use Flash if possible, so am looking for suggestions of ways which will work to implement different types of animation on a new site I am producing. The new site is for a magician, so I want to provide animated buttons (Cards turning over, etc.) and also embed video. Is it possible to do this without using Flash or is this the only real solution? I would like to keep it as cross-platform and standard as possible. ANSWER: Silverlight springs to mind as an obvious choice if you want to do animation using.NET on the web. It may not cover all platforms but will work in IE and FireFox and on the Mac.
[ ".net", "animation" ]
6
4
1,037
4
0
2008-08-10T12:39:20.830000
2008-08-10T13:01:37.680000
7,190
7,221
Setting up Continuous Integration with SVN
What tools would you recommend for setting up CI for build and deployment of multiple websites built on DotNetNuke using SVN for source control? We are currently looking at configuring Cruise Control to work with NAnt, NUnit, NCover and Trac as a test case. What other combinations would worth investigating? We have full control of our development environment so using some form of CI is certain here but I would also like to convince our production services team that they can reliably deploy to the system test, uat and even production environments using these tools.
We use CruiseControl with NUnit, NCover, FxCop, SVN and some custom tools we wrote ourselves to produce the reports. In my opinion it has proven (over the last few years) to be an excellent combination. It's frustrating that MS restricts all of its integration tools to VSTS. Its test framework is as good as NUnit, but you can't use its code coverage tools or anything else. I'd check out XNuit - it's looking pretty promising (but currently lacking UI). We automate nightly builds, and you could automate UAT and manual test builds, but I'm not sure that we'd ever want to automate the release to our production servers. Even if it were any change would be important enough that someone would have to watch over it anyway.
Setting up Continuous Integration with SVN What tools would you recommend for setting up CI for build and deployment of multiple websites built on DotNetNuke using SVN for source control? We are currently looking at configuring Cruise Control to work with NAnt, NUnit, NCover and Trac as a test case. What other combinations would worth investigating? We have full control of our development environment so using some form of CI is certain here but I would also like to convince our production services team that they can reliably deploy to the system test, uat and even production environments using these tools.
TITLE: Setting up Continuous Integration with SVN QUESTION: What tools would you recommend for setting up CI for build and deployment of multiple websites built on DotNetNuke using SVN for source control? We are currently looking at configuring Cruise Control to work with NAnt, NUnit, NCover and Trac as a test case. What other combinations would worth investigating? We have full control of our development environment so using some form of CI is certain here but I would also like to convince our production services team that they can reliably deploy to the system test, uat and even production environments using these tools. ANSWER: We use CruiseControl with NUnit, NCover, FxCop, SVN and some custom tools we wrote ourselves to produce the reports. In my opinion it has proven (over the last few years) to be an excellent combination. It's frustrating that MS restricts all of its integration tools to VSTS. Its test framework is as good as NUnit, but you can't use its code coverage tools or anything else. I'd check out XNuit - it's looking pretty promising (but currently lacking UI). We automate nightly builds, and you could automate UAT and manual test builds, but I'm not sure that we'd ever want to automate the release to our production servers. Even if it were any change would be important enough that someone would have to watch over it anyway.
[ "svn", "continuous-integration" ]
10
3
8,588
6
0
2008-08-10T13:09:13.780000
2008-08-10T15:34:37.620000
7,209
119,880
Alpha blending sprites in Nintendo DS Homebrew
I'm trying to alpha blend sprites and backgrounds with devkitPro (including libnds, libarm, etc). Does anyone know how to do this?
As a generic reference, i once wrote a small blog entry about that issue. Basically, you first have to define which layer is alpha-blended against which other layer(s). Afaik, the source layer(s) must be over destination layer(s) to have some blending displayed. that means the priority of source layers should be numerically lower than the the priority of destination layers. the source layer is what is going to be translucent, the destination(s) is what is going to be seen through (and yes, i find this rather confusing). For the sprites, specifically, you then have 3 ways to achieve alpha-blending depending on what you need and what you're "ready to pay" for it: You can make all the sprites have some alpha-blending by turning on BLEND_SRC_SPRITE in REG_BLDCNT[_SUB]... not that useful. You can selectively turn on blending of some sprites by using ATTR0_TYPE_BLENDED. The blending level will be the same for all sprites (and layers) bitmap-type sprites use direct colors (bypassing the palettes), so the ATTR2_PALETTE() field of GBA sprites is useless and has been recycled into ATTR2_ALPHA.
Alpha blending sprites in Nintendo DS Homebrew I'm trying to alpha blend sprites and backgrounds with devkitPro (including libnds, libarm, etc). Does anyone know how to do this?
TITLE: Alpha blending sprites in Nintendo DS Homebrew QUESTION: I'm trying to alpha blend sprites and backgrounds with devkitPro (including libnds, libarm, etc). Does anyone know how to do this? ANSWER: As a generic reference, i once wrote a small blog entry about that issue. Basically, you first have to define which layer is alpha-blended against which other layer(s). Afaik, the source layer(s) must be over destination layer(s) to have some blending displayed. that means the priority of source layers should be numerically lower than the the priority of destination layers. the source layer is what is going to be translucent, the destination(s) is what is going to be seen through (and yes, i find this rather confusing). For the sprites, specifically, you then have 3 ways to achieve alpha-blending depending on what you need and what you're "ready to pay" for it: You can make all the sprites have some alpha-blending by turning on BLEND_SRC_SPRITE in REG_BLDCNT[_SUB]... not that useful. You can selectively turn on blending of some sprites by using ATTR0_TYPE_BLENDED. The blending level will be the same for all sprites (and layers) bitmap-type sprites use direct colors (bypassing the palettes), so the ATTR2_PALETTE() field of GBA sprites is useless and has been recycled into ATTR2_ALPHA.
[ "c++", "c", "nintendo-ds" ]
9
6
2,174
3
0
2008-08-10T14:49:10.723000
2008-09-23T08:39:44.120000
7,212
8,886
Is it possible to add behavior to a non-dynamic ActionScript 3 class without inheriting the class?
What I'd like to do is something like the following: FooClass.prototype.method = function():String { return "Something"; } var foo:FooClass = new FooClass(); foo.method(); Which is to say, I'd like to extend a generated class with a single method, not via inheritance but via the prototype. The class is generated from a WSDL, it's not a dynamic class, and I don't want to touch the generated code because it will be overwritten anyway. Long story short, I'd like to have the moral equivalent of C# 3:s Extension Methods for AS3. Edit: I accepted aib's answer, because it fits what I was asking best -- although upon further reflection it doesn't really solve my problem, but that's my fault for asking the wrong question.:) Also, upmods for the good suggestions.
Yes, such a thing is possible. In fact, your example is very close to the solution. Try foo["method"](); instead of foo.method();
Is it possible to add behavior to a non-dynamic ActionScript 3 class without inheriting the class? What I'd like to do is something like the following: FooClass.prototype.method = function():String { return "Something"; } var foo:FooClass = new FooClass(); foo.method(); Which is to say, I'd like to extend a generated class with a single method, not via inheritance but via the prototype. The class is generated from a WSDL, it's not a dynamic class, and I don't want to touch the generated code because it will be overwritten anyway. Long story short, I'd like to have the moral equivalent of C# 3:s Extension Methods for AS3. Edit: I accepted aib's answer, because it fits what I was asking best -- although upon further reflection it doesn't really solve my problem, but that's my fault for asking the wrong question.:) Also, upmods for the good suggestions.
TITLE: Is it possible to add behavior to a non-dynamic ActionScript 3 class without inheriting the class? QUESTION: What I'd like to do is something like the following: FooClass.prototype.method = function():String { return "Something"; } var foo:FooClass = new FooClass(); foo.method(); Which is to say, I'd like to extend a generated class with a single method, not via inheritance but via the prototype. The class is generated from a WSDL, it's not a dynamic class, and I don't want to touch the generated code because it will be overwritten anyway. Long story short, I'd like to have the moral equivalent of C# 3:s Extension Methods for AS3. Edit: I accepted aib's answer, because it fits what I was asking best -- although upon further reflection it doesn't really solve my problem, but that's my fault for asking the wrong question.:) Also, upmods for the good suggestions. ANSWER: Yes, such a thing is possible. In fact, your example is very close to the solution. Try foo["method"](); instead of foo.method();
[ "apache-flex", "actionscript-3", "extension-methods" ]
5
3
1,363
5
0
2008-08-10T15:05:33.140000
2008-08-12T14:31:44.300000
7,214
7,235
User authentication on Resin webserver
I'm currently tasked with replacing an Apache + Resin Java web server with a Resin-only configuration. Currently in our apache setup, we use.htaccess and a small user database to provide passwording at a directory level. Does anyone know the equivalent setup when using just Resin as the web server?
See " Authentication on Resin " The closest you'll come to.htaccess with apache is configuring for Basic auth using an XmlAuthenticator. You'll need to convert your htpasswd file into the XML format that resin uses. Follow the "Quick Start" section and you'll get what you want.
User authentication on Resin webserver I'm currently tasked with replacing an Apache + Resin Java web server with a Resin-only configuration. Currently in our apache setup, we use.htaccess and a small user database to provide passwording at a directory level. Does anyone know the equivalent setup when using just Resin as the web server?
TITLE: User authentication on Resin webserver QUESTION: I'm currently tasked with replacing an Apache + Resin Java web server with a Resin-only configuration. Currently in our apache setup, we use.htaccess and a small user database to provide passwording at a directory level. Does anyone know the equivalent setup when using just Resin as the web server? ANSWER: See " Authentication on Resin " The closest you'll come to.htaccess with apache is configuring for Basic auth using an XmlAuthenticator. You'll need to convert your htpasswd file into the XML format that resin uses. Follow the "Quick Start" section and you'll get what you want.
[ "apache", "configuration", "webserver", "resin", "caucho" ]
2
1
1,012
1
0
2008-08-10T15:10:41.820000
2008-08-10T16:41:23.897000
7,224
7,225
Change the width of a scrollbar
Is it possible to change the width of a scroll bar on a form. This app is for a touch screen and it is a bit too narrow.
The width of the scrollbars is controlled by Windows. You can adjust the scrollbar width in Display Properties and it will affect all windows on the terminal.
Change the width of a scrollbar Is it possible to change the width of a scroll bar on a form. This app is for a touch screen and it is a bit too narrow.
TITLE: Change the width of a scrollbar QUESTION: Is it possible to change the width of a scroll bar on a form. This app is for a touch screen and it is a bit too narrow. ANSWER: The width of the scrollbars is controlled by Windows. You can adjust the scrollbar width in Display Properties and it will affect all windows on the terminal.
[ "vb.net", "scrollbar" ]
8
3
17,083
2
0
2008-08-10T15:48:24.083000
2008-08-10T15:48:41.070000
7,231
7,499
Automatically check bounced emails via POP3?
Can anyone recommend software or a.NET library that will check for bounced emails and the reason for the bounce? I get bounced emails into a pop3 account that I can read then. I need it to keep my user database clean from invalid email addresses and want to automate this (mark user as invalid email).
I have done a great deal of work handling bounce emails and there different types. If you want to be absolutely sure that the email your looking at is indeed a bounce of a specific kind I highly recommend getting a good filter. I have worked with Boogie Tools and it has worked very well. It lets you know what kind of bounce it is, Hard, Soft, Transient or if its even someone trying to unsubscribe. It has a muliple API's including.Net and I found it quite easy to get working.
Automatically check bounced emails via POP3? Can anyone recommend software or a.NET library that will check for bounced emails and the reason for the bounce? I get bounced emails into a pop3 account that I can read then. I need it to keep my user database clean from invalid email addresses and want to automate this (mark user as invalid email).
TITLE: Automatically check bounced emails via POP3? QUESTION: Can anyone recommend software or a.NET library that will check for bounced emails and the reason for the bounce? I get bounced emails into a pop3 account that I can read then. I need it to keep my user database clean from invalid email addresses and want to automate this (mark user as invalid email). ANSWER: I have done a great deal of work handling bounce emails and there different types. If you want to be absolutely sure that the email your looking at is indeed a bounce of a specific kind I highly recommend getting a good filter. I have worked with Boogie Tools and it has worked very well. It lets you know what kind of bounce it is, Hard, Soft, Transient or if its even someone trying to unsubscribe. It has a muliple API's including.Net and I found it quite easy to get working.
[ ".net", "email", "pop3", "email-bounces" ]
10
6
5,344
5
0
2008-08-10T16:16:15.370000
2008-08-11T03:38:55.647000
7,237
178,509
Does running a SQL Server 2005 database in compatibility level 80 have a negative impact on performance?
Our software must be able to run on SQL Server 2000 and 2005. To simplify development, we're running our SQL Server 2005 databases in compatibility level 80. However, database performance seems slower on SQL 2005 than on SQL 2000 in some cases (we have not confirmed this using benchmarks yet). Would upgrading the compatibility level to 90 improve performance on the SQL 2005 servers?
I think i read somewhere, that the SQL Server 2005 database engine should be about 30% faster than the SQL Server 2000 engine. It might be, that you have to run your database in compatibility mode 90 to get these benefits. But i stumbled on two scenarios, where performance can drop dramatically when using mssql 2005 compared to mssql 2000: Parameter Sniffing: When using a stored procedure, sql server will calculate exactly one execution plan at the time, you first call the procedure. The execution plan depends on the parameter values given for that call. In our case, procedures which normally took about 10 seconds are running for hours under mssql 2005. Take a look here and here. When using distributed queries, mssql 2005 behaves different concerning assumptions about the sort order on the remote server. Default behavior is, that the server copies the whole remote tables involved in a query to the local tempdb and then execute the joins locally. Workaround is to use OPENQUERY, where you can control exactly which resultset is transferred from the remote server.
Does running a SQL Server 2005 database in compatibility level 80 have a negative impact on performance? Our software must be able to run on SQL Server 2000 and 2005. To simplify development, we're running our SQL Server 2005 databases in compatibility level 80. However, database performance seems slower on SQL 2005 than on SQL 2000 in some cases (we have not confirmed this using benchmarks yet). Would upgrading the compatibility level to 90 improve performance on the SQL 2005 servers?
TITLE: Does running a SQL Server 2005 database in compatibility level 80 have a negative impact on performance? QUESTION: Our software must be able to run on SQL Server 2000 and 2005. To simplify development, we're running our SQL Server 2005 databases in compatibility level 80. However, database performance seems slower on SQL 2005 than on SQL 2000 in some cases (we have not confirmed this using benchmarks yet). Would upgrading the compatibility level to 90 improve performance on the SQL 2005 servers? ANSWER: I think i read somewhere, that the SQL Server 2005 database engine should be about 30% faster than the SQL Server 2000 engine. It might be, that you have to run your database in compatibility mode 90 to get these benefits. But i stumbled on two scenarios, where performance can drop dramatically when using mssql 2005 compared to mssql 2000: Parameter Sniffing: When using a stored procedure, sql server will calculate exactly one execution plan at the time, you first call the procedure. The execution plan depends on the parameter values given for that call. In our case, procedures which normally took about 10 seconds are running for hours under mssql 2005. Take a look here and here. When using distributed queries, mssql 2005 behaves different concerning assumptions about the sort order on the remote server. Default behavior is, that the server copies the whole remote tables involved in a query to the local tempdb and then execute the joins locally. Workaround is to use OPENQUERY, where you can control exactly which resultset is transferred from the remote server.
[ "sql-server", "database" ]
11
5
5,951
4
0
2008-08-10T16:46:12.640000
2008-10-07T13:46:25.677000
7,244
1,409,873
Anyone know a good workaround for the lack of an enum generic constraint?
What I want to do is something like this: I have enums with combined flagged values. public static class EnumExtension { public static bool IsSet ( this T input, T matchTo ) where T:enum //the constraint I want that doesn't exist in C#3 { return (input & matchTo)!= 0; } } So then I could do: MyEnum tester = MyEnum.FlagA | MyEnum.FlagB if( tester.IsSet( MyEnum.FlagA ) ) //act on flag a Unfortunately, C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this. Does anyone know a workaround?
EDIT: This is now live in version 0.0.0.2 of UnconstrainedMelody. (As requested on my blog post about enum constraints. I've included the basic facts below for the sake of a standalone answer.) The best solution is to wait for me to include it in UnconstrainedMelody 1. This is a library which takes C# code with "fake" constraints such as where T: struct, IEnumConstraint and turns it into where T: struct, System.Enum via a postbuild step. It shouldn't be too hard to write IsSet... although catering for both Int64 -based and UInt64 -based flags could be the tricky part. (I smell some helper methods coming on, basically allowing me to treat any flags enum as if it had a base type of UInt64.) What would you want the behaviour to be if you called tester.IsSet(MyFlags.A | MyFlags.C)? Should it check that all the specified flags are set? That would be my expectation. I'll try to do this on the way home tonight... I'm hoping to have a quick blitz on useful enum methods to get the library up to a usable standard quickly, then relax a bit. EDIT: I'm not sure about IsSet as a name, by the way. Options: Includes Contains HasFlag (or HasFlags) IsSet (it's certainly an option) Thoughts welcome. I'm sure it'll be a while before anything's set in stone anyway... 1 or submit it as a patch, of course...
Anyone know a good workaround for the lack of an enum generic constraint? What I want to do is something like this: I have enums with combined flagged values. public static class EnumExtension { public static bool IsSet ( this T input, T matchTo ) where T:enum //the constraint I want that doesn't exist in C#3 { return (input & matchTo)!= 0; } } So then I could do: MyEnum tester = MyEnum.FlagA | MyEnum.FlagB if( tester.IsSet( MyEnum.FlagA ) ) //act on flag a Unfortunately, C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this. Does anyone know a workaround?
TITLE: Anyone know a good workaround for the lack of an enum generic constraint? QUESTION: What I want to do is something like this: I have enums with combined flagged values. public static class EnumExtension { public static bool IsSet ( this T input, T matchTo ) where T:enum //the constraint I want that doesn't exist in C#3 { return (input & matchTo)!= 0; } } So then I could do: MyEnum tester = MyEnum.FlagA | MyEnum.FlagB if( tester.IsSet( MyEnum.FlagA ) ) //act on flag a Unfortunately, C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this. Does anyone know a workaround? ANSWER: EDIT: This is now live in version 0.0.0.2 of UnconstrainedMelody. (As requested on my blog post about enum constraints. I've included the basic facts below for the sake of a standalone answer.) The best solution is to wait for me to include it in UnconstrainedMelody 1. This is a library which takes C# code with "fake" constraints such as where T: struct, IEnumConstraint and turns it into where T: struct, System.Enum via a postbuild step. It shouldn't be too hard to write IsSet... although catering for both Int64 -based and UInt64 -based flags could be the tricky part. (I smell some helper methods coming on, basically allowing me to treat any flags enum as if it had a base type of UInt64.) What would you want the behaviour to be if you called tester.IsSet(MyFlags.A | MyFlags.C)? Should it check that all the specified flags are set? That would be my expectation. I'll try to do this on the way home tonight... I'm hoping to have a quick blitz on useful enum methods to get the library up to a usable standard quickly, then relax a bit. EDIT: I'm not sure about IsSet as a name, by the way. Options: Includes Contains HasFlag (or HasFlags) IsSet (it's certainly an option) Thoughts welcome. I'm sure it'll be a while before anything's set in stone anyway... 1 or submit it as a patch, of course...
[ "c#", ".net", "enums", "flags" ]
97
52
23,748
12
0
2008-08-10T17:14:10.260000
2009-09-11T09:12:34.137000
7,245
7,258
Puzzle: Find largest rectangle (maximal rectangle problem)
What's the most efficient algorithm to find the rectangle with the largest area which will fit in the empty space? Let's say the screen looks like this ('#' represents filled area):..................................###### ##...................................###.................### #####............... #####............... #####............... A probable solution is:..................................###### ##...++++++++++++........++++++++++++###.....++++++++++++### #####++++++++++++... #####++++++++++++... #####++++++++++++... Normally I'd enjoy figuring out a solution. Although this time I'd like to avoid wasting time fumbling around on my own since this has a practical use for a project I'm working on. Is there a well-known solution? Shog9 wrote: Is your input an array (as implied by the other responses), or a list of occlusions in the form of arbitrarily sized, positioned rectangles (as might be the case in a windowing system when dealing with window positions)? Yes, I have a structure which keeps track of a set of windows placed on the screen. I also have a grid which keeps track of all the areas between each edge, whether they are empty or filled, and the pixel position of their left or top edge. I think there is some modified form which would take advantage of this property. Do you know of any?
@lassevk I found the referenced article, from DDJ: The Maximal Rectangle Problem
Puzzle: Find largest rectangle (maximal rectangle problem) What's the most efficient algorithm to find the rectangle with the largest area which will fit in the empty space? Let's say the screen looks like this ('#' represents filled area):..................................###### ##...................................###.................### #####............... #####............... #####............... A probable solution is:..................................###### ##...++++++++++++........++++++++++++###.....++++++++++++### #####++++++++++++... #####++++++++++++... #####++++++++++++... Normally I'd enjoy figuring out a solution. Although this time I'd like to avoid wasting time fumbling around on my own since this has a practical use for a project I'm working on. Is there a well-known solution? Shog9 wrote: Is your input an array (as implied by the other responses), or a list of occlusions in the form of arbitrarily sized, positioned rectangles (as might be the case in a windowing system when dealing with window positions)? Yes, I have a structure which keeps track of a set of windows placed on the screen. I also have a grid which keeps track of all the areas between each edge, whether they are empty or filled, and the pixel position of their left or top edge. I think there is some modified form which would take advantage of this property. Do you know of any?
TITLE: Puzzle: Find largest rectangle (maximal rectangle problem) QUESTION: What's the most efficient algorithm to find the rectangle with the largest area which will fit in the empty space? Let's say the screen looks like this ('#' represents filled area):..................................###### ##...................................###.................### #####............... #####............... #####............... A probable solution is:..................................###### ##...++++++++++++........++++++++++++###.....++++++++++++### #####++++++++++++... #####++++++++++++... #####++++++++++++... Normally I'd enjoy figuring out a solution. Although this time I'd like to avoid wasting time fumbling around on my own since this has a practical use for a project I'm working on. Is there a well-known solution? Shog9 wrote: Is your input an array (as implied by the other responses), or a list of occlusions in the form of arbitrarily sized, positioned rectangles (as might be the case in a windowing system when dealing with window positions)? Yes, I have a structure which keeps track of a set of windows placed on the screen. I also have a grid which keeps track of all the areas between each edge, whether they are empty or filled, and the pixel position of their left or top edge. I think there is some modified form which would take advantage of this property. Do you know of any? ANSWER: @lassevk I found the referenced article, from DDJ: The Maximal Rectangle Problem
[ "algorithm", "language-agnostic", "math", "geometry" ]
45
23
33,708
6
0
2008-08-10T17:16:55.137000
2008-08-10T17:44:35.237000
7,252
7,274
How to make junior programmers write tests?
We have a junior programmer that simply doesn't write enough tests. I have to nag him every two hours, "have you written tests?" We've tried: Showing that the design becomes simpler Showing it prevents defects Making it an ego thing saying only bad programmers don't This weekend 2 team members had to come to work because his code had a NULL reference and he didn't test it My work requires top quality stable code, and usually everyone 'gets it' and there's no need to push tests through. We know we can make him write tests, but we all know the useful tests are those written when you're into it. Do you know of more motivations?
This is one of the hardest things to do. Getting your people to get it. Sometimes one of the best ways to help junior level programmers 'get it' and learn the right techniques from the seniors is to do a bit of pair programming. Try this: on an upcoming project, pair the junior guy up with yourself or another senior programmer. They should work together, taking turns "driving" (being the one typing at they keyboard) and "coaching" (looking over the shoulder of the driver and pointing out suggestions, mistakes, etc as they go). It may seem like a waste of resources, but you will find: That these guys together can produce code plenty fast and of higher quality. If your junior guy learns enough to "get it" with a senior guy directing him along the right path (eg. "Ok, now before we continue, lets write at test for this function.") It will be well worth the resources you commit to it. Maybe also have someone in your group give the Unit Testing 101 presentation by Kate Rhodes, I think its a great way to get people excited about testing, if delivered well. Another thing you can do is have your Jr. Devs practice the Bowling Game Kata which will help them learn Test Driven Development. It is in java, but could easily be adapted to any language.
How to make junior programmers write tests? We have a junior programmer that simply doesn't write enough tests. I have to nag him every two hours, "have you written tests?" We've tried: Showing that the design becomes simpler Showing it prevents defects Making it an ego thing saying only bad programmers don't This weekend 2 team members had to come to work because his code had a NULL reference and he didn't test it My work requires top quality stable code, and usually everyone 'gets it' and there's no need to push tests through. We know we can make him write tests, but we all know the useful tests are those written when you're into it. Do you know of more motivations?
TITLE: How to make junior programmers write tests? QUESTION: We have a junior programmer that simply doesn't write enough tests. I have to nag him every two hours, "have you written tests?" We've tried: Showing that the design becomes simpler Showing it prevents defects Making it an ego thing saying only bad programmers don't This weekend 2 team members had to come to work because his code had a NULL reference and he didn't test it My work requires top quality stable code, and usually everyone 'gets it' and there's no need to push tests through. We know we can make him write tests, but we all know the useful tests are those written when you're into it. Do you know of more motivations? ANSWER: This is one of the hardest things to do. Getting your people to get it. Sometimes one of the best ways to help junior level programmers 'get it' and learn the right techniques from the seniors is to do a bit of pair programming. Try this: on an upcoming project, pair the junior guy up with yourself or another senior programmer. They should work together, taking turns "driving" (being the one typing at they keyboard) and "coaching" (looking over the shoulder of the driver and pointing out suggestions, mistakes, etc as they go). It may seem like a waste of resources, but you will find: That these guys together can produce code plenty fast and of higher quality. If your junior guy learns enough to "get it" with a senior guy directing him along the right path (eg. "Ok, now before we continue, lets write at test for this function.") It will be well worth the resources you commit to it. Maybe also have someone in your group give the Unit Testing 101 presentation by Kate Rhodes, I think its a great way to get people excited about testing, if delivered well. Another thing you can do is have your Jr. Devs practice the Bowling Game Kata which will help them learn Test Driven Development. It is in java, but could easily be adapted to any language.
[ "unit-testing", "testing" ]
109
128
10,576
24
0
2008-08-10T17:34:46.630000
2008-08-10T18:17:34.983000
7,260
9,095
How do I setup Public-Key Authentication?
How do I setup Public-Key Authentication for SSH?
If you have SSH installed, you should be able to run.. ssh-keygen Then go through the steps, you'll have two files, id_rsa and id_rsa.pub (the first is your private key, the second is your public key - the one you copy to remote machines) Then, connect to the remote machine you want to login to, to the file ~/.ssh/authorized_keys add the contents of your that id_rsa.pub file. Oh, and chmod 600 all the id_rsa* files (both locally and remote), so no other users can read them: chmod 600 ~/.ssh/id_rsa* Similarly, ensure the remote ~/.ssh/authorized_keys file is chmod 600 also: chmod 600 ~/.ssh/authorized_keys Then, when you do ssh remote.machine, it should ask you for the key's password, not the remote machine. To make it nicer to use, you can use ssh-agent to hold the decrypted keys in memory - this means you don't have to type your keypair's password every single time. To launch the agent, you run (including the back-tick quotes, which eval the output of the ssh-agent command) `ssh-agent` On some distros, ssh-agent is started automatically. If you run echo $SSH_AUTH_SOCK and it shows a path (probably in /tmp/) it's already setup, so you can skip the previous command. Then to add your key, you do ssh-add ~/.ssh/id_rsa and enter your passphrase. It's stored until you remove it (using the ssh-add -D command, which removes all keys from the agent)
How do I setup Public-Key Authentication? How do I setup Public-Key Authentication for SSH?
TITLE: How do I setup Public-Key Authentication? QUESTION: How do I setup Public-Key Authentication for SSH? ANSWER: If you have SSH installed, you should be able to run.. ssh-keygen Then go through the steps, you'll have two files, id_rsa and id_rsa.pub (the first is your private key, the second is your public key - the one you copy to remote machines) Then, connect to the remote machine you want to login to, to the file ~/.ssh/authorized_keys add the contents of your that id_rsa.pub file. Oh, and chmod 600 all the id_rsa* files (both locally and remote), so no other users can read them: chmod 600 ~/.ssh/id_rsa* Similarly, ensure the remote ~/.ssh/authorized_keys file is chmod 600 also: chmod 600 ~/.ssh/authorized_keys Then, when you do ssh remote.machine, it should ask you for the key's password, not the remote machine. To make it nicer to use, you can use ssh-agent to hold the decrypted keys in memory - this means you don't have to type your keypair's password every single time. To launch the agent, you run (including the back-tick quotes, which eval the output of the ssh-agent command) `ssh-agent` On some distros, ssh-agent is started automatically. If you run echo $SSH_AUTH_SOCK and it shows a path (probably in /tmp/) it's already setup, so you can skip the previous command. Then to add your key, you do ssh-add ~/.ssh/id_rsa and enter your passphrase. It's stored until you remove it (using the ssh-add -D command, which removes all keys from the agent)
[ "linux", "ssh", "private-key", "public-key" ]
63
108
101,717
2
0
2008-08-10T17:50:11.467000
2008-08-12T18:13:37.127000
7,269
46,902
How can I identify in which Java Applet context running without passing an ID?
I'm part of a team that develops a pretty big Swing Java Applet. Most of our code are legacy and there are tons of singleton references. We've bunched all of them to a single "Application Context" singleton. What we now need is to create some way to separate the shared context (shared across all applets currently showing) and non-shared context (specific to each applet currently showing). However, we don't have an ID at each of the locations that call to the singleton, nor do we want to propagate the ID to all locations. What's the easiest way to identify in which applet context we're running? (I've tried messing with classloaders, thread groups, thread ids... so far I could find nothing that will enable me to ID the origin of the call).
Singletons are evil, what do you expect?;) Perhaps the most comprehensive approach would be to load the bulk of the applet in a different class loader (use java.net.URLClassLoader.newInstance). Then use a WeakHashMap to associate class loader with an applet. If you could split most of the code into a common class loader (as a parent of each per-applet class loader) and into the normal applet codebase, that would be faster but more work. Other hacks: If you have access to any component, you can use Component.getParent repeatedly or SwingUtilities.getRoot. If you are in a per-applet instance thread, then you can set up a ThreadLocal. From the EDT, you can read the current event from the queue (java.awt.EventQueue.getCurrentEvent()), and possibly find a component from that. Alternatively push an EventQueue with a overridden dispatchEvent method.
How can I identify in which Java Applet context running without passing an ID? I'm part of a team that develops a pretty big Swing Java Applet. Most of our code are legacy and there are tons of singleton references. We've bunched all of them to a single "Application Context" singleton. What we now need is to create some way to separate the shared context (shared across all applets currently showing) and non-shared context (specific to each applet currently showing). However, we don't have an ID at each of the locations that call to the singleton, nor do we want to propagate the ID to all locations. What's the easiest way to identify in which applet context we're running? (I've tried messing with classloaders, thread groups, thread ids... so far I could find nothing that will enable me to ID the origin of the call).
TITLE: How can I identify in which Java Applet context running without passing an ID? QUESTION: I'm part of a team that develops a pretty big Swing Java Applet. Most of our code are legacy and there are tons of singleton references. We've bunched all of them to a single "Application Context" singleton. What we now need is to create some way to separate the shared context (shared across all applets currently showing) and non-shared context (specific to each applet currently showing). However, we don't have an ID at each of the locations that call to the singleton, nor do we want to propagate the ID to all locations. What's the easiest way to identify in which applet context we're running? (I've tried messing with classloaders, thread groups, thread ids... so far I could find nothing that will enable me to ID the origin of the call). ANSWER: Singletons are evil, what do you expect?;) Perhaps the most comprehensive approach would be to load the bulk of the applet in a different class loader (use java.net.URLClassLoader.newInstance). Then use a WeakHashMap to associate class loader with an applet. If you could split most of the code into a common class loader (as a parent of each per-applet class loader) and into the normal applet codebase, that would be faster but more work. Other hacks: If you have access to any component, you can use Component.getParent repeatedly or SwingUtilities.getRoot. If you are in a per-applet instance thread, then you can set up a ThreadLocal. From the EDT, you can read the current event from the queue (java.awt.EventQueue.getCurrentEvent()), and possibly find a component from that. Alternatively push an EventQueue with a overridden dispatchEvent method.
[ "java", "swing", "applet" ]
8
3
2,140
3
0
2008-08-10T18:06:04.820000
2008-09-05T21:13:10.303000
7,277
7,292
Is it "bad practice" to be sensitive to linebreaks in XML documents?
I'm generating some XML documents and when it comes to the address part I have fragments that look like this: 15 Sample St Example Bay Some Country The XSLT that I have for converting this to XHTML has some funky recursive template to convert newline characters within strings to tags. This is all working fine; but is it considered "bad practice" to rely on linebreaks within XML documents? If so, is it recommended that I do this instead? 15 Sample St Example Bay Some Country Seems like it'd be really awkward to wrap every place where my text may be multiple lines with tags like that..
It's generally considered bad practice to rely on linebreaks, since it's a fragile way to differentiate data. While most XML processors will preserve any whitespace you put in your XML, it's not guaranteed. The real problem is that most applications that output your XML into a readable format consider all whitespace in an XML interchangable, and might collapse those linebreaks into a single space. That's why your XSLT has to jump through such hoops to render the data properly. Using a "br" tag would vastly simplify the transform. Another potential problem is that if you open up your XML document in an XML editor and pretty-print it, you're likely to lose those line breaks. If you do keep using linebreaks, make sure add an xml:space="preserve" attribute to "address." (You can do this in your DTD, if you're using one.) Some suggested reading An article from XML.com says the following: XML applications often seem to take a cavalier attitude toward whitespace because the rules about the places in an XML document where whitespace doesn't matter sometimes give these applications free rein to add or remove whitespace in certain places. A collection of XSL-list posts regarding whitespace.
Is it "bad practice" to be sensitive to linebreaks in XML documents? I'm generating some XML documents and when it comes to the address part I have fragments that look like this: 15 Sample St Example Bay Some Country The XSLT that I have for converting this to XHTML has some funky recursive template to convert newline characters within strings to tags. This is all working fine; but is it considered "bad practice" to rely on linebreaks within XML documents? If so, is it recommended that I do this instead? 15 Sample St Example Bay Some Country Seems like it'd be really awkward to wrap every place where my text may be multiple lines with tags like that..
TITLE: Is it "bad practice" to be sensitive to linebreaks in XML documents? QUESTION: I'm generating some XML documents and when it comes to the address part I have fragments that look like this: 15 Sample St Example Bay Some Country The XSLT that I have for converting this to XHTML has some funky recursive template to convert newline characters within strings to tags. This is all working fine; but is it considered "bad practice" to rely on linebreaks within XML documents? If so, is it recommended that I do this instead? 15 Sample St Example Bay Some Country Seems like it'd be really awkward to wrap every place where my text may be multiple lines with tags like that.. ANSWER: It's generally considered bad practice to rely on linebreaks, since it's a fragile way to differentiate data. While most XML processors will preserve any whitespace you put in your XML, it's not guaranteed. The real problem is that most applications that output your XML into a readable format consider all whitespace in an XML interchangable, and might collapse those linebreaks into a single space. That's why your XSLT has to jump through such hoops to render the data properly. Using a "br" tag would vastly simplify the transform. Another potential problem is that if you open up your XML document in an XML editor and pretty-print it, you're likely to lose those line breaks. If you do keep using linebreaks, make sure add an xml:space="preserve" attribute to "address." (You can do this in your DTD, if you're using one.) Some suggested reading An article from XML.com says the following: XML applications often seem to take a cavalier attitude toward whitespace because the rules about the places in an XML document where whitespace doesn't matter sometimes give these applications free rein to add or remove whitespace in certain places. A collection of XSL-list posts regarding whitespace.
[ "xml", "xslt", "xhtml", "whitespace", "line-breaks" ]
8
9
4,600
12
0
2008-08-10T18:20:38.130000
2008-08-10T19:05:08.930000