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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
48,680 | 48,719 | Winforms c# - Set focus to first child control of TabPage | Say I have a Textbox nested within a TabControl. When the form loads, I would like to focus on that Textbox (by default the focus is set to the TabControl ). Simply calling textbox1.focus() in the Load event of the form does not appear to work. I have been able to focus it by doing the following: private void frmMainLoad(object sender, EventArgs e) { foreach (TabPage tab in this.tabControl1.TabPages) { this.tabControl1.SelectedTab = tab; } } My question is: Is there a more elegant way to do this? | The following is the solution: private void frmMainLoad(object sender, EventArgs e) { ActiveControl = textBox1; } The better question would however be why... I'm not entirely sure what the answer to that one is. Edit: I suspect it is something to do with the fact that both the form, and the TabControl are containers, but I'm not sure. | Winforms c# - Set focus to first child control of TabPage Say I have a Textbox nested within a TabControl. When the form loads, I would like to focus on that Textbox (by default the focus is set to the TabControl ). Simply calling textbox1.focus() in the Load event of the form does not appear to work. I have been able to focus it by doing the following: private void frmMainLoad(object sender, EventArgs e) { foreach (TabPage tab in this.tabControl1.TabPages) { this.tabControl1.SelectedTab = tab; } } My question is: Is there a more elegant way to do this? | TITLE:
Winforms c# - Set focus to first child control of TabPage
QUESTION:
Say I have a Textbox nested within a TabControl. When the form loads, I would like to focus on that Textbox (by default the focus is set to the TabControl ). Simply calling textbox1.focus() in the Load event of the form does not appear to work. I have been able to focus it by doing the following: private void frmMainLoad(object sender, EventArgs e) { foreach (TabPage tab in this.tabControl1.TabPages) { this.tabControl1.SelectedTab = tab; } } My question is: Is there a more elegant way to do this?
ANSWER:
The following is the solution: private void frmMainLoad(object sender, EventArgs e) { ActiveControl = textBox1; } The better question would however be why... I'm not entirely sure what the answer to that one is. Edit: I suspect it is something to do with the fact that both the form, and the TabControl are containers, but I'm not sure. | [
"c#",
".net",
"winforms",
"focus"
] | 20 | 47 | 45,442 | 6 | 0 | 2008-09-07T18:57:24.980000 | 2008-09-07T19:47:36.060000 |
48,688 | 90,648 | How to save persistent objects databound to a DataLayoutControl (DevExpress tools)? | I have a small form displaying the DataLayoutControl component. If I use a GridControl the objects get saved. If I use the DataLayoutControl (which shows them individually) they do not get saved after they are changed. The underlying object is changed after the user interface edits, but doesn't get saved. How can I enable this? PS: I have tried UnitOfWork.CommitChanges (i have one uow going through the whole architecture) to no avail. | You should have a Session and an XPCollection on the form where the DataLayoutControl is. You should hook XPCollection with Session. You select the right class for the XPCollection and maybe add some criterial that make the XPCollection return zero records. Hook XPCollection to the DataLayoutControl. Then you should provide a constructor with a parameter: The Oid of the object you want to edit. Inside the constructor you should use the Criteria to make the XPCollection contain only that object. Make sure you call Session.Save() in your Save button or menu item. | How to save persistent objects databound to a DataLayoutControl (DevExpress tools)? I have a small form displaying the DataLayoutControl component. If I use a GridControl the objects get saved. If I use the DataLayoutControl (which shows them individually) they do not get saved after they are changed. The underlying object is changed after the user interface edits, but doesn't get saved. How can I enable this? PS: I have tried UnitOfWork.CommitChanges (i have one uow going through the whole architecture) to no avail. | TITLE:
How to save persistent objects databound to a DataLayoutControl (DevExpress tools)?
QUESTION:
I have a small form displaying the DataLayoutControl component. If I use a GridControl the objects get saved. If I use the DataLayoutControl (which shows them individually) they do not get saved after they are changed. The underlying object is changed after the user interface edits, but doesn't get saved. How can I enable this? PS: I have tried UnitOfWork.CommitChanges (i have one uow going through the whole architecture) to no avail.
ANSWER:
You should have a Session and an XPCollection on the form where the DataLayoutControl is. You should hook XPCollection with Session. You select the right class for the XPCollection and maybe add some criterial that make the XPCollection return zero records. Hook XPCollection to the DataLayoutControl. Then you should provide a constructor with a parameter: The Oid of the object you want to edit. Inside the constructor you should use the Criteria to make the XPCollection contain only that object. Make sure you call Session.Save() in your Save button or menu item. | [
".net",
"devexpress",
"xpo"
] | 3 | 3 | 2,479 | 1 | 0 | 2008-09-07T19:07:50.337000 | 2008-09-18T07:09:42.297000 |
48,733 | 50,509 | How to maintain Hibernate cache consistency running two Java applications? | Our design has one jvm that is a jboss/webapp (read/write) that is used to maintain the data via hibernate (using jpa) to the db. The model has 10-15 persistent classes with 3-5 levels of depth in the relationships. We then have a separate jvm that is the server using this data. As it is running continuously we just have one long db session (read only). There is currently no intra-jvm cache involved - so we manually signal one jvm from the other. Now when the webapp changes some data, it signals the server to reload the changed data. What we have found is that we need to tell hibernate to purge the data and then reload it. Just doing a fetch/merge with the db does not do the job - mainly in respect of the objects several layers down the hierarchy. Any thoughts on whether there is anything fundamentally wrong with this design or if anyone is doing this and has had better luck with working with hibernate on the reloads. Thanks, Chris | A Hibernate session loads all data it reads from the DB into what they call the first-level cache. Once a row is loaded from the DB, any subsequent fetches for a row with the same PK will return the data from this cache. Furthermore, Hibernate gaurentees reference equality for objects with the same PK in a single Session. From what I understand, your read-only server application never closes its Hibernate session. So when the DB gets updated by the read-write application, the Session on read-only server is unaware of the change. Effectively, your read-only application is loading an in-memory copy of the database and using that copy, which gets stale in due course. The simplest and best course of action I can suggest is to close and open Sessions as needed. This sidesteps the whole problem. Hibernate Sessions are intended to be a window for a short-lived interaction with the DB. I agree that there is a performance gain by not reloading the object-graph again and again; but you need to measure it and convince yourself that it is worth the pains. Another option is to close and reopen the Session periodically. This ensures that the read-only application works with data not older than a given time interval. But there definitely is a window where the read-only application works with stale data (although the design guarantees that it gets the up-to-date data eventually). This might be permissible in many applications - you need to evaluate your situation. The third option is to use a second level cache implementation, and use short-lived Sessions. There are various caching packages that work with Hibernate with relative merits and demerits. | How to maintain Hibernate cache consistency running two Java applications? Our design has one jvm that is a jboss/webapp (read/write) that is used to maintain the data via hibernate (using jpa) to the db. The model has 10-15 persistent classes with 3-5 levels of depth in the relationships. We then have a separate jvm that is the server using this data. As it is running continuously we just have one long db session (read only). There is currently no intra-jvm cache involved - so we manually signal one jvm from the other. Now when the webapp changes some data, it signals the server to reload the changed data. What we have found is that we need to tell hibernate to purge the data and then reload it. Just doing a fetch/merge with the db does not do the job - mainly in respect of the objects several layers down the hierarchy. Any thoughts on whether there is anything fundamentally wrong with this design or if anyone is doing this and has had better luck with working with hibernate on the reloads. Thanks, Chris | TITLE:
How to maintain Hibernate cache consistency running two Java applications?
QUESTION:
Our design has one jvm that is a jboss/webapp (read/write) that is used to maintain the data via hibernate (using jpa) to the db. The model has 10-15 persistent classes with 3-5 levels of depth in the relationships. We then have a separate jvm that is the server using this data. As it is running continuously we just have one long db session (read only). There is currently no intra-jvm cache involved - so we manually signal one jvm from the other. Now when the webapp changes some data, it signals the server to reload the changed data. What we have found is that we need to tell hibernate to purge the data and then reload it. Just doing a fetch/merge with the db does not do the job - mainly in respect of the objects several layers down the hierarchy. Any thoughts on whether there is anything fundamentally wrong with this design or if anyone is doing this and has had better luck with working with hibernate on the reloads. Thanks, Chris
ANSWER:
A Hibernate session loads all data it reads from the DB into what they call the first-level cache. Once a row is loaded from the DB, any subsequent fetches for a row with the same PK will return the data from this cache. Furthermore, Hibernate gaurentees reference equality for objects with the same PK in a single Session. From what I understand, your read-only server application never closes its Hibernate session. So when the DB gets updated by the read-write application, the Session on read-only server is unaware of the change. Effectively, your read-only application is loading an in-memory copy of the database and using that copy, which gets stale in due course. The simplest and best course of action I can suggest is to close and open Sessions as needed. This sidesteps the whole problem. Hibernate Sessions are intended to be a window for a short-lived interaction with the DB. I agree that there is a performance gain by not reloading the object-graph again and again; but you need to measure it and convince yourself that it is worth the pains. Another option is to close and reopen the Session periodically. This ensures that the read-only application works with data not older than a given time interval. But there definitely is a window where the read-only application works with stale data (although the design guarantees that it gets the up-to-date data eventually). This might be permissible in many applications - you need to evaluate your situation. The third option is to use a second level cache implementation, and use short-lived Sessions. There are various caching packages that work with Hibernate with relative merits and demerits. | [
"java",
"hibernate",
"caching"
] | 10 | 14 | 12,817 | 4 | 0 | 2008-09-07T20:09:11.390000 | 2008-09-08T19:45:49.880000 |
48,744 | 48,826 | Finding the phone numbers in 50,000 HTML pages | How do you find the phone numbers in 50,000 HTML pages? Jeff Attwood posted 5 Questions for programmers applying for jobs: In an effort to make life simpler for phone screeners, I've put together this list of Five Essential Questions that you need to ask during an SDE screen. They won't guarantee that your candidate will be great, but they will help eliminate a huge number of candidates who are slipping through our process today. 1) Coding The candidate has to write some simple code, with correct syntax, in C, C++, or Java. 2) OO design The candidate has to define basic OO concepts, and come up with classes to model a simple problem. 3) Scripting and regexes The candidate has to describe how to find the phone numbers in 50,000 HTML pages. 4) Data structures The candidate has to demonstrate basic knowledge of the most common data structures. 5) Bits and bytes The candidate has to answer simple questions about bits, bytes, and binary numbers. Please understand: what I'm looking for here is a total vacuum in one of these areas. It's OK if they struggle a little and then figure it out. It's OK if they need some minor hints or prompting. I don't mind if they're rusty or slow. What you're looking for is candidates who are utterly clueless, or horribly confused, about the area in question. >>> The Entirety of Jeff´s Original Post <<< Note: Steve Yegge originally posed the Question. | egrep "(([0-9]{1,2}.)?[0-9]{3}.[0-9]{3}.[0-9]{4})". -R --include='*.html' | Finding the phone numbers in 50,000 HTML pages How do you find the phone numbers in 50,000 HTML pages? Jeff Attwood posted 5 Questions for programmers applying for jobs: In an effort to make life simpler for phone screeners, I've put together this list of Five Essential Questions that you need to ask during an SDE screen. They won't guarantee that your candidate will be great, but they will help eliminate a huge number of candidates who are slipping through our process today. 1) Coding The candidate has to write some simple code, with correct syntax, in C, C++, or Java. 2) OO design The candidate has to define basic OO concepts, and come up with classes to model a simple problem. 3) Scripting and regexes The candidate has to describe how to find the phone numbers in 50,000 HTML pages. 4) Data structures The candidate has to demonstrate basic knowledge of the most common data structures. 5) Bits and bytes The candidate has to answer simple questions about bits, bytes, and binary numbers. Please understand: what I'm looking for here is a total vacuum in one of these areas. It's OK if they struggle a little and then figure it out. It's OK if they need some minor hints or prompting. I don't mind if they're rusty or slow. What you're looking for is candidates who are utterly clueless, or horribly confused, about the area in question. >>> The Entirety of Jeff´s Original Post <<< Note: Steve Yegge originally posed the Question. | TITLE:
Finding the phone numbers in 50,000 HTML pages
QUESTION:
How do you find the phone numbers in 50,000 HTML pages? Jeff Attwood posted 5 Questions for programmers applying for jobs: In an effort to make life simpler for phone screeners, I've put together this list of Five Essential Questions that you need to ask during an SDE screen. They won't guarantee that your candidate will be great, but they will help eliminate a huge number of candidates who are slipping through our process today. 1) Coding The candidate has to write some simple code, with correct syntax, in C, C++, or Java. 2) OO design The candidate has to define basic OO concepts, and come up with classes to model a simple problem. 3) Scripting and regexes The candidate has to describe how to find the phone numbers in 50,000 HTML pages. 4) Data structures The candidate has to demonstrate basic knowledge of the most common data structures. 5) Bits and bytes The candidate has to answer simple questions about bits, bytes, and binary numbers. Please understand: what I'm looking for here is a total vacuum in one of these areas. It's OK if they struggle a little and then figure it out. It's OK if they need some minor hints or prompting. I don't mind if they're rusty or slow. What you're looking for is candidates who are utterly clueless, or horribly confused, about the area in question. >>> The Entirety of Jeff´s Original Post <<< Note: Steve Yegge originally posed the Question.
ANSWER:
egrep "(([0-9]{1,2}.)?[0-9]{3}.[0-9]{3}.[0-9]{4})". -R --include='*.html' | [
"regex",
"algorithm",
"language-agnostic"
] | 20 | 26 | 21,543 | 8 | 0 | 2008-09-07T20:18:50.633000 | 2008-09-07T21:53:17.523000 |
48,755 | 48,759 | When should a method be static? | In addition, are there any performance advantages to static methods over instance methods? I came across the following recently: http://www.cafeaulait.org/course/week4/22.html: When should a method be static? Neither reads from nor writes to instance fields Independent of the state of the object Mathematical methods that accept arguments, apply an algorithm to those arguments, and return a value Factory methods that serve in lieu of constructors I would be very interested in the feedback of the Stack Overflow community on this. | Make methods static when they are not part of the instance. Don't sweat the micro-optimisations. You might find you have lots of private methods that could be static but you always call from instance methods (or each other). In that case it doesn't really matter that much. However, if you want to actually be able to test your code, and perhaps use it from elsewhere, you might want to consider making those static methods in a different, non-instantiable class. | When should a method be static? In addition, are there any performance advantages to static methods over instance methods? I came across the following recently: http://www.cafeaulait.org/course/week4/22.html: When should a method be static? Neither reads from nor writes to instance fields Independent of the state of the object Mathematical methods that accept arguments, apply an algorithm to those arguments, and return a value Factory methods that serve in lieu of constructors I would be very interested in the feedback of the Stack Overflow community on this. | TITLE:
When should a method be static?
QUESTION:
In addition, are there any performance advantages to static methods over instance methods? I came across the following recently: http://www.cafeaulait.org/course/week4/22.html: When should a method be static? Neither reads from nor writes to instance fields Independent of the state of the object Mathematical methods that accept arguments, apply an algorithm to those arguments, and return a value Factory methods that serve in lieu of constructors I would be very interested in the feedback of the Stack Overflow community on this.
ANSWER:
Make methods static when they are not part of the instance. Don't sweat the micro-optimisations. You might find you have lots of private methods that could be static but you always call from instance methods (or each other). In that case it doesn't really matter that much. However, if you want to actually be able to test your code, and perhaps use it from elsewhere, you might want to consider making those static methods in a different, non-instantiable class. | [
"language-agnostic",
"static"
] | 35 | 24 | 17,269 | 8 | 0 | 2008-09-07T20:28:46.680000 | 2008-09-07T20:33:39.663000 |
48,757 | 48,837 | Unhandled exceptions filter in a windows service | I am creating a windows service and want to know best practices for this. In all my windows Program I have a form that asks the user if he wants to report the error and if he answers yes I created a case in FogBugz. What should I do in a windows service. | You could also have a system tray representation of the service which would show a small notification about any errors and ask the user whether they want it reported or not. I think that it is still better to be able to give the user the choice whenever you are sending 'out' data from their computer. | Unhandled exceptions filter in a windows service I am creating a windows service and want to know best practices for this. In all my windows Program I have a form that asks the user if he wants to report the error and if he answers yes I created a case in FogBugz. What should I do in a windows service. | TITLE:
Unhandled exceptions filter in a windows service
QUESTION:
I am creating a windows service and want to know best practices for this. In all my windows Program I have a form that asks the user if he wants to report the error and if he answers yes I created a case in FogBugz. What should I do in a windows service.
ANSWER:
You could also have a system tray representation of the service which would show a small notification about any errors and ask the user whether they want it reported or not. I think that it is still better to be able to give the user the choice whenever you are sending 'out' data from their computer. | [
".net",
"exception",
"windows-services"
] | 3 | 1 | 400 | 2 | 0 | 2008-09-07T20:32:40.117000 | 2008-09-07T22:11:32.050000 |
48,772 | 48,778 | How do I create a foreign key in SQL Server? | I have never "hand-coded" object creation code for SQL Server and foreign key decleration is seemingly different between SQL Server and Postgres. Here is my sql so far: drop table exams; drop table question_bank; drop table anwser_bank;
create table exams ( exam_id uniqueidentifier primary key, exam_name varchar(50), ); create table question_bank ( question_id uniqueidentifier primary key, question_exam_id uniqueidentifier not null, question_text varchar(1024) not null, question_point_value decimal, constraint question_exam_id foreign key references exams(exam_id) ); create table anwser_bank ( anwser_id uniqueidentifier primary key, anwser_question_id uniqueidentifier, anwser_text varchar(1024), anwser_is_correct bit ); When I run the query I get this error: Msg 8139, Level 16, State 0, Line 9 Number of referencing columns in foreign key differs from number of referenced columns, table 'question_bank'. Can you spot the error? | create table question_bank ( question_id uniqueidentifier primary key, question_exam_id uniqueidentifier not null, question_text varchar(1024) not null, question_point_value decimal, constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id) ); | How do I create a foreign key in SQL Server? I have never "hand-coded" object creation code for SQL Server and foreign key decleration is seemingly different between SQL Server and Postgres. Here is my sql so far: drop table exams; drop table question_bank; drop table anwser_bank;
create table exams ( exam_id uniqueidentifier primary key, exam_name varchar(50), ); create table question_bank ( question_id uniqueidentifier primary key, question_exam_id uniqueidentifier not null, question_text varchar(1024) not null, question_point_value decimal, constraint question_exam_id foreign key references exams(exam_id) ); create table anwser_bank ( anwser_id uniqueidentifier primary key, anwser_question_id uniqueidentifier, anwser_text varchar(1024), anwser_is_correct bit ); When I run the query I get this error: Msg 8139, Level 16, State 0, Line 9 Number of referencing columns in foreign key differs from number of referenced columns, table 'question_bank'. Can you spot the error? | TITLE:
How do I create a foreign key in SQL Server?
QUESTION:
I have never "hand-coded" object creation code for SQL Server and foreign key decleration is seemingly different between SQL Server and Postgres. Here is my sql so far: drop table exams; drop table question_bank; drop table anwser_bank;
create table exams ( exam_id uniqueidentifier primary key, exam_name varchar(50), ); create table question_bank ( question_id uniqueidentifier primary key, question_exam_id uniqueidentifier not null, question_text varchar(1024) not null, question_point_value decimal, constraint question_exam_id foreign key references exams(exam_id) ); create table anwser_bank ( anwser_id uniqueidentifier primary key, anwser_question_id uniqueidentifier, anwser_text varchar(1024), anwser_is_correct bit ); When I run the query I get this error: Msg 8139, Level 16, State 0, Line 9 Number of referencing columns in foreign key differs from number of referenced columns, table 'question_bank'. Can you spot the error?
ANSWER:
create table question_bank ( question_id uniqueidentifier primary key, question_exam_id uniqueidentifier not null, question_text varchar(1024) not null, question_point_value decimal, constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id) ); | [
"sql",
"sql-server",
"t-sql"
] | 262 | 209 | 480,970 | 11 | 0 | 2008-09-07T20:49:56.440000 | 2008-09-07T20:57:59.120000 |
48,773 | 48,792 | Adding extra information to a custom exception | I've created a custom exception for a very specific problem that can go wrong. I receive data from another system, and I raise the exception if it bombs while trying to parse that data. In my custom exception, I added a field called "ResponseData", so I can track exactly what my code couldn't handle. In custom exceptions such as this one, should that extra response data go into the exception "message"? If it goes there, the message could be huge. I kind of want it there because I'm using Elmah, and that's how I can get at that data. So the question is either: - How can I get Elmah to record extra information from a field in a custom exception OR - Should extra exception details go into the "message" property? | You shouldn't fill.Message with debug information, but rather with a concise, helpful piece of text. http://msdn.microsoft.com/en-us/library/system.exception.message.aspx The text of Message should completely describe the error and should, when possible, explain how to correct it. The value of the Message property is included in the information returned by ToString. The Message property is set only when creating an Exception. If no message was supplied to the constructor for the current instance, the system supplies a default message that is formatted using the current system culture. [..] Notes to Inheritors: The Message property is overridden in classes that require control over message content or format. Application code typically accesses this property when it needs to display information about an exception that has been caught. The error message should be localized. Response data does not qualify as a description. Not being familiar with elmah, I can't tell you how to extend the Exception class while using it. Does elmah implement its own subclass to Exception? Or an interface? Can you subclass it yourself? | Adding extra information to a custom exception I've created a custom exception for a very specific problem that can go wrong. I receive data from another system, and I raise the exception if it bombs while trying to parse that data. In my custom exception, I added a field called "ResponseData", so I can track exactly what my code couldn't handle. In custom exceptions such as this one, should that extra response data go into the exception "message"? If it goes there, the message could be huge. I kind of want it there because I'm using Elmah, and that's how I can get at that data. So the question is either: - How can I get Elmah to record extra information from a field in a custom exception OR - Should extra exception details go into the "message" property? | TITLE:
Adding extra information to a custom exception
QUESTION:
I've created a custom exception for a very specific problem that can go wrong. I receive data from another system, and I raise the exception if it bombs while trying to parse that data. In my custom exception, I added a field called "ResponseData", so I can track exactly what my code couldn't handle. In custom exceptions such as this one, should that extra response data go into the exception "message"? If it goes there, the message could be huge. I kind of want it there because I'm using Elmah, and that's how I can get at that data. So the question is either: - How can I get Elmah to record extra information from a field in a custom exception OR - Should extra exception details go into the "message" property?
ANSWER:
You shouldn't fill.Message with debug information, but rather with a concise, helpful piece of text. http://msdn.microsoft.com/en-us/library/system.exception.message.aspx The text of Message should completely describe the error and should, when possible, explain how to correct it. The value of the Message property is included in the information returned by ToString. The Message property is set only when creating an Exception. If no message was supplied to the constructor for the current instance, the system supplies a default message that is formatted using the current system culture. [..] Notes to Inheritors: The Message property is overridden in classes that require control over message content or format. Application code typically accesses this property when it needs to display information about an exception that has been caught. The error message should be localized. Response data does not qualify as a description. Not being familiar with elmah, I can't tell you how to extend the Exception class while using it. Does elmah implement its own subclass to Exception? Or an interface? Can you subclass it yourself? | [
"c#",
".net",
"exception",
"elmah"
] | 13 | 7 | 11,840 | 6 | 0 | 2008-09-07T20:50:00.717000 | 2008-09-07T21:14:13.967000 |
48,774 | 64,106 | Boolean Expressions in Shell Scripts | What's the "right" way to do the following as a boolean expression? for i in `ls $1/resources`; do if [ $i!= "database.db" ] then if [ $i!= "tiles" ] then if [ $i!= "map.pdf" ] then if [ $i!= "map.png" ] then svn export -q $1/resources/$i../MyProject/Resources/$i... | The other solutions have a couple of common mistakes: http://www.pixelbeat.org/programming/shell_script_mistakes.html for i in $(ls...) is redundant/problematic just do: for i in $1/resources*; do... [ $i!= file1 -a $1!= file2 ] This actually has 2 problems. a. The $i is not quoted, hence names with spaces will cause issues b. -a is inefficient if stat ing files as it doesn't short circuit (I know the above is not stat ing files). So instead try: for i in $1/resources/*; do if [ "$i"!= "database.db" ] && [ "$i"!= "tiles" ] && [ "$i"!= "map.pdf" ] && [ "$i"!= "map.png" ]; then svn export -q "$i" "../MyProject/Resources/$(basename $i)" fi done | Boolean Expressions in Shell Scripts What's the "right" way to do the following as a boolean expression? for i in `ls $1/resources`; do if [ $i!= "database.db" ] then if [ $i!= "tiles" ] then if [ $i!= "map.pdf" ] then if [ $i!= "map.png" ] then svn export -q $1/resources/$i../MyProject/Resources/$i... | TITLE:
Boolean Expressions in Shell Scripts
QUESTION:
What's the "right" way to do the following as a boolean expression? for i in `ls $1/resources`; do if [ $i!= "database.db" ] then if [ $i!= "tiles" ] then if [ $i!= "map.pdf" ] then if [ $i!= "map.png" ] then svn export -q $1/resources/$i../MyProject/Resources/$i...
ANSWER:
The other solutions have a couple of common mistakes: http://www.pixelbeat.org/programming/shell_script_mistakes.html for i in $(ls...) is redundant/problematic just do: for i in $1/resources*; do... [ $i!= file1 -a $1!= file2 ] This actually has 2 problems. a. The $i is not quoted, hence names with spaces will cause issues b. -a is inefficient if stat ing files as it doesn't short circuit (I know the above is not stat ing files). So instead try: for i in $1/resources/*; do if [ "$i"!= "database.db" ] && [ "$i"!= "tiles" ] && [ "$i"!= "map.pdf" ] && [ "$i"!= "map.png" ]; then svn export -q "$i" "../MyProject/Resources/$(basename $i)" fi done | [
"bash",
"shell",
"expression"
] | 11 | 11 | 19,537 | 5 | 0 | 2008-09-07T20:51:35.470000 | 2008-09-15T15:47:04.653000 |
48,777 | 48,806 | Python: No module named core.exceptions | I'm trying to get Google AppEngine to work on my Debian box and am getting the following error when I try to access my page:: No module named core.exceptions The same app works fine for me when I run it on my other Ubuntu box, so I know it's not a problem with the app itself. However, I need to get it working on this Debian box. It originally had python 2.4 but after AppEngine complained about it I installed the python2.5 and python2.5-dev packages (to no avail). I saw on this Google Group post that it may be due to the version of AppEngine and just to reinstall it, but that didn't work. Any ideas? Edit 1: Also tried uninstalling python2.4 and 2.5 then reinstalling 2.5, which also didn't work. Edit 2: Turns out when I made AppEngine into a CVS project it didn't add the core directory into my project, so when I checked it out there literally was no module named core.exceptions. Re-downloading that folder resolved the problem. | core.exceptions is part of django; what version of django do you have installed? The AppEngine comes with the appropriate version for whatever release you've downloaded (in the lib/django directory). It can be installed by going to that directory and running python setup.py install | Python: No module named core.exceptions I'm trying to get Google AppEngine to work on my Debian box and am getting the following error when I try to access my page:: No module named core.exceptions The same app works fine for me when I run it on my other Ubuntu box, so I know it's not a problem with the app itself. However, I need to get it working on this Debian box. It originally had python 2.4 but after AppEngine complained about it I installed the python2.5 and python2.5-dev packages (to no avail). I saw on this Google Group post that it may be due to the version of AppEngine and just to reinstall it, but that didn't work. Any ideas? Edit 1: Also tried uninstalling python2.4 and 2.5 then reinstalling 2.5, which also didn't work. Edit 2: Turns out when I made AppEngine into a CVS project it didn't add the core directory into my project, so when I checked it out there literally was no module named core.exceptions. Re-downloading that folder resolved the problem. | TITLE:
Python: No module named core.exceptions
QUESTION:
I'm trying to get Google AppEngine to work on my Debian box and am getting the following error when I try to access my page:: No module named core.exceptions The same app works fine for me when I run it on my other Ubuntu box, so I know it's not a problem with the app itself. However, I need to get it working on this Debian box. It originally had python 2.4 but after AppEngine complained about it I installed the python2.5 and python2.5-dev packages (to no avail). I saw on this Google Group post that it may be due to the version of AppEngine and just to reinstall it, but that didn't work. Any ideas? Edit 1: Also tried uninstalling python2.4 and 2.5 then reinstalling 2.5, which also didn't work. Edit 2: Turns out when I made AppEngine into a CVS project it didn't add the core directory into my project, so when I checked it out there literally was no module named core.exceptions. Re-downloading that folder resolved the problem.
ANSWER:
core.exceptions is part of django; what version of django do you have installed? The AppEngine comes with the appropriate version for whatever release you've downloaded (in the lib/django directory). It can be installed by going to that directory and running python setup.py install | [
"python",
"google-app-engine"
] | 6 | 6 | 2,740 | 1 | 0 | 2008-09-07T20:57:16.923000 | 2008-09-07T21:28:54.350000 |
48,782 | 60,327 | TinyMCE vs Xinha | I have to choose an online WYSIWYG editor. I'm pending between TinyMCE and Xinha. My application is developed in Asp.Net 3.5. Could you help me with with some pros and cons? | Haven't tried Xihna myself, but I have experience with TinyMCE and FCKeditor. In my company we switched to TinyMce (from FCKeditor) due to the superior support for pasting from word documents and the (relatively easy to work with) plugin architecture which we used to add some custom modules (links browser, simple file browser). TinyMCE also converts the text to xhtml code which is usually better. | TinyMCE vs Xinha I have to choose an online WYSIWYG editor. I'm pending between TinyMCE and Xinha. My application is developed in Asp.Net 3.5. Could you help me with with some pros and cons? | TITLE:
TinyMCE vs Xinha
QUESTION:
I have to choose an online WYSIWYG editor. I'm pending between TinyMCE and Xinha. My application is developed in Asp.Net 3.5. Could you help me with with some pros and cons?
ANSWER:
Haven't tried Xihna myself, but I have experience with TinyMCE and FCKeditor. In my company we switched to TinyMce (from FCKeditor) due to the superior support for pasting from word documents and the (relatively easy to work with) plugin architecture which we used to add some custom modules (links browser, simple file browser). TinyMCE also converts the text to xhtml code which is usually better. | [
"html",
"editor",
"tinymce",
"wysiwyg"
] | 4 | 5 | 5,033 | 7 | 0 | 2008-09-07T21:00:06.153000 | 2008-09-13T04:23:22.987000 |
48,805 | 48,809 | How do you access browser history? | Some e-Marketing tools claim to choose which web page to display based on where you were before. That is, if you've been browsing truck sites and then go to Ford.com, your first page would be of the Ford Explorer. I know you can get the immediate preceding page with HTTP_REFERRER, but how do you know where they were 6 sites ago? | Javascript this should get you started: http://www.dicabrio.com/javascript/steal-history.php There are more nefarius means to: http://ha.ckers.org/blog/20070228/steal-browser-history-without-javascript/ Edit:I wanted to add that although this works it is a sleazy marketing teqnique and an invasion of privacy. | How do you access browser history? Some e-Marketing tools claim to choose which web page to display based on where you were before. That is, if you've been browsing truck sites and then go to Ford.com, your first page would be of the Ford Explorer. I know you can get the immediate preceding page with HTTP_REFERRER, but how do you know where they were 6 sites ago? | TITLE:
How do you access browser history?
QUESTION:
Some e-Marketing tools claim to choose which web page to display based on where you were before. That is, if you've been browsing truck sites and then go to Ford.com, your first page would be of the Ford Explorer. I know you can get the immediate preceding page with HTTP_REFERRER, but how do you know where they were 6 sites ago?
ANSWER:
Javascript this should get you started: http://www.dicabrio.com/javascript/steal-history.php There are more nefarius means to: http://ha.ckers.org/blog/20070228/steal-browser-history-without-javascript/ Edit:I wanted to add that although this works it is a sleazy marketing teqnique and an invasion of privacy. | [
"browser-history"
] | 28 | 27 | 40,505 | 4 | 0 | 2008-09-07T21:26:29.693000 | 2008-09-07T21:34:59.047000 |
48,844 | 48,976 | Is the Mono Developer Support from Novell worth it? | My company are thinking about using Mono for an upcoming product, so we were thinking about the $12,995 Mono Kickstart support from Novell. Anybody here used it, is it worth it? | if i were you i'd probably start the project and then only if i needed support for mono buy the product. that way if you dont need it you wont be wasting the $13k. | Is the Mono Developer Support from Novell worth it? My company are thinking about using Mono for an upcoming product, so we were thinking about the $12,995 Mono Kickstart support from Novell. Anybody here used it, is it worth it? | TITLE:
Is the Mono Developer Support from Novell worth it?
QUESTION:
My company are thinking about using Mono for an upcoming product, so we were thinking about the $12,995 Mono Kickstart support from Novell. Anybody here used it, is it worth it?
ANSWER:
if i were you i'd probably start the project and then only if i needed support for mono buy the product. that way if you dont need it you wont be wasting the $13k. | [
"mono"
] | 4 | 4 | 332 | 1 | 0 | 2008-09-07T22:24:27.027000 | 2008-09-08T01:33:01.067000 |
48,864 | 48,917 | What is this Icarus thing that comes with MbUnit? | I've had to install MbUnit multiple times now and it keeps coming with something called the Gallilo Icarus GUI Test Runner I have tried using it thinking it was just an update to the MbUnit GUI but it won't detect my MbUnit tests and sometimes won't even open the assemblies properly. Perhaps I'm just overlooking it but I haven't been able to find much of an answer on their website either except that it has something to do with a new testing platform. Can someone give me a better explanation of what this is? | According to a blog entry MbUnit v3 and Gallio alpha 1, So whats going on here, Gallio is a neutral test platform that is an off shoot from the work we had done on MbUnit v3. Gallio is both a common framework and a set of runners for testing tools. MbUnit v3 uses Gallio as its native test platform, Gallio can also as Jeff mentions run MbUnit, NUnit and XUnit.net tests. For both migration purposes and to help improve how you are using your existing test framework we hope this will prove useful. We still have a lot of work to do but make no secrets of what we are up to, check out our road map. I do want to draw attention to the work we are doing with our new runners. Starting with Icarus, our new GUI. So, "Gallio is a neutral test platform" and "Icarus, [their] new GUI." | What is this Icarus thing that comes with MbUnit? I've had to install MbUnit multiple times now and it keeps coming with something called the Gallilo Icarus GUI Test Runner I have tried using it thinking it was just an update to the MbUnit GUI but it won't detect my MbUnit tests and sometimes won't even open the assemblies properly. Perhaps I'm just overlooking it but I haven't been able to find much of an answer on their website either except that it has something to do with a new testing platform. Can someone give me a better explanation of what this is? | TITLE:
What is this Icarus thing that comes with MbUnit?
QUESTION:
I've had to install MbUnit multiple times now and it keeps coming with something called the Gallilo Icarus GUI Test Runner I have tried using it thinking it was just an update to the MbUnit GUI but it won't detect my MbUnit tests and sometimes won't even open the assemblies properly. Perhaps I'm just overlooking it but I haven't been able to find much of an answer on their website either except that it has something to do with a new testing platform. Can someone give me a better explanation of what this is?
ANSWER:
According to a blog entry MbUnit v3 and Gallio alpha 1, So whats going on here, Gallio is a neutral test platform that is an off shoot from the work we had done on MbUnit v3. Gallio is both a common framework and a set of runners for testing tools. MbUnit v3 uses Gallio as its native test platform, Gallio can also as Jeff mentions run MbUnit, NUnit and XUnit.net tests. For both migration purposes and to help improve how you are using your existing test framework we hope this will prove useful. We still have a lot of work to do but make no secrets of what we are up to, check out our road map. I do want to draw attention to the work we are doing with our new runners. Starting with Icarus, our new GUI. So, "Gallio is a neutral test platform" and "Icarus, [their] new GUI." | [
"unit-testing",
"testing",
"tdd",
"automated-tests",
"mbunit"
] | 1 | 2 | 1,039 | 1 | 0 | 2008-09-07T22:51:42.420000 | 2008-09-08T00:10:38.097000 |
48,872 | 48,879 | Why/when should you use nested classes in .net? Or shouldn't you? | In Kathleen Dollard's 2008 blog post, she presents an interesting reason to use nested classes in.net. However, she also mentions that FxCop doesn't like nested classes. I'm assuming that the people writing FxCop rules aren't stupid, so there must be reasoning behind that position, but I haven't been able to find it. | Use a nested class when the class you are nesting is only useful to the enclosing class. For instance, nested classes allow you to write something like (simplified): public class SortedMap { private class TreeNode { TreeNode left; TreeNode right; } } You can make a complete definition of your class in one place, you don't have to jump through any PIMPL hoops to define how your class works, and the outside world doesn't need to see anything of your implementation. If the TreeNode class was external, you would either have to make all the fields public or make a bunch of get/set methods to use it. The outside world would have another class polluting their intellisense. | Why/when should you use nested classes in .net? Or shouldn't you? In Kathleen Dollard's 2008 blog post, she presents an interesting reason to use nested classes in.net. However, she also mentions that FxCop doesn't like nested classes. I'm assuming that the people writing FxCop rules aren't stupid, so there must be reasoning behind that position, but I haven't been able to find it. | TITLE:
Why/when should you use nested classes in .net? Or shouldn't you?
QUESTION:
In Kathleen Dollard's 2008 blog post, she presents an interesting reason to use nested classes in.net. However, she also mentions that FxCop doesn't like nested classes. I'm assuming that the people writing FxCop rules aren't stupid, so there must be reasoning behind that position, but I haven't been able to find it.
ANSWER:
Use a nested class when the class you are nesting is only useful to the enclosing class. For instance, nested classes allow you to write something like (simplified): public class SortedMap { private class TreeNode { TreeNode left; TreeNode right; } } You can make a complete definition of your class in one place, you don't have to jump through any PIMPL hoops to define how your class works, and the outside world doesn't need to see anything of your implementation. If the TreeNode class was external, you would either have to make all the fields public or make a bunch of get/set methods to use it. The outside world would have another class polluting their intellisense. | [
".net",
"class",
"nested",
"fxcop"
] | 106 | 110 | 54,035 | 14 | 0 | 2008-09-07T23:01:20.073000 | 2008-09-07T23:12:43.133000 |
48,877 | 48,900 | Choosing between Ajax, Flex and Silverlight | Ajax, Flex and Silverlight are a few ways to make more interactive web applications. What kinds of factors would you consider when deciding which to use for a new web application? Does any one of them offer better cross-platform compatibility, performance, developer tools or community support? | Here's a quick rundown of each area (with lots of helpful links): Cross-platform compatibility Ajax works in any modern browser that can run JavaScript. Flex requires Flash or anything else that can handle SWF s but, once that's installed, it's a total freeride as far as compatibility. Silverlight is tricky and misunderstood so carefully consider your userbase before going with this MS foray into the rich web applications arms race. Also keep in mind that Silverlight is still in Beta, so it may become more widely used and installed in the future as it is developed. Performance I'm fearful of making too many statements about performance because it really depends on how much you are willing to optimize and the exact nature of your application. Also, some technology stacks are just never going to be very fast. Some people out there have been making comparisons, but again, it depends on a great many factors (even the version of the browser from which you are testing!). It's probably best to choose based on other factors and optimize once you've started to develop. Developer tools There are the "golden standard" dev tools for each of the three: Ajax has basically unlimited options, depending on the rest of your technology and architecture choices. The big questions you're actually faced with are which libraries to rely upon, and Google has voiced a pretty well adopted answer with things like Web Toolkit. When you get right down to it, it's just XML and JavaScript, right? Flex is from Adobe and, just like with Flash development, you'd better stick with their homegrown tools because--well--they're making the standards as they go along. Microsoft has positioned Microsoft Expression Blend versions 2.0 and 2.5 for designing the UI of Silverlight 1.0 and 2 applications respectively. Visual Studio 2008 can be used to develop and debug Silverlight applications ( from Wikipedia ). Community support There is both official and unofficial community, corporate, and open-source support for all three options. Whichever you are already integrated with and which makes you feel most at home are very individual things, but I'll offer this advice: stick with what you know. If you are a MS developer and have MSDN as your homepage, you are probably going to think the Silverlight documentation and forums are really helpful. Flex has a very similar story; the forums are pretty good and if you're a Flash person already, you're going to be right at home with their documentation and user community. On the other hand, Ajax is basically all over the place because you can implement so many different ways and use so many widely-varied libraries. Each library can have it's own forums to visit and mailing lists to lurk within for answers. Once again, all three have corporate giants trying to foster their communities and to get the best support possible to the developers that will give them greater market share in the future. | Choosing between Ajax, Flex and Silverlight Ajax, Flex and Silverlight are a few ways to make more interactive web applications. What kinds of factors would you consider when deciding which to use for a new web application? Does any one of them offer better cross-platform compatibility, performance, developer tools or community support? | TITLE:
Choosing between Ajax, Flex and Silverlight
QUESTION:
Ajax, Flex and Silverlight are a few ways to make more interactive web applications. What kinds of factors would you consider when deciding which to use for a new web application? Does any one of them offer better cross-platform compatibility, performance, developer tools or community support?
ANSWER:
Here's a quick rundown of each area (with lots of helpful links): Cross-platform compatibility Ajax works in any modern browser that can run JavaScript. Flex requires Flash or anything else that can handle SWF s but, once that's installed, it's a total freeride as far as compatibility. Silverlight is tricky and misunderstood so carefully consider your userbase before going with this MS foray into the rich web applications arms race. Also keep in mind that Silverlight is still in Beta, so it may become more widely used and installed in the future as it is developed. Performance I'm fearful of making too many statements about performance because it really depends on how much you are willing to optimize and the exact nature of your application. Also, some technology stacks are just never going to be very fast. Some people out there have been making comparisons, but again, it depends on a great many factors (even the version of the browser from which you are testing!). It's probably best to choose based on other factors and optimize once you've started to develop. Developer tools There are the "golden standard" dev tools for each of the three: Ajax has basically unlimited options, depending on the rest of your technology and architecture choices. The big questions you're actually faced with are which libraries to rely upon, and Google has voiced a pretty well adopted answer with things like Web Toolkit. When you get right down to it, it's just XML and JavaScript, right? Flex is from Adobe and, just like with Flash development, you'd better stick with their homegrown tools because--well--they're making the standards as they go along. Microsoft has positioned Microsoft Expression Blend versions 2.0 and 2.5 for designing the UI of Silverlight 1.0 and 2 applications respectively. Visual Studio 2008 can be used to develop and debug Silverlight applications ( from Wikipedia ). Community support There is both official and unofficial community, corporate, and open-source support for all three options. Whichever you are already integrated with and which makes you feel most at home are very individual things, but I'll offer this advice: stick with what you know. If you are a MS developer and have MSDN as your homepage, you are probably going to think the Silverlight documentation and forums are really helpful. Flex has a very similar story; the forums are pretty good and if you're a Flash person already, you're going to be right at home with their documentation and user community. On the other hand, Ajax is basically all over the place because you can implement so many different ways and use so many widely-varied libraries. Each library can have it's own forums to visit and mailing lists to lurk within for answers. Once again, all three have corporate giants trying to foster their communities and to get the best support possible to the developers that will give them greater market share in the future. | [
"ajax",
"silverlight",
"apache-flex"
] | 11 | 13 | 1,534 | 5 | 0 | 2008-09-07T23:09:31.160000 | 2008-09-07T23:38:25.117000 |
48,905 | 125,852 | Fundeps and GADTs: When is type checking decidable? | I was reading a research paper about Haskell and how HList is implemented and wondering when the techniques described are and are not decidable for the type checker. Also, because you can do similar things with GADTs, I was wondering if GADT type checking is always decidable. I would prefer citations if you have them so I can read/understand the explanations. Thanks! | I believe GADT type checking is always decidable; it's inference which is undecidable, as it requires higher order unification. But a GADT type checker is a restricted form of the proof checkers you see in eg. Coq, where the constructors build up the proof term. For example, the classic example of embedding lambda calculus into GADTs has a constructor for each reduction rule, so if you want to find the normal form of a term, you have to tell it which constructors will get you to it. The halting problem has been moved into the user's hands:-) | Fundeps and GADTs: When is type checking decidable? I was reading a research paper about Haskell and how HList is implemented and wondering when the techniques described are and are not decidable for the type checker. Also, because you can do similar things with GADTs, I was wondering if GADT type checking is always decidable. I would prefer citations if you have them so I can read/understand the explanations. Thanks! | TITLE:
Fundeps and GADTs: When is type checking decidable?
QUESTION:
I was reading a research paper about Haskell and how HList is implemented and wondering when the techniques described are and are not decidable for the type checker. Also, because you can do similar things with GADTs, I was wondering if GADT type checking is always decidable. I would prefer citations if you have them so I can read/understand the explanations. Thanks!
ANSWER:
I believe GADT type checking is always decidable; it's inference which is undecidable, as it requires higher order unification. But a GADT type checker is a restricted form of the proof checkers you see in eg. Coq, where the constructors build up the proof term. For example, the classic example of embedding lambda calculus into GADTs has a constructor for each reduction rule, so if you want to find the normal form of a term, you have to tell it which constructors will get you to it. The halting problem has been moved into the user's hands:-) | [
"haskell",
"type-inference",
"type-systems",
"gadt"
] | 16 | 9 | 1,234 | 2 | 0 | 2008-09-07T23:46:50.963000 | 2008-09-24T07:35:45.513000 |
48,908 | 48,929 | How Do Sockets Work in C? | I am a bit confused about socket programming in C. You create a socket, bind it to an interface and an IP address and get it to listen. I found a couple of web resources on that, and understood it fine. In particular, I found an article Network programming under Unix systems to be very informative. What confuses me is the timing of data arriving on the socket. How can you tell when packets arrive, and how big the packet is, do you have to do all the heavy lifting yourself? My basic assumption here is that packets can be of variable length, so once binary data starts appearing down the socket, how do you begin to construct packets from that? | Short answer is that you have to do all the heavy lifting yourself. You can be notified that there is data available to be read, but you won't know how many bytes are available. In most IP protocols that use variable length packets, there will be a header with a known fixed length prepended to the packet. This header will contain the length of the packet. You read the header, get the length of the packet, then read the packet. You repeat this pattern (read header, then read packet) until communication is complete. When reading data from a socket, you request a certain number of bytes. The read call may block until the requested number of bytes are read, but it can return fewer bytes than what was requested. When this happens, you simply retry the read, requesting the remaining bytes. Here's a typical C function for reading a set number of bytes from a socket: /* buffer points to memory block that is bigger than the number of bytes to be read */ /* socket is open socket that is connected to a sender */ /* bytesToRead is the number of bytes expected from the sender */ /* bytesRead is a pointer to a integer variable that will hold the number of bytes */ /* actually received from the sender. */ /* The function returns either the number of bytes read, */ /* 0 if the socket was closed by the sender, and */ /* -1 if an error occurred while reading from the socket */ int readBytes(int socket, char *buffer, int bytesToRead, int *bytesRead) { *bytesRead = 0; while(*bytesRead < bytesToRead) { int ret = read(socket, buffer + *bytesRead, bytesToRead - *bytesRead); if(ret <= 0) { /* either connection was closed or an error occurred */ return ret; } else { *bytesRead += ret; } } return *bytesRead; } | How Do Sockets Work in C? I am a bit confused about socket programming in C. You create a socket, bind it to an interface and an IP address and get it to listen. I found a couple of web resources on that, and understood it fine. In particular, I found an article Network programming under Unix systems to be very informative. What confuses me is the timing of data arriving on the socket. How can you tell when packets arrive, and how big the packet is, do you have to do all the heavy lifting yourself? My basic assumption here is that packets can be of variable length, so once binary data starts appearing down the socket, how do you begin to construct packets from that? | TITLE:
How Do Sockets Work in C?
QUESTION:
I am a bit confused about socket programming in C. You create a socket, bind it to an interface and an IP address and get it to listen. I found a couple of web resources on that, and understood it fine. In particular, I found an article Network programming under Unix systems to be very informative. What confuses me is the timing of data arriving on the socket. How can you tell when packets arrive, and how big the packet is, do you have to do all the heavy lifting yourself? My basic assumption here is that packets can be of variable length, so once binary data starts appearing down the socket, how do you begin to construct packets from that?
ANSWER:
Short answer is that you have to do all the heavy lifting yourself. You can be notified that there is data available to be read, but you won't know how many bytes are available. In most IP protocols that use variable length packets, there will be a header with a known fixed length prepended to the packet. This header will contain the length of the packet. You read the header, get the length of the packet, then read the packet. You repeat this pattern (read header, then read packet) until communication is complete. When reading data from a socket, you request a certain number of bytes. The read call may block until the requested number of bytes are read, but it can return fewer bytes than what was requested. When this happens, you simply retry the read, requesting the remaining bytes. Here's a typical C function for reading a set number of bytes from a socket: /* buffer points to memory block that is bigger than the number of bytes to be read */ /* socket is open socket that is connected to a sender */ /* bytesToRead is the number of bytes expected from the sender */ /* bytesRead is a pointer to a integer variable that will hold the number of bytes */ /* actually received from the sender. */ /* The function returns either the number of bytes read, */ /* 0 if the socket was closed by the sender, and */ /* -1 if an error occurred while reading from the socket */ int readBytes(int socket, char *buffer, int bytesToRead, int *bytesRead) { *bytesRead = 0; while(*bytesRead < bytesToRead) { int ret = read(socket, buffer + *bytesRead, bytesToRead - *bytesRead); if(ret <= 0) { /* either connection was closed or an error occurred */ return ret; } else { *bytesRead += ret; } } return *bytesRead; } | [
"c",
"sockets",
"network-programming"
] | 21 | 17 | 7,338 | 4 | 0 | 2008-09-08T00:00:32.020000 | 2008-09-08T00:27:17.370000 |
48,916 | 48,971 | Multi-threaded splash screen in C#? | I want a splash screen to show while the application is loading. I have a form with a system tray control tied to it. I want the splash screen to display while this form loads, which takes a bit of time since it's accessing a web service API to populate some drop-downs. I also want to do some basic testing for dependencies before loading (that is, the web service is available, the configuration file is readable). As each phase of the startup goes, I want to update the splash screen with progress. I have been reading a lot on threading, but I am getting lost on where this should be controlled from (the main() method?). I am also missing how Application.Run() works, is this where the threads for this should be created from? Now, if the form with the system tray control is the "living" form, should the splash come from there? Wouldn't it not load until the form is completed anyway? I'm not looking for a code handout, more of an algorithm/approach so I can figure this out once and for all:) | Well, for a ClickOnce app that I deployed in the past, we used the Microsoft.VisualBasic namespace to handle the splash screen threading. You can reference and use the Microsoft.VisualBasic assembly from C# in.NET 2.0 and it provides a lot of nice services. Have the main form inherit from Microsoft.VisualBasic.WindowsFormsApplicationBase Override the "OnCreateSplashScreen" method like so: protected override void OnCreateSplashScreen() { this.SplashScreen = new SplashForm(); this.SplashScreen.TopMost = true; } Very straightforward, it shows your SplashForm (which you need to create) while loading is going on, then closes it automatically once the main form has completed loading. This really makes things simple, and the VisualBasic.WindowsFormsApplicationBase is of course well tested by Microsoft and has a lot of functionality that can make your life a lot easier in Winforms, even in an application that is 100% C#. At the end of the day, it's all IL and bytecode anyway, so why not use it? | Multi-threaded splash screen in C#? I want a splash screen to show while the application is loading. I have a form with a system tray control tied to it. I want the splash screen to display while this form loads, which takes a bit of time since it's accessing a web service API to populate some drop-downs. I also want to do some basic testing for dependencies before loading (that is, the web service is available, the configuration file is readable). As each phase of the startup goes, I want to update the splash screen with progress. I have been reading a lot on threading, but I am getting lost on where this should be controlled from (the main() method?). I am also missing how Application.Run() works, is this where the threads for this should be created from? Now, if the form with the system tray control is the "living" form, should the splash come from there? Wouldn't it not load until the form is completed anyway? I'm not looking for a code handout, more of an algorithm/approach so I can figure this out once and for all:) | TITLE:
Multi-threaded splash screen in C#?
QUESTION:
I want a splash screen to show while the application is loading. I have a form with a system tray control tied to it. I want the splash screen to display while this form loads, which takes a bit of time since it's accessing a web service API to populate some drop-downs. I also want to do some basic testing for dependencies before loading (that is, the web service is available, the configuration file is readable). As each phase of the startup goes, I want to update the splash screen with progress. I have been reading a lot on threading, but I am getting lost on where this should be controlled from (the main() method?). I am also missing how Application.Run() works, is this where the threads for this should be created from? Now, if the form with the system tray control is the "living" form, should the splash come from there? Wouldn't it not load until the form is completed anyway? I'm not looking for a code handout, more of an algorithm/approach so I can figure this out once and for all:)
ANSWER:
Well, for a ClickOnce app that I deployed in the past, we used the Microsoft.VisualBasic namespace to handle the splash screen threading. You can reference and use the Microsoft.VisualBasic assembly from C# in.NET 2.0 and it provides a lot of nice services. Have the main form inherit from Microsoft.VisualBasic.WindowsFormsApplicationBase Override the "OnCreateSplashScreen" method like so: protected override void OnCreateSplashScreen() { this.SplashScreen = new SplashForm(); this.SplashScreen.TopMost = true; } Very straightforward, it shows your SplashForm (which you need to create) while loading is going on, then closes it automatically once the main form has completed loading. This really makes things simple, and the VisualBasic.WindowsFormsApplicationBase is of course well tested by Microsoft and has a lot of functionality that can make your life a lot easier in Winforms, even in an application that is 100% C#. At the end of the day, it's all IL and bytecode anyway, so why not use it? | [
"c#",
".net",
"winforms",
"multithreading",
"splash-screen"
] | 62 | 46 | 45,815 | 12 | 0 | 2008-09-08T00:10:07.490000 | 2008-09-08T01:28:03.933000 |
48,931 | 49,434 | How to read bound hover callback functions in jQuery | I used jQuery to set hover callbacks for elements on my page. I'm now writing a module which needs to temporarily set new hover behaviour for some elements. The new module has no access to the original code for the hover functions. I want to store the old hover functions before I set new ones so I can restore them when finished with the temporary hover behaviour. I think these can be stored using the jQuery.data() function: //save old hover behavior (somehow)
$('#foo').data('oldhoverin',???)
$('#foo').data('oldhoverout',???);
//set new hover behavior
$('#foo').hover(newhoverin,newhoverout); Do stuff with new hover behaviour... //restore old hover behaviour $('#foo').hover($('#foo').data('oldhoverin'),$('#foo').data('oldhoverout')); But how do I get the currently registered hover functions from jQuery? Shadow2531, I am trying to do this without modifying the code which originally registered the callbacks. Your suggestion would work fine otherwise. Thanks for the suggestion, and for helping clarify what I'm searching for. Maybe I have to go into the source of jquery and figure out how these callbacks are stored internally. Maybe I should change the question to "Is it possible to do this without modifying jquery?" | Calling an event bind method (such as hover ) does not delete old event handlers, only adds your new events, so your idea of 'restoring' the old event functions wouldn't work, as it wouldn't delete your events. You can add your own events, and then remove them without affecting any other events then use Event namespacing: http://docs.jquery.com/Events_(Guide)#Namespacing_events | How to read bound hover callback functions in jQuery I used jQuery to set hover callbacks for elements on my page. I'm now writing a module which needs to temporarily set new hover behaviour for some elements. The new module has no access to the original code for the hover functions. I want to store the old hover functions before I set new ones so I can restore them when finished with the temporary hover behaviour. I think these can be stored using the jQuery.data() function: //save old hover behavior (somehow)
$('#foo').data('oldhoverin',???)
$('#foo').data('oldhoverout',???);
//set new hover behavior
$('#foo').hover(newhoverin,newhoverout); Do stuff with new hover behaviour... //restore old hover behaviour $('#foo').hover($('#foo').data('oldhoverin'),$('#foo').data('oldhoverout')); But how do I get the currently registered hover functions from jQuery? Shadow2531, I am trying to do this without modifying the code which originally registered the callbacks. Your suggestion would work fine otherwise. Thanks for the suggestion, and for helping clarify what I'm searching for. Maybe I have to go into the source of jquery and figure out how these callbacks are stored internally. Maybe I should change the question to "Is it possible to do this without modifying jquery?" | TITLE:
How to read bound hover callback functions in jQuery
QUESTION:
I used jQuery to set hover callbacks for elements on my page. I'm now writing a module which needs to temporarily set new hover behaviour for some elements. The new module has no access to the original code for the hover functions. I want to store the old hover functions before I set new ones so I can restore them when finished with the temporary hover behaviour. I think these can be stored using the jQuery.data() function: //save old hover behavior (somehow)
$('#foo').data('oldhoverin',???)
$('#foo').data('oldhoverout',???);
//set new hover behavior
$('#foo').hover(newhoverin,newhoverout); Do stuff with new hover behaviour... //restore old hover behaviour $('#foo').hover($('#foo').data('oldhoverin'),$('#foo').data('oldhoverout')); But how do I get the currently registered hover functions from jQuery? Shadow2531, I am trying to do this without modifying the code which originally registered the callbacks. Your suggestion would work fine otherwise. Thanks for the suggestion, and for helping clarify what I'm searching for. Maybe I have to go into the source of jquery and figure out how these callbacks are stored internally. Maybe I should change the question to "Is it possible to do this without modifying jquery?"
ANSWER:
Calling an event bind method (such as hover ) does not delete old event handlers, only adds your new events, so your idea of 'restoring' the old event functions wouldn't work, as it wouldn't delete your events. You can add your own events, and then remove them without affecting any other events then use Event namespacing: http://docs.jquery.com/Events_(Guide)#Namespacing_events | [
"javascript",
"jquery",
"callback"
] | 5 | 4 | 6,144 | 4 | 0 | 2008-09-08T00:29:58.330000 | 2008-09-08T10:35:30.263000 |
48,933 | 48,952 | How do I list loaded plugins in Vim? | Does anybody know of a way to list up the "loaded plugins" in Vim? I know I should be keeping track of this kind of stuff myself but it would always be nice to be able to check the current status. | Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following VIM Tips site: " where was an option set:scriptnames: list all plugins, _vimrcs loaded (super):verbose set history?: reveals value of history and where set:function: list functions:func SearchCompl: List particular function | How do I list loaded plugins in Vim? Does anybody know of a way to list up the "loaded plugins" in Vim? I know I should be keeping track of this kind of stuff myself but it would always be nice to be able to check the current status. | TITLE:
How do I list loaded plugins in Vim?
QUESTION:
Does anybody know of a way to list up the "loaded plugins" in Vim? I know I should be keeping track of this kind of stuff myself but it would always be nice to be able to check the current status.
ANSWER:
Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following VIM Tips site: " where was an option set:scriptnames: list all plugins, _vimrcs loaded (super):verbose set history?: reveals value of history and where set:function: list functions:func SearchCompl: List particular function | [
"vim",
"plugins"
] | 336 | 417 | 151,142 | 6 | 0 | 2008-09-08T00:32:56.030000 | 2008-09-08T01:02:10.017000 |
48,934 | 48,938 | In Delphi 7, why can I assign a value to a const? | I copied some Delphi code from one project to another, and found that it doesn't compile in the new project, though it did in the old one. The code looks something like this: procedure TForm1.CalculateGP(..) const Price: money = 0; begin... Price:= 1.0;... end; So in the new project, Delphi complains that "left side cannot be assigned to" - understandable! But this code compiles in the old project. So my question is, why? Is there a compiler switch to allow consts to be reassigned? How does that even work? I thought consts were replaced by their values at compile time? | You need to turn assignable typed constants on.
Project -> Options -> Compiler -> Assignable typed Constants Also you can add {$J+} or {$WRITEABLECONST ON} to the pas file, which is probably better, since it'll work even if you move the file to another project. | In Delphi 7, why can I assign a value to a const? I copied some Delphi code from one project to another, and found that it doesn't compile in the new project, though it did in the old one. The code looks something like this: procedure TForm1.CalculateGP(..) const Price: money = 0; begin... Price:= 1.0;... end; So in the new project, Delphi complains that "left side cannot be assigned to" - understandable! But this code compiles in the old project. So my question is, why? Is there a compiler switch to allow consts to be reassigned? How does that even work? I thought consts were replaced by their values at compile time? | TITLE:
In Delphi 7, why can I assign a value to a const?
QUESTION:
I copied some Delphi code from one project to another, and found that it doesn't compile in the new project, though it did in the old one. The code looks something like this: procedure TForm1.CalculateGP(..) const Price: money = 0; begin... Price:= 1.0;... end; So in the new project, Delphi complains that "left side cannot be assigned to" - understandable! But this code compiles in the old project. So my question is, why? Is there a compiler switch to allow consts to be reassigned? How does that even work? I thought consts were replaced by their values at compile time?
ANSWER:
You need to turn assignable typed constants on.
Project -> Options -> Compiler -> Assignable typed Constants Also you can add {$J+} or {$WRITEABLECONST ON} to the pas file, which is probably better, since it'll work even if you move the file to another project. | [
"delphi",
"constants"
] | 21 | 30 | 8,728 | 4 | 0 | 2008-09-08T00:34:45.560000 | 2008-09-08T00:46:42.083000 |
48,935 | 49,171 | How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5? | I'm building an application in C# using WPF. How can I bind to some keys? Also, how can I bind to the Windows key? | I'm not sure of what you mean by "global" here, but here it goes (I'm assuming you mean a command at the application level, for example, Save All that can be triggered from anywhere by Ctrl + Shift + S.) You find the global UIElement of your choice, for example, the top level window which is the parent of all the controls where you need this binding. Due to "bubbling" of WPF events, events at child elements will bubble all the way up to the root of the control tree. Now, first you need to bind the Key-Combo with a Command using an InputBinding like this you can then hookup the command to your handler (e.g. code that gets called by SaveAll ) via a CommandBinding. For the Windows Key, you use the right Key enumerated member, Key.LWin or Key.RWin public WindowMain() { InitializeComponent();
// Bind Key var ib = new InputBinding( MyAppCommands.SaveAll, new KeyGesture(Key.S, ModifierKeys.Shift | ModifierKeys.Control)); this.InputBindings.Add(ib);
// Bind handler var cb = new CommandBinding( MyAppCommands.SaveAll); cb.Executed += new ExecutedRoutedEventHandler( HandlerThatSavesEverthing );
this.CommandBindings.Add (cb ); }
private void HandlerThatSavesEverthing (object obSender, ExecutedRoutedEventArgs e) { // Do the Save All thing here. } | How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5? I'm building an application in C# using WPF. How can I bind to some keys? Also, how can I bind to the Windows key? | TITLE:
How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?
QUESTION:
I'm building an application in C# using WPF. How can I bind to some keys? Also, how can I bind to the Windows key?
ANSWER:
I'm not sure of what you mean by "global" here, but here it goes (I'm assuming you mean a command at the application level, for example, Save All that can be triggered from anywhere by Ctrl + Shift + S.) You find the global UIElement of your choice, for example, the top level window which is the parent of all the controls where you need this binding. Due to "bubbling" of WPF events, events at child elements will bubble all the way up to the root of the control tree. Now, first you need to bind the Key-Combo with a Command using an InputBinding like this you can then hookup the command to your handler (e.g. code that gets called by SaveAll ) via a CommandBinding. For the Windows Key, you use the right Key enumerated member, Key.LWin or Key.RWin public WindowMain() { InitializeComponent();
// Bind Key var ib = new InputBinding( MyAppCommands.SaveAll, new KeyGesture(Key.S, ModifierKeys.Shift | ModifierKeys.Control)); this.InputBindings.Add(ib);
// Bind handler var cb = new CommandBinding( MyAppCommands.SaveAll); cb.Executed += new ExecutedRoutedEventHandler( HandlerThatSavesEverthing );
this.CommandBindings.Add (cb ); }
private void HandlerThatSavesEverthing (object obSender, ExecutedRoutedEventArgs e) { // Do the Save All thing here. } | [
"c#",
".net",
"wpf",
"windows",
"hotkeys"
] | 53 | 28 | 73,324 | 11 | 0 | 2008-09-08T00:35:47.477000 | 2008-09-08T04:36:33.417000 |
48,947 | 50,596 | How do I implement a callback in PHP? | How are callbacks written in PHP? | The manual uses the terms "callback" and "callable" interchangeably, however, "callback" traditionally refers to a string or array value that acts like a function pointer, referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are: $cb1 = 'someGlobalFunction'; $cb2 = ['ClassName', 'someStaticMethod']; $cb3 = [$object, 'somePublicMethod'];
// this syntax is callable since PHP 5.2.3 but a string containing it // cannot be called directly $cb2 = 'ClassName::someStaticMethod'; $cb2(); // fatal error
// legacy syntax for PHP 4 $cb3 = array(&$object, 'somePublicMethod'); This is a safe way to use callable values in general: if (is_callable($cb2)) { // Autoloading will be invoked to load the class "ClassName" if it's not // yet defined, and PHP will check that the class has a method // "someStaticMethod". Note that is_callable() will NOT verify that the // method can safely be executed in static context.
$returnValue = call_user_func($cb2, $arg1, $arg2); } Modern PHP versions allow the first three formats above to be invoked directly as $cb(). call_user_func and call_user_func_array support all the above. See: http://php.net/manual/en/language.types.callable.php Notes/Caveats: If the function/class is namespaced, the string must contain the fully-qualified name. E.g. ['Vendor\Package\Foo', 'method'] call_user_func does not support passing non-objects by reference, so you can either use call_user_func_array or, in later PHP versions, save the callback to a var and use the direct syntax: $cb(); Objects with an __invoke() method (including anonymous functions) fall under the category "callable" and can be used the same way, but I personally don't associate these with the legacy "callback" term. The legacy create_function() creates a global function and returns its name. It's a wrapper for eval() and anonymous functions should be used instead. | How do I implement a callback in PHP? How are callbacks written in PHP? | TITLE:
How do I implement a callback in PHP?
QUESTION:
How are callbacks written in PHP?
ANSWER:
The manual uses the terms "callback" and "callable" interchangeably, however, "callback" traditionally refers to a string or array value that acts like a function pointer, referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are: $cb1 = 'someGlobalFunction'; $cb2 = ['ClassName', 'someStaticMethod']; $cb3 = [$object, 'somePublicMethod'];
// this syntax is callable since PHP 5.2.3 but a string containing it // cannot be called directly $cb2 = 'ClassName::someStaticMethod'; $cb2(); // fatal error
// legacy syntax for PHP 4 $cb3 = array(&$object, 'somePublicMethod'); This is a safe way to use callable values in general: if (is_callable($cb2)) { // Autoloading will be invoked to load the class "ClassName" if it's not // yet defined, and PHP will check that the class has a method // "someStaticMethod". Note that is_callable() will NOT verify that the // method can safely be executed in static context.
$returnValue = call_user_func($cb2, $arg1, $arg2); } Modern PHP versions allow the first three formats above to be invoked directly as $cb(). call_user_func and call_user_func_array support all the above. See: http://php.net/manual/en/language.types.callable.php Notes/Caveats: If the function/class is namespaced, the string must contain the fully-qualified name. E.g. ['Vendor\Package\Foo', 'method'] call_user_func does not support passing non-objects by reference, so you can either use call_user_func_array or, in later PHP versions, save the callback to a var and use the direct syntax: $cb(); Objects with an __invoke() method (including anonymous functions) fall under the category "callable" and can be used the same way, but I personally don't associate these with the legacy "callback" term. The legacy create_function() creates a global function and returns its name. It's a wrapper for eval() and anonymous functions should be used instead. | [
"php"
] | 192 | 177 | 137,008 | 9 | 0 | 2008-09-08T00:53:34.360000 | 2008-09-08T20:29:04.563000 |
48,984 | 49,136 | Is there a way to make WatiN click a link before the page finishes loading | We're using WatiN for testing our UI, but one page (which is unfortunately not under our teams control) takes forever to finish loading. Is there a way to get WatiN to click a link on the page before the page finishes rendering completely? | Here's the code we found to work: IE browser = new IE(....); browser.Button("SlowPageLoadingButton").ClickNoWait(); Link continueLink = browser.Link(Find.ByText("linktext")); continueLink.WaitUntilExists(); continueLink.Click(); | Is there a way to make WatiN click a link before the page finishes loading We're using WatiN for testing our UI, but one page (which is unfortunately not under our teams control) takes forever to finish loading. Is there a way to get WatiN to click a link on the page before the page finishes rendering completely? | TITLE:
Is there a way to make WatiN click a link before the page finishes loading
QUESTION:
We're using WatiN for testing our UI, but one page (which is unfortunately not under our teams control) takes forever to finish loading. Is there a way to get WatiN to click a link on the page before the page finishes rendering completely?
ANSWER:
Here's the code we found to work: IE browser = new IE(....); browser.Button("SlowPageLoadingButton").ClickNoWait(); Link continueLink = browser.Link(Find.ByText("linktext")); continueLink.WaitUntilExists(); continueLink.Click(); | [
"unit-testing",
"automated-tests",
"watin"
] | 6 | 11 | 4,892 | 2 | 0 | 2008-09-08T01:42:20.577000 | 2008-09-08T03:53:36.843000 |
48,993 | 49,454 | Linking combo box (JQuery preferrably) | I am wondering if anyone has any experience using a JQuery plugin that converts a html Blah combo box into something (probably a div) where selecting an item acts the same as clicking a link. I guess you could probably use javascript to handle a selection event (my javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack. Your advice, experience and recommendations are appreciated. | The simple solution is to use $("#mySelect").change(function() { document.location = this.value; }); This creates an onchange event on the select box that redirects you to the url stored in the value field of the selected option. | Linking combo box (JQuery preferrably) I am wondering if anyone has any experience using a JQuery plugin that converts a html Blah combo box into something (probably a div) where selecting an item acts the same as clicking a link. I guess you could probably use javascript to handle a selection event (my javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack. Your advice, experience and recommendations are appreciated. | TITLE:
Linking combo box (JQuery preferrably)
QUESTION:
I am wondering if anyone has any experience using a JQuery plugin that converts a html Blah combo box into something (probably a div) where selecting an item acts the same as clicking a link. I guess you could probably use javascript to handle a selection event (my javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack. Your advice, experience and recommendations are appreciated.
ANSWER:
The simple solution is to use $("#mySelect").change(function() { document.location = this.value; }); This creates an onchange event on the select box that redirects you to the url stored in the value field of the selected option. | [
"javascript",
"jquery",
"html",
"drop-down-menu"
] | 5 | 8 | 13,785 | 4 | 0 | 2008-09-08T01:51:01.100000 | 2008-09-08T10:53:42.327000 |
49,011 | 49,233 | REST how to handle query parameters when put to resource? | I have a REST data service where I want to allow the users to create new items with HTTP PUT using different formats like json,xml,csv. I'm unsure how to best handle the format specification in the url: PUT /ressource/ID/json PUT /ressource/ID/xml or PUT /ressource/ID?format=json PUT /ressource/ID?format=xml So what is the best way to specify a format indicator? If I specify the format with an query parameter and want to do a PUT how can I do this with curl? curl -T test/data.json -d "format=json" http://localhost:5000/resource/33 does not work. curl -T test/data.json http://localhost:5000/update?format=json works, but I would rather let curl build the query parameters instead of adding them by myself. | A general principle of RESTful web services is to use the features built-in to HTTP, when applicable. In this case, you can indicate the format of your PUT request's content by setting the Content-Type header to application/json or application/xml. | REST how to handle query parameters when put to resource? I have a REST data service where I want to allow the users to create new items with HTTP PUT using different formats like json,xml,csv. I'm unsure how to best handle the format specification in the url: PUT /ressource/ID/json PUT /ressource/ID/xml or PUT /ressource/ID?format=json PUT /ressource/ID?format=xml So what is the best way to specify a format indicator? If I specify the format with an query parameter and want to do a PUT how can I do this with curl? curl -T test/data.json -d "format=json" http://localhost:5000/resource/33 does not work. curl -T test/data.json http://localhost:5000/update?format=json works, but I would rather let curl build the query parameters instead of adding them by myself. | TITLE:
REST how to handle query parameters when put to resource?
QUESTION:
I have a REST data service where I want to allow the users to create new items with HTTP PUT using different formats like json,xml,csv. I'm unsure how to best handle the format specification in the url: PUT /ressource/ID/json PUT /ressource/ID/xml or PUT /ressource/ID?format=json PUT /ressource/ID?format=xml So what is the best way to specify a format indicator? If I specify the format with an query parameter and want to do a PUT how can I do this with curl? curl -T test/data.json -d "format=json" http://localhost:5000/resource/33 does not work. curl -T test/data.json http://localhost:5000/update?format=json works, but I would rather let curl build the query parameters instead of adding them by myself.
ANSWER:
A general principle of RESTful web services is to use the features built-in to HTTP, when applicable. In this case, you can indicate the format of your PUT request's content by setting the Content-Type header to application/json or application/xml. | [
"html",
"rest"
] | 4 | 15 | 7,176 | 1 | 0 | 2008-09-08T02:08:07.253000 | 2008-09-08T06:24:48.353000 |
49,035 | 49,056 | What does the const operator mean when used with a method in C++? | Given a declaration like this: class A { public: void Foo() const; }; What does it mean? Google turns up this: Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const object, and the compiler will give an error message. But I find that somewhat confusing; can anyone out there put it in better terms? Thanks. | Consider a variation of your class A. class A { public: void Foo() const; void Moo();
private: int m_nState; // Could add mutable keyword if desired int GetState() const { return m_nState; } void SetState(int val) { m_nState = val; } };
const A *A1 = new A(); A *A2 = new A();
A1->Foo(); // OK A2->Foo(); // OK
A1->Moo(); // Error - Not allowed to call non-const function on const object instance A2->Moo(); // OK The const keyword on a function declaration indicates to the compiler that the function is contractually obligated not to modify the state of A. Thus you are unable to call non- const functions within A::Foo nor change the value of member variables. To illustrate, Foo() may not invoke A::SetState as it is declared non- const, A::GetState however is ok because it is explicitly declared const. The member m_nState may not be changed either unless declared with the keyword mutable. One example of this usage of const is for 'getter' functions to obtain the value of member variables. @1800 Information: I forgot about mutable! The mutable keyword instructs the compiler to accept modifications to the member variable which would otherwise cause a compiler error. It is used when the function needs to modify state but the object is considered logically consistent (constant) regardless of the modification. | What does the const operator mean when used with a method in C++? Given a declaration like this: class A { public: void Foo() const; }; What does it mean? Google turns up this: Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const object, and the compiler will give an error message. But I find that somewhat confusing; can anyone out there put it in better terms? Thanks. | TITLE:
What does the const operator mean when used with a method in C++?
QUESTION:
Given a declaration like this: class A { public: void Foo() const; }; What does it mean? Google turns up this: Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const object, and the compiler will give an error message. But I find that somewhat confusing; can anyone out there put it in better terms? Thanks.
ANSWER:
Consider a variation of your class A. class A { public: void Foo() const; void Moo();
private: int m_nState; // Could add mutable keyword if desired int GetState() const { return m_nState; } void SetState(int val) { m_nState = val; } };
const A *A1 = new A(); A *A2 = new A();
A1->Foo(); // OK A2->Foo(); // OK
A1->Moo(); // Error - Not allowed to call non-const function on const object instance A2->Moo(); // OK The const keyword on a function declaration indicates to the compiler that the function is contractually obligated not to modify the state of A. Thus you are unable to call non- const functions within A::Foo nor change the value of member variables. To illustrate, Foo() may not invoke A::SetState as it is declared non- const, A::GetState however is ok because it is explicitly declared const. The member m_nState may not be changed either unless declared with the keyword mutable. One example of this usage of const is for 'getter' functions to obtain the value of member variables. @1800 Information: I forgot about mutable! The mutable keyword instructs the compiler to accept modifications to the member variable which would otherwise cause a compiler error. It is used when the function needs to modify state but the object is considered logically consistent (constant) regardless of the modification. | [
"c++"
] | 8 | 12 | 5,338 | 7 | 0 | 2008-09-08T02:20:19.847000 | 2008-09-08T02:37:08.667000 |
49,046 | 49,055 | Different sizeof results | Why does n not equal to 8 in the following function? void foo(char cvalue[8]) { int n = sizeof (cvalue); } But n does equal to 8 in this version of the function: void bar() { char cvalue[8]; int n = sizeof (cvalue); } | Because you can't pass entire arrays as function parameters in C. You're actually passing a pointer to it; the brackets are syntactic sugar. There are no guarantees the array you're pointing to has size 8, since you could pass this function any character pointer you want. // These all do the same thing void foo(char cvalue[8]) void foo(char cvalue[]) void foo(char *cvalue) | Different sizeof results Why does n not equal to 8 in the following function? void foo(char cvalue[8]) { int n = sizeof (cvalue); } But n does equal to 8 in this version of the function: void bar() { char cvalue[8]; int n = sizeof (cvalue); } | TITLE:
Different sizeof results
QUESTION:
Why does n not equal to 8 in the following function? void foo(char cvalue[8]) { int n = sizeof (cvalue); } But n does equal to 8 in this version of the function: void bar() { char cvalue[8]; int n = sizeof (cvalue); }
ANSWER:
Because you can't pass entire arrays as function parameters in C. You're actually passing a pointer to it; the brackets are syntactic sugar. There are no guarantees the array you're pointing to has size 8, since you could pass this function any character pointer you want. // These all do the same thing void foo(char cvalue[8]) void foo(char cvalue[]) void foo(char *cvalue) | [
"c++",
"c",
"sizeof"
] | 17 | 48 | 1,181 | 4 | 0 | 2008-09-08T02:31:38.553000 | 2008-09-08T02:35:55.923000 |
49,066 | 49,766 | Renaming the containing project folder in VS.net under TFS | I have a vs.net project, and after some refactoring, have modified the name of the project. How can I easily rename the underlying windows folder name to match this new project name under a TFS controlled project and solution? Note, I used to be able to do by fiddling with things in the background using SourceSafe... | Just right click on the folder in TFS, and select Rename. Once you commit the rename, TFS will make the changes on disk for you. As Kevin pointed out, you will want to make sure that everything is checked in, because TFS will remove the old folder and everything in it, and pull down the renamed folder with the current version of the files in it. One final note: You can't rename a folder that you haven't mapped, or that you haven't done a "Get" from. I don't know why, but TFS will disable the Rename option in these cases. At least that's what happened to me, if I remember correctly. | Renaming the containing project folder in VS.net under TFS I have a vs.net project, and after some refactoring, have modified the name of the project. How can I easily rename the underlying windows folder name to match this new project name under a TFS controlled project and solution? Note, I used to be able to do by fiddling with things in the background using SourceSafe... | TITLE:
Renaming the containing project folder in VS.net under TFS
QUESTION:
I have a vs.net project, and after some refactoring, have modified the name of the project. How can I easily rename the underlying windows folder name to match this new project name under a TFS controlled project and solution? Note, I used to be able to do by fiddling with things in the background using SourceSafe...
ANSWER:
Just right click on the folder in TFS, and select Rename. Once you commit the rename, TFS will make the changes on disk for you. As Kevin pointed out, you will want to make sure that everything is checked in, because TFS will remove the old folder and everything in it, and pull down the renamed folder with the current version of the files in it. One final note: You can't rename a folder that you haven't mapped, or that you haven't done a "Get" from. I don't know why, but TFS will disable the Rename option in these cases. At least that's what happened to me, if I remember correctly. | [
"visual-studio-2008",
"visual-studio-2005",
"tfs",
"directory"
] | 68 | 20 | 46,273 | 6 | 0 | 2008-09-08T02:45:54.887000 | 2008-09-08T14:06:23.767000 |
49,089 | 49,163 | Where WCF and ADO.Net Data services stand? | I am bit confused about ADO.Net Data Services. Is it just meant for creating RESTful web services? I know WCF started in the SOAP world but now I hear it has good support for REST. Same goes for ADO.Net data services where you can make it work in an RPC model if you cannot look at everything from a resource oriented view. At least from the demos I saw recently, it looks like ADO.Net Data Services is built on WCF stack on the server. Please correct me if I am wrong. I am not intending to start a REST vs SOAP debate but I guess things are not that crystal clear anymore. Any suggestions or guidelines on what to use where? | In my view ADO.Net data services is for creating restful services that are closely aligned with your domain model, that is the models themselves are published rather then say some form of DTO etc. Using it for RPC style services seems like a bad fit, though unfortunately even some very basic features like being able to perform a filtered counts etc. aren't available which often means you'll end up using some RPC just to meet the requirements of your customers i.e. so you can display a paged grid etc. WCF 3.5 pre-SP1 was a fairly weak RESTful platform, with SP1 things have improved in both Uri templates and with the availability of ATOMPub support, such that it's becoming more capable, but they don't really provide any elegant solution for supporting say JSON, XML, ATOM or even something more esoteric like payload like CSV simultaneously, short of having to make use of URL rewriting and different extension, method name munging etc. - rather then just selecting a serializer/deserializer based on the headers of the request. With WCF it's still difficult to create services that work in a more a natural restful manor i.e. where resources include urls, and you can transition state by navigating through them - it's a little clunky - ADO.Net data services does this quite well with it's AtomPub support though. My recommendation would be use web services where they're naturally are services and strong service boundaries being enforced, use ADO.Net Data services for rich web-style clients (websites, ajax, silverlight) where the composability of the url queries can save a lot of plumbing and your domain model is pretty basic... and roll your own REST layer (perhaps using an MVC framework as a starting point) if you need complete control over the information i.e. if you're publishing an API for other developers to consume on a social platform etc. My 2ø worth! | Where WCF and ADO.Net Data services stand? I am bit confused about ADO.Net Data Services. Is it just meant for creating RESTful web services? I know WCF started in the SOAP world but now I hear it has good support for REST. Same goes for ADO.Net data services where you can make it work in an RPC model if you cannot look at everything from a resource oriented view. At least from the demos I saw recently, it looks like ADO.Net Data Services is built on WCF stack on the server. Please correct me if I am wrong. I am not intending to start a REST vs SOAP debate but I guess things are not that crystal clear anymore. Any suggestions or guidelines on what to use where? | TITLE:
Where WCF and ADO.Net Data services stand?
QUESTION:
I am bit confused about ADO.Net Data Services. Is it just meant for creating RESTful web services? I know WCF started in the SOAP world but now I hear it has good support for REST. Same goes for ADO.Net data services where you can make it work in an RPC model if you cannot look at everything from a resource oriented view. At least from the demos I saw recently, it looks like ADO.Net Data Services is built on WCF stack on the server. Please correct me if I am wrong. I am not intending to start a REST vs SOAP debate but I guess things are not that crystal clear anymore. Any suggestions or guidelines on what to use where?
ANSWER:
In my view ADO.Net data services is for creating restful services that are closely aligned with your domain model, that is the models themselves are published rather then say some form of DTO etc. Using it for RPC style services seems like a bad fit, though unfortunately even some very basic features like being able to perform a filtered counts etc. aren't available which often means you'll end up using some RPC just to meet the requirements of your customers i.e. so you can display a paged grid etc. WCF 3.5 pre-SP1 was a fairly weak RESTful platform, with SP1 things have improved in both Uri templates and with the availability of ATOMPub support, such that it's becoming more capable, but they don't really provide any elegant solution for supporting say JSON, XML, ATOM or even something more esoteric like payload like CSV simultaneously, short of having to make use of URL rewriting and different extension, method name munging etc. - rather then just selecting a serializer/deserializer based on the headers of the request. With WCF it's still difficult to create services that work in a more a natural restful manor i.e. where resources include urls, and you can transition state by navigating through them - it's a little clunky - ADO.Net data services does this quite well with it's AtomPub support though. My recommendation would be use web services where they're naturally are services and strong service boundaries being enforced, use ADO.Net Data services for rich web-style clients (websites, ajax, silverlight) where the composability of the url queries can save a lot of plumbing and your domain model is pretty basic... and roll your own REST layer (perhaps using an MVC framework as a starting point) if you need complete control over the information i.e. if you're publishing an API for other developers to consume on a social platform etc. My 2ø worth! | [
"wcf",
"web-services",
"ado.net",
"rest"
] | 5 | 2 | 2,220 | 3 | 0 | 2008-09-08T02:59:53.633000 | 2008-09-08T04:21:09.167000 |
49,098 | 49,130 | Can cout alter variables somehow? | So I have a function that looks something like this: float function(){ float x = SomeValue; return x / SomeOtherValue; } At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the function looked like this: float function(){ float x = SomeValue; cout << x; return x / SomeOtherValue; } and it worked! Of course, I solved the problem altogether by using a double. But I'm curious as to why the function worked properly when I couted it. Is this typical, or could there be a bug somewhere else that I'm missing? (If it's any help, the value stored in the float is just an integer value, and not a particularly big one. I just put it in a float to avoid casting.) | Welcome to the wonderful world of floating point. The answer you get will likely depend on the floating point model you compiled the code with. This happens because of the difference between the IEEE spec and the hardware the code is running on. Your CPU likely has 80 bit floating point registers that get use to hold the 32-bit float value. This means that there is far more precision while the value stays in a register than when it is forced to a memory address (also known as 'homing' the register). When you passed the value to cout the compiler had to write the floating point to memory, and this results in a lost of precision and interesting behaviour WRT overflow cases. See the MSDN documentation on VC++ floating point switches. You could try compiling with /fp:strict and seeing what happens. | Can cout alter variables somehow? So I have a function that looks something like this: float function(){ float x = SomeValue; return x / SomeOtherValue; } At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the function looked like this: float function(){ float x = SomeValue; cout << x; return x / SomeOtherValue; } and it worked! Of course, I solved the problem altogether by using a double. But I'm curious as to why the function worked properly when I couted it. Is this typical, or could there be a bug somewhere else that I'm missing? (If it's any help, the value stored in the float is just an integer value, and not a particularly big one. I just put it in a float to avoid casting.) | TITLE:
Can cout alter variables somehow?
QUESTION:
So I have a function that looks something like this: float function(){ float x = SomeValue; return x / SomeOtherValue; } At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the function looked like this: float function(){ float x = SomeValue; cout << x; return x / SomeOtherValue; } and it worked! Of course, I solved the problem altogether by using a double. But I'm curious as to why the function worked properly when I couted it. Is this typical, or could there be a bug somewhere else that I'm missing? (If it's any help, the value stored in the float is just an integer value, and not a particularly big one. I just put it in a float to avoid casting.)
ANSWER:
Welcome to the wonderful world of floating point. The answer you get will likely depend on the floating point model you compiled the code with. This happens because of the difference between the IEEE spec and the hardware the code is running on. Your CPU likely has 80 bit floating point registers that get use to hold the 32-bit float value. This means that there is far more precision while the value stays in a register than when it is forced to a memory address (also known as 'homing' the register). When you passed the value to cout the compiler had to write the floating point to memory, and this results in a lost of precision and interesting behaviour WRT overflow cases. See the MSDN documentation on VC++ floating point switches. You could try compiling with /fp:strict and seeing what happens. | [
"c++",
"floating-point",
"cout",
"cpu-registers",
"floating-point-precision"
] | 9 | 18 | 2,451 | 5 | 0 | 2008-09-08T03:02:27.683000 | 2008-09-08T03:43:10.770000 |
49,107 | 50,755 | What's the cleanest way to simulate pass-by-reference in Actionscript 3.0? | Actionscript 3.0 (and I assume Javascript and ECMAScript in general) lacks pass-by-reference for native types like ints. As a result I'm finding getting values back from a function really clunky. What's the normal pattern to work around this? For example, is there a clean way to implement swap( intA, intB ) in Actionscript? | I Believe the best you can do is pass a container object as an argument to a function and change the values of some properties in that object: function swapAB(aValuesContainer:Object):void { if (!(aValuesContainer.hasOwnProperty("a") && aValuesContainer.hasOwnProperty("b"))) throw new ArgumentError("aValuesContainer must have properties a and b");
var tempValue:int = aValuesContainer["a"]; aValuesContainer["a"] = aValuesContainer["b"]; aValuesContainer["b"] = tempValue; } var ints:Object = {a:13, b:25}; swapAB(ints); | What's the cleanest way to simulate pass-by-reference in Actionscript 3.0? Actionscript 3.0 (and I assume Javascript and ECMAScript in general) lacks pass-by-reference for native types like ints. As a result I'm finding getting values back from a function really clunky. What's the normal pattern to work around this? For example, is there a clean way to implement swap( intA, intB ) in Actionscript? | TITLE:
What's the cleanest way to simulate pass-by-reference in Actionscript 3.0?
QUESTION:
Actionscript 3.0 (and I assume Javascript and ECMAScript in general) lacks pass-by-reference for native types like ints. As a result I'm finding getting values back from a function really clunky. What's the normal pattern to work around this? For example, is there a clean way to implement swap( intA, intB ) in Actionscript?
ANSWER:
I Believe the best you can do is pass a container object as an argument to a function and change the values of some properties in that object: function swapAB(aValuesContainer:Object):void { if (!(aValuesContainer.hasOwnProperty("a") && aValuesContainer.hasOwnProperty("b"))) throw new ArgumentError("aValuesContainer must have properties a and b");
var tempValue:int = aValuesContainer["a"]; aValuesContainer["a"] = aValuesContainer["b"]; aValuesContainer["b"] = tempValue; } var ints:Object = {a:13, b:25}; swapAB(ints); | [
"actionscript-3"
] | 13 | 7 | 10,833 | 8 | 0 | 2008-09-08T03:07:35.630000 | 2008-09-08T21:38:45.817000 |
49,134 | 49,142 | What's the best .NET library for OpenID and ASP.NET MVC? | I'm looking at using OpenID for my authentication scheme and wanted to know what the best.NET library is to use for MVC specific applications? thx | .Net OpenID project is the best library to use right now that I know of. I think SO used it also. The source includes a sample ASP.NET MVC project using the library. Scott Hanselman did a post on how to use the.Net OpenID project inside of ASP.NET MVC. | What's the best .NET library for OpenID and ASP.NET MVC? I'm looking at using OpenID for my authentication scheme and wanted to know what the best.NET library is to use for MVC specific applications? thx | TITLE:
What's the best .NET library for OpenID and ASP.NET MVC?
QUESTION:
I'm looking at using OpenID for my authentication scheme and wanted to know what the best.NET library is to use for MVC specific applications? thx
ANSWER:
.Net OpenID project is the best library to use right now that I know of. I think SO used it also. The source includes a sample ASP.NET MVC project using the library. Scott Hanselman did a post on how to use the.Net OpenID project inside of ASP.NET MVC. | [
".net",
"asp.net-mvc",
"authentication",
"openid"
] | 30 | 18 | 2,508 | 4 | 0 | 2008-09-08T03:50:23.153000 | 2008-09-08T03:57:04.933000 |
49,137 | 49,148 | Calling python from a c++ program for distribution | I would like to call python script files from my c++ program. I am not sure that the people I will distribute to will have python installed. | Boost has a python interface library which could help you. Boost.Python | Calling python from a c++ program for distribution I would like to call python script files from my c++ program. I am not sure that the people I will distribute to will have python installed. | TITLE:
Calling python from a c++ program for distribution
QUESTION:
I would like to call python script files from my c++ program. I am not sure that the people I will distribute to will have python installed.
ANSWER:
Boost has a python interface library which could help you. Boost.Python | [
"c++",
"python",
"embedded-language"
] | 69 | 39 | 126,917 | 7 | 0 | 2008-09-08T03:53:39.560000 | 2008-09-08T04:01:10.447000 |
49,138 | 49,182 | Storing MD5 Hash in SQL Server | In SQL Server would a varbinary(16) be the most efficient way of storing an MD5 hash? Won't be doing anything with it except returning it in a linq query. | Based on the documentation on MSDN and my experience, binary is better, since the md5 hash does not vary in size. The size for a binary data type is n bytes, so the size of the data. The size of a varbinary data type is n bytes + 2 bytes on top of the size of the data. | Storing MD5 Hash in SQL Server In SQL Server would a varbinary(16) be the most efficient way of storing an MD5 hash? Won't be doing anything with it except returning it in a linq query. | TITLE:
Storing MD5 Hash in SQL Server
QUESTION:
In SQL Server would a varbinary(16) be the most efficient way of storing an MD5 hash? Won't be doing anything with it except returning it in a linq query.
ANSWER:
Based on the documentation on MSDN and my experience, binary is better, since the md5 hash does not vary in size. The size for a binary data type is n bytes, so the size of the data. The size of a varbinary data type is n bytes + 2 bytes on top of the size of the data. | [
"sql-server",
"md5"
] | 13 | 16 | 10,698 | 2 | 0 | 2008-09-08T03:54:15.440000 | 2008-09-08T04:56:17.287000 |
49,146 | 49,155 | How can I make an EXE file from a Python program? | I've used several modules to make EXEs for Python, but I'm not sure if I'm doing it right. How should I go about this, and why? Please base your answers on personal experience, and provide references where necessary. | Auto PY to EXE - A.py to.exe converter using a simple graphical interface built using Eel and PyInstaller in Python. py2exe is probably what you want, but it only works on Windows. PyInstaller works on Windows and Linux. Py2app works on the Mac. | How can I make an EXE file from a Python program? I've used several modules to make EXEs for Python, but I'm not sure if I'm doing it right. How should I go about this, and why? Please base your answers on personal experience, and provide references where necessary. | TITLE:
How can I make an EXE file from a Python program?
QUESTION:
I've used several modules to make EXEs for Python, but I'm not sure if I'm doing it right. How should I go about this, and why? Please base your answers on personal experience, and provide references where necessary.
ANSWER:
Auto PY to EXE - A.py to.exe converter using a simple graphical interface built using Eel and PyInstaller in Python. py2exe is probably what you want, but it only works on Windows. PyInstaller works on Windows and Linux. Py2app works on the Mac. | [
"python",
"exe",
"executable"
] | 117 | 98 | 307,511 | 7 | 0 | 2008-09-08T03:59:57.937000 | 2008-09-08T04:10:45.947000 |
49,147 | 49,153 | How do I create a MessageBox in C#? | I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a 'Hello, World!' UI Edition. I started in the Form Designer and made a button named "Click Me!" proceeded to double-click it and typed in MessageBox("Hello, World!"); I received the following error: MessageBox is a 'type' but used as a 'variable' Fair enough, it seems in C# MessageBox is an Object. I tried the following MessageBox a = new MessageBox("Hello, World!"); I received the following error: MessageBox does not contain a constructor that takes '1' arguments Now I am stumped. Please help. | MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) { //some interesting behaviour here } which I guess is a bit unwieldy but it gets the job done. See https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult for additional enum options you can use here. | How do I create a MessageBox in C#? I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a 'Hello, World!' UI Edition. I started in the Form Designer and made a button named "Click Me!" proceeded to double-click it and typed in MessageBox("Hello, World!"); I received the following error: MessageBox is a 'type' but used as a 'variable' Fair enough, it seems in C# MessageBox is an Object. I tried the following MessageBox a = new MessageBox("Hello, World!"); I received the following error: MessageBox does not contain a constructor that takes '1' arguments Now I am stumped. Please help. | TITLE:
How do I create a MessageBox in C#?
QUESTION:
I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a 'Hello, World!' UI Edition. I started in the Form Designer and made a button named "Click Me!" proceeded to double-click it and typed in MessageBox("Hello, World!"); I received the following error: MessageBox is a 'type' but used as a 'variable' Fair enough, it seems in C# MessageBox is an Object. I tried the following MessageBox a = new MessageBox("Hello, World!"); I received the following error: MessageBox does not contain a constructor that takes '1' arguments Now I am stumped. Please help.
ANSWER:
MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) { //some interesting behaviour here } which I guess is a bit unwieldy but it gets the job done. See https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult for additional enum options you can use here. | [
"c#",
".net"
] | 23 | 49 | 131,883 | 8 | 0 | 2008-09-08T04:00:54.860000 | 2008-09-08T04:08:48.633000 |
49,156 | 49,205 | Importing JavaScript in JSP tags | I have a.tag file that requires a JavaScript library (as in a.js file). Currently I am just remembering to import the.js file in every JSP that uses the tag but this is a bit cumbersome and prone to error. Is there a way to do the importing of the.js inside the JSP tag? (for caching reasons I would want the.js to be a script import) | There is no reason you cannot have a script tag in the body, even though it is preferable for it to be in the head. Just emit the script tag before you emit your tag's markup. The only thing to consider is that you do not want to include the script more than once if you use the jsp tag on the page more than once. The way to solve that is to remember that you have already included the script, by addng an attribute to the request object. | Importing JavaScript in JSP tags I have a.tag file that requires a JavaScript library (as in a.js file). Currently I am just remembering to import the.js file in every JSP that uses the tag but this is a bit cumbersome and prone to error. Is there a way to do the importing of the.js inside the JSP tag? (for caching reasons I would want the.js to be a script import) | TITLE:
Importing JavaScript in JSP tags
QUESTION:
I have a.tag file that requires a JavaScript library (as in a.js file). Currently I am just remembering to import the.js file in every JSP that uses the tag but this is a bit cumbersome and prone to error. Is there a way to do the importing of the.js inside the JSP tag? (for caching reasons I would want the.js to be a script import)
ANSWER:
There is no reason you cannot have a script tag in the body, even though it is preferable for it to be in the head. Just emit the script tag before you emit your tag's markup. The only thing to consider is that you do not want to include the script more than once if you use the jsp tag on the page more than once. The way to solve that is to remember that you have already included the script, by addng an attribute to the request object. | [
"javascript",
"java",
"jsp",
"jsp-tags"
] | 8 | 6 | 3,748 | 2 | 0 | 2008-09-08T04:11:21.467000 | 2008-09-08T05:37:56.483000 |
49,158 | 55,744 | GreaseMonkey script to auto login using HTTP authentication | I've got quite a few GreaseMonkey scripts that I wrote at my work which automatically log me into the internal sites we have here. I've managed to write a script for nearly each one of these sites except for our time sheet application, which uses HTTP authentication. Is there a way I can use GreaseMonkey to log me into this site automatically? Edit: I am aware of the store password functionality in browsers, but my scripts go a step further by checking if I'm logged into the site when it loads (by traversing HTML) and then submitting a post to the login page. This removes the step of having to load up the site, entering the login page, entering my credentials, then hitting submit | It is possible to log in using HTTP authentication by setting the "Authorization" HTTP header, with the value of this header set to the string "basic username:password", but with the "username:password" portion of the string Base 64 encoded. http://frontier.userland.com/stories/storyReader$2159 A bit of researching found that GreaseMonkey has a a function built into it where you can send GET / POST requests to the server called GM_xmlhttpRequest http://diveintogreasemonkey.org/api/gm_xmlhttprequest.html So putting it all together (and also getting this JavaScript code to convert strings into base64 I get the following http://www.webtoolkit.info/javascript-base64.html var loggedInText = document.getElementById('metanav').firstChild.firstChild.innerHTML; if (loggedInText!= "logged in as jklp") { var username = 'jklp'; var password = 'jklpPass'; var base64string = Base64.encode(username + ":" + password);
GM_xmlhttpRequest({ method: 'GET', url: 'http://foo.com/trac/login', headers: { 'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3', 'Accept': 'application/atom+xml,application/xml,text/xml', 'Authorization':'Basic ' + base64string, } }); } So when I now visit the site, it traverses the DOM and if I'm not logged in, it automagically logs me in. | GreaseMonkey script to auto login using HTTP authentication I've got quite a few GreaseMonkey scripts that I wrote at my work which automatically log me into the internal sites we have here. I've managed to write a script for nearly each one of these sites except for our time sheet application, which uses HTTP authentication. Is there a way I can use GreaseMonkey to log me into this site automatically? Edit: I am aware of the store password functionality in browsers, but my scripts go a step further by checking if I'm logged into the site when it loads (by traversing HTML) and then submitting a post to the login page. This removes the step of having to load up the site, entering the login page, entering my credentials, then hitting submit | TITLE:
GreaseMonkey script to auto login using HTTP authentication
QUESTION:
I've got quite a few GreaseMonkey scripts that I wrote at my work which automatically log me into the internal sites we have here. I've managed to write a script for nearly each one of these sites except for our time sheet application, which uses HTTP authentication. Is there a way I can use GreaseMonkey to log me into this site automatically? Edit: I am aware of the store password functionality in browsers, but my scripts go a step further by checking if I'm logged into the site when it loads (by traversing HTML) and then submitting a post to the login page. This removes the step of having to load up the site, entering the login page, entering my credentials, then hitting submit
ANSWER:
It is possible to log in using HTTP authentication by setting the "Authorization" HTTP header, with the value of this header set to the string "basic username:password", but with the "username:password" portion of the string Base 64 encoded. http://frontier.userland.com/stories/storyReader$2159 A bit of researching found that GreaseMonkey has a a function built into it where you can send GET / POST requests to the server called GM_xmlhttpRequest http://diveintogreasemonkey.org/api/gm_xmlhttprequest.html So putting it all together (and also getting this JavaScript code to convert strings into base64 I get the following http://www.webtoolkit.info/javascript-base64.html var loggedInText = document.getElementById('metanav').firstChild.firstChild.innerHTML; if (loggedInText!= "logged in as jklp") { var username = 'jklp'; var password = 'jklpPass'; var base64string = Base64.encode(username + ":" + password);
GM_xmlhttpRequest({ method: 'GET', url: 'http://foo.com/trac/login', headers: { 'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3', 'Accept': 'application/atom+xml,application/xml,text/xml', 'Authorization':'Basic ' + base64string, } }); } So when I now visit the site, it traverses the DOM and if I'm not logged in, it automagically logs me in. | [
"javascript",
"http",
"authentication",
"greasemonkey",
"http-authentication"
] | 7 | 6 | 28,017 | 4 | 0 | 2008-09-08T04:11:48.830000 | 2008-09-11T03:18:58.447000 |
49,164 | 49,169 | How do I turn a python program into an .egg file? | How do I turn a python program into an.egg file? | Setuptools is the software that creates.egg files. It's an extension of the distutils package in the standard library. The process involves creating a setup.py file, then python setup.py bdist_egg creates an.egg package. | How do I turn a python program into an .egg file? How do I turn a python program into an.egg file? | TITLE:
How do I turn a python program into an .egg file?
QUESTION:
How do I turn a python program into an.egg file?
ANSWER:
Setuptools is the software that creates.egg files. It's an extension of the distutils package in the standard library. The process involves creating a setup.py file, then python setup.py bdist_egg creates an.egg package. | [
"python",
"deployment",
"egg"
] | 21 | 15 | 9,362 | 3 | 0 | 2008-09-08T04:21:22.020000 | 2008-09-08T04:33:39.930000 |
49,166 | 49,186 | Connecting to registry remotely, and getting exceptions | I've inherited a hoary old piece of code (by hoary, I mean warty with lots of undocumented bug fixes than WTF-y) and there's one part that's giving me a bit of trouble. Here's how it connects to the remote registry to get the add/remove programs key: try { remoteKey = RegistryKey.OpenRemoteBaseKey( RegistryHive.LocalMachine, addr.Value).OpenSubKey( "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"); return 1; } catch (IOException e) { IOException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 2; } catch (UnauthorizedAccessException e) { UnauthorizedAccessException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 3; } catch (System.Security.SecurityException e) { System.Security.SecurityException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 4; } Now, I have two problems: I know why the IOException - if it's a non-Windows machine it'll throw that. The difference between UnauthorizedAccessException and SecurityException I'm not so clear on. Anyone got any ideas? This entire bit of code was designed before anyone had thought you might not use your local logon for everything. I can't work out how you do authentication for remotely connecting to the registry, anyway, and this code looks like it's only used in one case, when it can't get this information from WMI. Any help with either would be great. | John's pointer to MSDN answered what UnauthorizedAccessException is for - it only appears when you try to access a key remotely, using OpenRemoteBaseKey. We're a little wary about changing the security context on the computer - I've found a reference here about using WMI (which we're already using for the vast majority of the heavy lifting) to access the registry, so I might try that instead. | Connecting to registry remotely, and getting exceptions I've inherited a hoary old piece of code (by hoary, I mean warty with lots of undocumented bug fixes than WTF-y) and there's one part that's giving me a bit of trouble. Here's how it connects to the remote registry to get the add/remove programs key: try { remoteKey = RegistryKey.OpenRemoteBaseKey( RegistryHive.LocalMachine, addr.Value).OpenSubKey( "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"); return 1; } catch (IOException e) { IOException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 2; } catch (UnauthorizedAccessException e) { UnauthorizedAccessException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 3; } catch (System.Security.SecurityException e) { System.Security.SecurityException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 4; } Now, I have two problems: I know why the IOException - if it's a non-Windows machine it'll throw that. The difference between UnauthorizedAccessException and SecurityException I'm not so clear on. Anyone got any ideas? This entire bit of code was designed before anyone had thought you might not use your local logon for everything. I can't work out how you do authentication for remotely connecting to the registry, anyway, and this code looks like it's only used in one case, when it can't get this information from WMI. Any help with either would be great. | TITLE:
Connecting to registry remotely, and getting exceptions
QUESTION:
I've inherited a hoary old piece of code (by hoary, I mean warty with lots of undocumented bug fixes than WTF-y) and there's one part that's giving me a bit of trouble. Here's how it connects to the remote registry to get the add/remove programs key: try { remoteKey = RegistryKey.OpenRemoteBaseKey( RegistryHive.LocalMachine, addr.Value).OpenSubKey( "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"); return 1; } catch (IOException e) { IOException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 2; } catch (UnauthorizedAccessException e) { UnauthorizedAccessException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 3; } catch (System.Security.SecurityException e) { System.Security.SecurityException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 4; } Now, I have two problems: I know why the IOException - if it's a non-Windows machine it'll throw that. The difference between UnauthorizedAccessException and SecurityException I'm not so clear on. Anyone got any ideas? This entire bit of code was designed before anyone had thought you might not use your local logon for everything. I can't work out how you do authentication for remotely connecting to the registry, anyway, and this code looks like it's only used in one case, when it can't get this information from WMI. Any help with either would be great.
ANSWER:
John's pointer to MSDN answered what UnauthorizedAccessException is for - it only appears when you try to access a key remotely, using OpenRemoteBaseKey. We're a little wary about changing the security context on the computer - I've found a reference here about using WMI (which we're already using for the vast majority of the heavy lifting) to access the registry, so I might try that instead. | [
"c#",
"windows",
"exception"
] | 0 | 0 | 1,230 | 3 | 0 | 2008-09-08T04:24:37.410000 | 2008-09-08T05:00:45.670000 |
49,168 | 49,172 | How can I embed Perl inside a C++ application? | I would like to call Perl script files from my c++ program. I am not sure that the people I will distribute to will have Perl installed. Basically I'm looking for a.lib file that I can use that has an Apache like distribution license. | You can embed perl into your app. Perl Embedding by John Quillan C++ wrapper around Perl C API | How can I embed Perl inside a C++ application? I would like to call Perl script files from my c++ program. I am not sure that the people I will distribute to will have Perl installed. Basically I'm looking for a.lib file that I can use that has an Apache like distribution license. | TITLE:
How can I embed Perl inside a C++ application?
QUESTION:
I would like to call Perl script files from my c++ program. I am not sure that the people I will distribute to will have Perl installed. Basically I'm looking for a.lib file that I can use that has an Apache like distribution license.
ANSWER:
You can embed perl into your app. Perl Embedding by John Quillan C++ wrapper around Perl C API | [
"c++",
"perl"
] | 7 | 16 | 9,541 | 3 | 0 | 2008-09-08T04:29:51.033000 | 2008-09-08T04:42:23.607000 |
49,183 | 49,191 | MFC: MessageBox during a Drag-Drop | I need to display an error message on rejecting a drop in my application. I tried this in the OnDrop() but then the source application hangs until my message box is dismissed. How can I do that? | You can always call PostMessage with a private message in the WM_APP range and in the message handler show the error. That way you show the error after the drag and drop operation is really over and there is no danger of messing up anything. | MFC: MessageBox during a Drag-Drop I need to display an error message on rejecting a drop in my application. I tried this in the OnDrop() but then the source application hangs until my message box is dismissed. How can I do that? | TITLE:
MFC: MessageBox during a Drag-Drop
QUESTION:
I need to display an error message on rejecting a drop in my application. I tried this in the OnDrop() but then the source application hangs until my message box is dismissed. How can I do that?
ANSWER:
You can always call PostMessage with a private message in the WM_APP range and in the message handler show the error. That way you show the error after the drag and drop operation is really over and there is no danger of messing up anything. | [
"mfc",
"drag-and-drop"
] | 1 | 2 | 736 | 3 | 0 | 2008-09-08T04:57:32.197000 | 2008-09-08T05:11:56.093000 |
49,194 | 49,197 | ASP.NET MVC Preview 4 - Stop Url.RouteUrl() etc. using existing parameters | I have an action like this: public class News: System.Web.Mvc.Controller { public ActionResult Archive(int year) { / *** / } } With a route like this: routes.MapRoute( "News-Archive", "News.mvc/Archive/{year}", new { controller = "News", action = "Archive" } ); The URL that I am on is: News.mvc/Archive/2008 I have a form on this page like this: 2007 Submitting the form should go to News.mvc/Archive/2007 if '2007' is selected in the form. This requires the form 'action' attribute to be "News.mvc/Archive". However, if I declare a form like this: "> it renders as: Can someone please let me know what I'm missing? | You have a couple problems, I think. First, your route doesn't have a default value for "year", so the URL "/News.mvc/Archive" is actually not valid for routing purposes. Second, you're expect form values to show up as route parameters, but that's not how HTML works. If you use a plain form with a select and a submit, your URLs will end up having "?year=2007" on the end of them. This is just how GET-method forms are designed to work in HTML. So you need to come to some conclusion about what's important. If you want the user to be able to select something from the dropdown and that changes the submission URL, then you're going to have to use Javascript to achieve this (by intercepting the form submit and formulating the correct URL). If you're okay with /News.mvc/Archive?year=2007 as your URL, then you should remove the {year} designator from the route entirely. You can still leave the "int year" parameter on your action, since form values will also populate action method parameters. | ASP.NET MVC Preview 4 - Stop Url.RouteUrl() etc. using existing parameters I have an action like this: public class News: System.Web.Mvc.Controller { public ActionResult Archive(int year) { / *** / } } With a route like this: routes.MapRoute( "News-Archive", "News.mvc/Archive/{year}", new { controller = "News", action = "Archive" } ); The URL that I am on is: News.mvc/Archive/2008 I have a form on this page like this: 2007 Submitting the form should go to News.mvc/Archive/2007 if '2007' is selected in the form. This requires the form 'action' attribute to be "News.mvc/Archive". However, if I declare a form like this: "> it renders as: Can someone please let me know what I'm missing? | TITLE:
ASP.NET MVC Preview 4 - Stop Url.RouteUrl() etc. using existing parameters
QUESTION:
I have an action like this: public class News: System.Web.Mvc.Controller { public ActionResult Archive(int year) { / *** / } } With a route like this: routes.MapRoute( "News-Archive", "News.mvc/Archive/{year}", new { controller = "News", action = "Archive" } ); The URL that I am on is: News.mvc/Archive/2008 I have a form on this page like this: 2007 Submitting the form should go to News.mvc/Archive/2007 if '2007' is selected in the form. This requires the form 'action' attribute to be "News.mvc/Archive". However, if I declare a form like this: "> it renders as: Can someone please let me know what I'm missing?
ANSWER:
You have a couple problems, I think. First, your route doesn't have a default value for "year", so the URL "/News.mvc/Archive" is actually not valid for routing purposes. Second, you're expect form values to show up as route parameters, but that's not how HTML works. If you use a plain form with a select and a submit, your URLs will end up having "?year=2007" on the end of them. This is just how GET-method forms are designed to work in HTML. So you need to come to some conclusion about what's important. If you want the user to be able to select something from the dropdown and that changes the submission URL, then you're going to have to use Javascript to achieve this (by intercepting the form submit and formulating the correct URL). If you're okay with /News.mvc/Archive?year=2007 as your URL, then you should remove the {year} designator from the route entirely. You can still leave the "int year" parameter on your action, since form values will also populate action method parameters. | [
"c#",
"asp.net-mvc",
"forms",
"routes"
] | 5 | 2 | 5,550 | 3 | 0 | 2008-09-08T05:18:12.147000 | 2008-09-08T05:25:58.417000 |
49,195 | 49,202 | What language should I learn as a bridge to C (and derivatives) | The first language I learnt was PHP, but I have more recently picked up Python. As these are all 'high-level' languages, I have found them a bit difficult to pick up. I also tried to learn Objective-C but I gave up. So, what language should I learn to bridge between Python to C | It's not clear why you need a bridge language. Why don't you start working with C directly? C is a very simple language itself. I think that hardest part for C learner is pointers and everything else related to memory management. Also C lang is oriented on structured programming, so you will need to learn how to implement data structures and algorithms without OOP goodness. Actually, your question is pretty hard, usually people go from low level langs to high level and I can understand frustration of those who goes in other direction. | What language should I learn as a bridge to C (and derivatives) The first language I learnt was PHP, but I have more recently picked up Python. As these are all 'high-level' languages, I have found them a bit difficult to pick up. I also tried to learn Objective-C but I gave up. So, what language should I learn to bridge between Python to C | TITLE:
What language should I learn as a bridge to C (and derivatives)
QUESTION:
The first language I learnt was PHP, but I have more recently picked up Python. As these are all 'high-level' languages, I have found them a bit difficult to pick up. I also tried to learn Objective-C but I gave up. So, what language should I learn to bridge between Python to C
ANSWER:
It's not clear why you need a bridge language. Why don't you start working with C directly? C is a very simple language itself. I think that hardest part for C learner is pointers and everything else related to memory management. Also C lang is oriented on structured programming, so you will need to learn how to implement data structures and algorithms without OOP goodness. Actually, your question is pretty hard, usually people go from low level langs to high level and I can understand frustration of those who goes in other direction. | [
"python",
"c"
] | 4 | 15 | 919 | 14 | 0 | 2008-09-08T05:23:35.957000 | 2008-09-08T05:34:02.920000 |
49,196 | 49,198 | Storing third-party libraries in source control | Should libraries that the application relies on be stored in source control? One part of me says it should and another part say's no. It feels wrong to add a 20mb library that dwarfs the entire app just because you rely on a couple of functions from it (albeit rather heavily). Should you just store the jar/dll or maybe even the distributed zip/tar of the project? What do other people do? | store everything you will need to build the project 10 years from now.I store the entire zip distribution of any library, just in case Edit for 2017: This answer did not age well:-). If you are still using something old like ant or make, the above still applies. If you use something more modern like maven or graddle (or Nuget on.net for example), with dependency management, you should be running a dependency management server, in addition to your version control server. As long as you have good backups of both, and your dependency management server does not delete old dependencies, you should be ok. For an example of a dependency management server, see for example Sonatype Nexus or JFrog Artifcatory, among many others. | Storing third-party libraries in source control Should libraries that the application relies on be stored in source control? One part of me says it should and another part say's no. It feels wrong to add a 20mb library that dwarfs the entire app just because you rely on a couple of functions from it (albeit rather heavily). Should you just store the jar/dll or maybe even the distributed zip/tar of the project? What do other people do? | TITLE:
Storing third-party libraries in source control
QUESTION:
Should libraries that the application relies on be stored in source control? One part of me says it should and another part say's no. It feels wrong to add a 20mb library that dwarfs the entire app just because you rely on a couple of functions from it (albeit rather heavily). Should you just store the jar/dll or maybe even the distributed zip/tar of the project? What do other people do?
ANSWER:
store everything you will need to build the project 10 years from now.I store the entire zip distribution of any library, just in case Edit for 2017: This answer did not age well:-). If you are still using something old like ant or make, the above still applies. If you use something more modern like maven or graddle (or Nuget on.net for example), with dependency management, you should be running a dependency management server, in addition to your version control server. As long as you have good backups of both, and your dependency management server does not delete old dependencies, you should be ok. For an example of a dependency management server, see for example Sonatype Nexus or JFrog Artifcatory, among many others. | [
"version-control"
] | 87 | 53 | 21,351 | 17 | 0 | 2008-09-08T05:25:01.367000 | 2008-09-08T05:28:00.050000 |
49,211 | 345,696 | How can I use a key blob generated from Win32 CryptoAPI in my .NET application? | I have an existing application that is written in C++ for Windows. This application uses the Win32 CryptoAPI to generate a TripleDES session key for encrypting/decrypting data. We're using the exponent of one trick to export the session key out as a blob, which allows the blob to be stored somewhere in a decrypted format. The question is how can we use this in our.NET application (C#). The framework encapsulates/wraps much of what the CryptoAPI is doing. Part of the problem is the CryptAPI states that the TripleDES algorithm for the Microsoft Enhanced Cryptographic Provider is 168 bits (3 keys of 56 bits). However, the.NET framework states their keys are 192 bits (3 keys of 64 bits). Apparently, the 3 extra bytes in the.NET framework is for parity? Anyway, we need to read the key portion out of the blob and somehow be able to use that in our.NET application. Currently we are not getting the expected results when attempting to use the key in.NET. The decryption is failing miserably. Any help would be greatly appreciated. Update: I've been working on ways to resolve this and have come up with a solution that I will post in time. However, still would appreciate any feedback from others. | Intro I'm Finally getting around to posting the solution. I hope it provides some help to others out there that might be doing similar type things. There really isn't much reference to doing this elsewhere. Prerequisites In order for a lot of this to make sense it's necessary to read the exponent of one trick, which allows you to export a session key out to a blob (a well known byte structure). One can then do what they wish with this byte stream, but it holds the all important key. MSDN Documentation is Confusing In this particular example, I'm using the Microsoft Enhanced Cryptographic Provider, with the Triple DES ( CALG_3DES ) algorithm. The first thing that threw me for a loop was the fact that the key length is listed at 168 bits, with a block length of 64 bits. How can the key length be 168? Three keys of 56 bits? What happens to the other byte? So with that information I started to read elsewhere how the last byte is really parity and for whatever reason CryptoAPI strips that off. Is that really the case? Seems kind of crazy that they would do that, but OK. Consumption of Key in.NET Using the TripleDESCryptoServiceProvider, I noticed the remarks in the docs indicated that: This algorithm supports key lengths from 128 bits to 192 bits in increments of 64 bits. So if CryptoAPI has key lengths of 168, how will I get that into.NET which supports only supports multiples of 64? Therefore, the.NET side of the API takes parity into account, where the CryptoAPI does not. As one could imagine... confused was I. So with all of this, I'm trying to figure out how to reconstruct the key on the.NET side with the proper parity information. Doable, but not very fun... let's just leave it at that. Once I got all of this in place, everything ended up failing with a CAPITAL F. Still with me? Good, because I just fell off my horse again. Light Bulbs and Fireworks Low and behold, as I'm scraping MSDN for every last bit of information I find a conflicting piece in the Win32 CryptExportKey function. Low and behold I find this piece of invaluble information: For any of the DES key permutations that use a PLAINTEXTKEYBLOB, only the full key size, including parity bit, may be exported. The following key sizes are supported. Algorithm Supported key size CALG_DES 64 bits CALG_3DES_112 128 bits CALG_3DES 192 bits So it does export a key that is a multiple of 64 bits! Woohoo! Now to fix the code on the.NET side..NET Import Code Tweak The byte order is important to keep in mind when importing a byte stream that contains a key that was exported as a blob from the CryptoAPI. The two API's do not use the same byte order, therefore, as @nic-strong indicates, reversing the byte array is essential before actually trying to use the key. Other than that, things work as expected. Simply solved: Array.Reverse( keyByteArray ); Conclusion I hope this helps somebody out there. I spent way too much time trying to track this down. Leave any comments if you have further questions and I can attempt to help fill in any details. Happy Crypto! | How can I use a key blob generated from Win32 CryptoAPI in my .NET application? I have an existing application that is written in C++ for Windows. This application uses the Win32 CryptoAPI to generate a TripleDES session key for encrypting/decrypting data. We're using the exponent of one trick to export the session key out as a blob, which allows the blob to be stored somewhere in a decrypted format. The question is how can we use this in our.NET application (C#). The framework encapsulates/wraps much of what the CryptoAPI is doing. Part of the problem is the CryptAPI states that the TripleDES algorithm for the Microsoft Enhanced Cryptographic Provider is 168 bits (3 keys of 56 bits). However, the.NET framework states their keys are 192 bits (3 keys of 64 bits). Apparently, the 3 extra bytes in the.NET framework is for parity? Anyway, we need to read the key portion out of the blob and somehow be able to use that in our.NET application. Currently we are not getting the expected results when attempting to use the key in.NET. The decryption is failing miserably. Any help would be greatly appreciated. Update: I've been working on ways to resolve this and have come up with a solution that I will post in time. However, still would appreciate any feedback from others. | TITLE:
How can I use a key blob generated from Win32 CryptoAPI in my .NET application?
QUESTION:
I have an existing application that is written in C++ for Windows. This application uses the Win32 CryptoAPI to generate a TripleDES session key for encrypting/decrypting data. We're using the exponent of one trick to export the session key out as a blob, which allows the blob to be stored somewhere in a decrypted format. The question is how can we use this in our.NET application (C#). The framework encapsulates/wraps much of what the CryptoAPI is doing. Part of the problem is the CryptAPI states that the TripleDES algorithm for the Microsoft Enhanced Cryptographic Provider is 168 bits (3 keys of 56 bits). However, the.NET framework states their keys are 192 bits (3 keys of 64 bits). Apparently, the 3 extra bytes in the.NET framework is for parity? Anyway, we need to read the key portion out of the blob and somehow be able to use that in our.NET application. Currently we are not getting the expected results when attempting to use the key in.NET. The decryption is failing miserably. Any help would be greatly appreciated. Update: I've been working on ways to resolve this and have come up with a solution that I will post in time. However, still would appreciate any feedback from others.
ANSWER:
Intro I'm Finally getting around to posting the solution. I hope it provides some help to others out there that might be doing similar type things. There really isn't much reference to doing this elsewhere. Prerequisites In order for a lot of this to make sense it's necessary to read the exponent of one trick, which allows you to export a session key out to a blob (a well known byte structure). One can then do what they wish with this byte stream, but it holds the all important key. MSDN Documentation is Confusing In this particular example, I'm using the Microsoft Enhanced Cryptographic Provider, with the Triple DES ( CALG_3DES ) algorithm. The first thing that threw me for a loop was the fact that the key length is listed at 168 bits, with a block length of 64 bits. How can the key length be 168? Three keys of 56 bits? What happens to the other byte? So with that information I started to read elsewhere how the last byte is really parity and for whatever reason CryptoAPI strips that off. Is that really the case? Seems kind of crazy that they would do that, but OK. Consumption of Key in.NET Using the TripleDESCryptoServiceProvider, I noticed the remarks in the docs indicated that: This algorithm supports key lengths from 128 bits to 192 bits in increments of 64 bits. So if CryptoAPI has key lengths of 168, how will I get that into.NET which supports only supports multiples of 64? Therefore, the.NET side of the API takes parity into account, where the CryptoAPI does not. As one could imagine... confused was I. So with all of this, I'm trying to figure out how to reconstruct the key on the.NET side with the proper parity information. Doable, but not very fun... let's just leave it at that. Once I got all of this in place, everything ended up failing with a CAPITAL F. Still with me? Good, because I just fell off my horse again. Light Bulbs and Fireworks Low and behold, as I'm scraping MSDN for every last bit of information I find a conflicting piece in the Win32 CryptExportKey function. Low and behold I find this piece of invaluble information: For any of the DES key permutations that use a PLAINTEXTKEYBLOB, only the full key size, including parity bit, may be exported. The following key sizes are supported. Algorithm Supported key size CALG_DES 64 bits CALG_3DES_112 128 bits CALG_3DES 192 bits So it does export a key that is a multiple of 64 bits! Woohoo! Now to fix the code on the.NET side..NET Import Code Tweak The byte order is important to keep in mind when importing a byte stream that contains a key that was exported as a blob from the CryptoAPI. The two API's do not use the same byte order, therefore, as @nic-strong indicates, reversing the byte array is essential before actually trying to use the key. Other than that, things work as expected. Simply solved: Array.Reverse( keyByteArray ); Conclusion I hope this helps somebody out there. I spent way too much time trying to track this down. Leave any comments if you have further questions and I can attempt to help fill in any details. Happy Crypto! | [
".net",
"c++",
"encryption",
"cryptography",
"cryptoapi"
] | 2 | 5 | 4,119 | 2 | 0 | 2008-09-08T05:42:23.290000 | 2008-12-06T01:26:28.080000 |
49,214 | 49,218 | Populating a list of integers in .NET | I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously: List iList = new List (); for (int i = 1; i <= x; i++) { iList.Add(i); } This seems dumb, surely there's a more elegant way to do this, something like the PHP range method | If you're using.Net 3.5, Enumerable.Range is what you need. Generates a sequence of integral numbers within a specified range. | Populating a list of integers in .NET I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously: List iList = new List (); for (int i = 1; i <= x; i++) { iList.Add(i); } This seems dumb, surely there's a more elegant way to do this, something like the PHP range method | TITLE:
Populating a list of integers in .NET
QUESTION:
I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously: List iList = new List (); for (int i = 1; i <= x; i++) { iList.Add(i); } This seems dumb, surely there's a more elegant way to do this, something like the PHP range method
ANSWER:
If you're using.Net 3.5, Enumerable.Range is what you need. Generates a sequence of integral numbers within a specified range. | [
"c#",
".net",
"list",
"integer"
] | 88 | 102 | 50,137 | 4 | 0 | 2008-09-08T05:45:34 | 2008-09-08T05:49:40.043000 |
49,220 | 49,221 | How can I map a list of strings to my entity using NHibernate? | I've got two tables in my database: Articles and Tags The Tags tables consist of ArticleID (foreign key) and a Tag (varchar). Now I need to map an articles tags into a readonly collection on Article entity, either using IList Tags or ReadOnlyCollection Tags. I've consulted the NHibernate reference material, but I can't seem to figure when to use Set, Bag and the other Nhibernate collections. I've seen examples using the ISet collection, but I really don't like to tie my entity classes to a NHibernate type. How can I do the mapping in NHibernate? edit: I ended up using a instead, as it doesn't require an index: | The type of collection to use in your mapping depends on how you want to represent the collection in code. The settings map like so: The maps directly to an IList. The maps directly to an IDictionary. The maps to an IList. A does not completely comply with the IList interface because the Add() method is not guaranteed to return the correct index. An object can be added to a without initializing the IList. Make sure to either hide the IList from the consumers of your API or make it well documented. The maps to an Iesi.Collections.ISet. That interface is part of the Iesi.Collections assembly distributed with NHibernate. so if you want an IList to be returned, then you would use the mapping. In your case, I'd probably map using the mapping. | How can I map a list of strings to my entity using NHibernate? I've got two tables in my database: Articles and Tags The Tags tables consist of ArticleID (foreign key) and a Tag (varchar). Now I need to map an articles tags into a readonly collection on Article entity, either using IList Tags or ReadOnlyCollection Tags. I've consulted the NHibernate reference material, but I can't seem to figure when to use Set, Bag and the other Nhibernate collections. I've seen examples using the ISet collection, but I really don't like to tie my entity classes to a NHibernate type. How can I do the mapping in NHibernate? edit: I ended up using a instead, as it doesn't require an index: | TITLE:
How can I map a list of strings to my entity using NHibernate?
QUESTION:
I've got two tables in my database: Articles and Tags The Tags tables consist of ArticleID (foreign key) and a Tag (varchar). Now I need to map an articles tags into a readonly collection on Article entity, either using IList Tags or ReadOnlyCollection Tags. I've consulted the NHibernate reference material, but I can't seem to figure when to use Set, Bag and the other Nhibernate collections. I've seen examples using the ISet collection, but I really don't like to tie my entity classes to a NHibernate type. How can I do the mapping in NHibernate? edit: I ended up using a instead, as it doesn't require an index:
ANSWER:
The type of collection to use in your mapping depends on how you want to represent the collection in code. The settings map like so: The maps directly to an IList. The maps directly to an IDictionary. The maps to an IList. A does not completely comply with the IList interface because the Add() method is not guaranteed to return the correct index. An object can be added to a without initializing the IList. Make sure to either hide the IList from the consumers of your API or make it well documented. The maps to an Iesi.Collections.ISet. That interface is part of the Iesi.Collections assembly distributed with NHibernate. so if you want an IList to be returned, then you would use the mapping. In your case, I'd probably map using the mapping. | [
"nhibernate"
] | 2 | 5 | 2,501 | 1 | 0 | 2008-09-08T05:51:35.483000 | 2008-09-08T05:57:37 |
49,226 | 49,256 | 128 bit data encryption using Java | I need to store some sensitive data by encrypting it with atleast 128 bit key. I investigated into javax.crypto package and found that there are certain Cipher names, like PBEWithMD5AndDES or PBEWithSHA1AndDESede which provides encryption upto 56 bit and 80 bit ( http://en.wikipedia.org/wiki/DESede ). I referred other guys posts but those are mainly using RSA and in my understanding RSA is generally suitable for encrypting the communication data (with private-public key pair). My need is different, I just want to store the data and retrieve it back by decrypting it. Therefore I don't need any private-public key pairs. Please let me know if you have any idea about this. | Use Advanced Encryption Standard (AES). It supports Key lengths of 128, 192, or 256 bits. The algorithm is simple. The Sun Java website has a section explaining how to do AES encryption in Java. From Wikipedia...... the Advanced Encryption Standard (AES), also known as Rijndael, is a block cipher adopted as an encryption standard by the U.S. government. It has been analyzed extensively and is now used worldwide, as was the case with its predecessor, the Data Encryption Standard (DES)... So as a rule of thumb you are not supposed to use DES or its variants because it is being phased out. As of now, it is better to use AES. There are other options like Twofish, Blowfish etc also. Note that Twofish can be considered as an advanced version of Blowfish. | 128 bit data encryption using Java I need to store some sensitive data by encrypting it with atleast 128 bit key. I investigated into javax.crypto package and found that there are certain Cipher names, like PBEWithMD5AndDES or PBEWithSHA1AndDESede which provides encryption upto 56 bit and 80 bit ( http://en.wikipedia.org/wiki/DESede ). I referred other guys posts but those are mainly using RSA and in my understanding RSA is generally suitable for encrypting the communication data (with private-public key pair). My need is different, I just want to store the data and retrieve it back by decrypting it. Therefore I don't need any private-public key pairs. Please let me know if you have any idea about this. | TITLE:
128 bit data encryption using Java
QUESTION:
I need to store some sensitive data by encrypting it with atleast 128 bit key. I investigated into javax.crypto package and found that there are certain Cipher names, like PBEWithMD5AndDES or PBEWithSHA1AndDESede which provides encryption upto 56 bit and 80 bit ( http://en.wikipedia.org/wiki/DESede ). I referred other guys posts but those are mainly using RSA and in my understanding RSA is generally suitable for encrypting the communication data (with private-public key pair). My need is different, I just want to store the data and retrieve it back by decrypting it. Therefore I don't need any private-public key pairs. Please let me know if you have any idea about this.
ANSWER:
Use Advanced Encryption Standard (AES). It supports Key lengths of 128, 192, or 256 bits. The algorithm is simple. The Sun Java website has a section explaining how to do AES encryption in Java. From Wikipedia...... the Advanced Encryption Standard (AES), also known as Rijndael, is a block cipher adopted as an encryption standard by the U.S. government. It has been analyzed extensively and is now used worldwide, as was the case with its predecessor, the Data Encryption Standard (DES)... So as a rule of thumb you are not supposed to use DES or its variants because it is being phased out. As of now, it is better to use AES. There are other options like Twofish, Blowfish etc also. Note that Twofish can be considered as an advanced version of Blowfish. | [
"java",
"cryptography"
] | 5 | 8 | 9,758 | 6 | 0 | 2008-09-08T06:13:19.863000 | 2008-09-08T07:01:45.567000 |
49,251 | 49,531 | Crash reporting in C for Linux | Following this question: Good crash reporting library in c# Is there any library like CrashRpt.dll that does the same on Linux? That is, generate a failure report including a core dump and any necessary environment and notify the developer about it? Edit: This seems to be a duplicate of this question | See Getting stack traces on Unix systems, automatically on Stack Overflow. | Crash reporting in C for Linux Following this question: Good crash reporting library in c# Is there any library like CrashRpt.dll that does the same on Linux? That is, generate a failure report including a core dump and any necessary environment and notify the developer about it? Edit: This seems to be a duplicate of this question | TITLE:
Crash reporting in C for Linux
QUESTION:
Following this question: Good crash reporting library in c# Is there any library like CrashRpt.dll that does the same on Linux? That is, generate a failure report including a core dump and any necessary environment and notify the developer about it? Edit: This seems to be a duplicate of this question
ANSWER:
See Getting stack traces on Unix systems, automatically on Stack Overflow. | [
"c",
"linux",
"crashrpt"
] | 4 | 3 | 3,260 | 7 | 0 | 2008-09-08T06:53:06.040000 | 2008-09-08T11:51:17.257000 |
49,252 | 49,255 | ruby method names | For a project I am working on in ruby I am overriding the method_missing method so that I can set variables using a method call like this, similar to setting variables in an ActiveRecord object: Object.variable_name= 'new value' However, after implementing this I found out that many of the variable names have periods (.) in them. I have found this workaround: Object.send('variable.name=', 'new value') However, I am wondering is there a way to escape the period so that I can use Object.variable.name= 'new value' | Don't do it! Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros: attr_writer:bar attr_reader:baz attr_accessor:foo Okay, now that you have been warned, here's how to do it. Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go. class SillySetter def initialize path=nil @path = path end
def method_missing name,value=nil new_path = @path? "#{@path}.#{name}": name if name.to_s[-1] ==?= puts "setting #{new_path} #{value}" else return self.class.new(path=new_path) end end end
s = SillySetter.new s.foo = 5 # -> setting foo= 5 s.foo.bar.baz = 4 # -> setting foo.bar.baz= 4 I didn't want to encourage ruby sillyness, but I just couldn't help myself! | ruby method names For a project I am working on in ruby I am overriding the method_missing method so that I can set variables using a method call like this, similar to setting variables in an ActiveRecord object: Object.variable_name= 'new value' However, after implementing this I found out that many of the variable names have periods (.) in them. I have found this workaround: Object.send('variable.name=', 'new value') However, I am wondering is there a way to escape the period so that I can use Object.variable.name= 'new value' | TITLE:
ruby method names
QUESTION:
For a project I am working on in ruby I am overriding the method_missing method so that I can set variables using a method call like this, similar to setting variables in an ActiveRecord object: Object.variable_name= 'new value' However, after implementing this I found out that many of the variable names have periods (.) in them. I have found this workaround: Object.send('variable.name=', 'new value') However, I am wondering is there a way to escape the period so that I can use Object.variable.name= 'new value'
ANSWER:
Don't do it! Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros: attr_writer:bar attr_reader:baz attr_accessor:foo Okay, now that you have been warned, here's how to do it. Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go. class SillySetter def initialize path=nil @path = path end
def method_missing name,value=nil new_path = @path? "#{@path}.#{name}": name if name.to_s[-1] ==?= puts "setting #{new_path} #{value}" else return self.class.new(path=new_path) end end end
s = SillySetter.new s.foo = 5 # -> setting foo= 5 s.foo.bar.baz = 4 # -> setting foo.bar.baz= 4 I didn't want to encourage ruby sillyness, but I just couldn't help myself! | [
"ruby"
] | 2 | 9 | 2,984 | 3 | 0 | 2008-09-08T06:54:26.723000 | 2008-09-08T06:58:22.673000 |
49,258 | 49,266 | What is the cleanest way to direct wxWidgets to always use wxFileConfig? | I am writing my first serious wxWidgets program. I'd like to use the wxConfig facility to make the program's user options persistent. However I don't want wxConfigBase to automatically use the Windows registry. Even though I'm initially targeting Windows, I'd prefer to use a configuration (eg.ini) file. Does anyone know a clean and simple way of doing this? Thanks. | According to the source of wx/config.h file, all you need is to define the wxUSE_CONFIG_NATIVE symbol to 0 in your project and then it will always use wxFileConfig. | What is the cleanest way to direct wxWidgets to always use wxFileConfig? I am writing my first serious wxWidgets program. I'd like to use the wxConfig facility to make the program's user options persistent. However I don't want wxConfigBase to automatically use the Windows registry. Even though I'm initially targeting Windows, I'd prefer to use a configuration (eg.ini) file. Does anyone know a clean and simple way of doing this? Thanks. | TITLE:
What is the cleanest way to direct wxWidgets to always use wxFileConfig?
QUESTION:
I am writing my first serious wxWidgets program. I'd like to use the wxConfig facility to make the program's user options persistent. However I don't want wxConfigBase to automatically use the Windows registry. Even though I'm initially targeting Windows, I'd prefer to use a configuration (eg.ini) file. Does anyone know a clean and simple way of doing this? Thanks.
ANSWER:
According to the source of wx/config.h file, all you need is to define the wxUSE_CONFIG_NATIVE symbol to 0 in your project and then it will always use wxFileConfig. | [
"c++",
"wxwidgets"
] | 2 | 2 | 1,256 | 2 | 0 | 2008-09-08T07:08:26.643000 | 2008-09-08T07:27:38.280000 |
49,260 | 49,265 | Deploying a project using LINQ to SQL | I am working on a winforms application using LINQ to SQL - and am building the app using a SQL Express instance on my workstation. The final installation of the project will be on a proper SQL Server 2005. The database has the same name, and all tables are identical but the hostname is different. The only way I have found to make my app work from one machine to the next is to re-open the code in Visual Studio, delete all of the objects referring to the SQL express instance from my.mdbl, save the project, connect to the other server, drag all of the references back on, and rebuild the application for release once more. an answer here suggested that one can simply modify the app.config/web.config file - whih would work for asp.net, but this is a winforms application. What's the correct way of making LINQ to SQL apps use a new database without having to re-open the app in visual studio? | If I understand your problem correctly, you simply change the database's connection string in your app.config / web.config. Edit, post clarification: You have the connection strings stored somewhere. They might be in the app.config of your server. Still, you get them from somewhere and that somewhere may be in an app.config. Use that then:) | Deploying a project using LINQ to SQL I am working on a winforms application using LINQ to SQL - and am building the app using a SQL Express instance on my workstation. The final installation of the project will be on a proper SQL Server 2005. The database has the same name, and all tables are identical but the hostname is different. The only way I have found to make my app work from one machine to the next is to re-open the code in Visual Studio, delete all of the objects referring to the SQL express instance from my.mdbl, save the project, connect to the other server, drag all of the references back on, and rebuild the application for release once more. an answer here suggested that one can simply modify the app.config/web.config file - whih would work for asp.net, but this is a winforms application. What's the correct way of making LINQ to SQL apps use a new database without having to re-open the app in visual studio? | TITLE:
Deploying a project using LINQ to SQL
QUESTION:
I am working on a winforms application using LINQ to SQL - and am building the app using a SQL Express instance on my workstation. The final installation of the project will be on a proper SQL Server 2005. The database has the same name, and all tables are identical but the hostname is different. The only way I have found to make my app work from one machine to the next is to re-open the code in Visual Studio, delete all of the objects referring to the SQL express instance from my.mdbl, save the project, connect to the other server, drag all of the references back on, and rebuild the application for release once more. an answer here suggested that one can simply modify the app.config/web.config file - whih would work for asp.net, but this is a winforms application. What's the correct way of making LINQ to SQL apps use a new database without having to re-open the app in visual studio?
ANSWER:
If I understand your problem correctly, you simply change the database's connection string in your app.config / web.config. Edit, post clarification: You have the connection strings stored somewhere. They might be in the app.config of your server. Still, you get them from somewhere and that somewhere may be in an app.config. Use that then:) | [
"linq-to-sql",
"deployment"
] | 1 | 1 | 2,136 | 4 | 0 | 2008-09-08T07:15:17.217000 | 2008-09-08T07:26:04.667000 |
49,263 | 50,110 | Approximate string matching algorithms | Here at work, we often need to find a string from the list of strings that is the closest match to some other input string. Currently, we are using Needleman-Wunsch algorithm. The algorithm often returns a lot of false-positives (if we set the minimum-score too low), sometimes it doesn't find a match when it should (when the minimum-score is too high) and, most of the times, we need to check the results by hand. We thought we should try other alternatives. Do you have any experiences with the algorithms? Do you know how the algorithms compare to one another? I'd really appreciate some advice. PS: We're coding in C#, but you shouldn't care about it - I'm asking about the algorithms in general. Oh, I'm sorry I forgot to mention that. No, we're not using it to match duplicate data. We have a list of strings that we are looking for - we call it search-list. And then we need to process texts from various sources (like RSS feeds, web-sites, forums, etc.) - we extract parts of those texts (there are entire sets of rules for that, but that's irrelevant) and we need to match those against the search-list. If the string matches one of the strings in search-list - we need to do some further processing of the thing (which is also irrelevant). We can not perform the normal comparison, because the strings extracted from the outside sources, most of the times, include some extra words etc. Anyway, it's not for duplicate detection. | OK, Needleman-Wunsch(NW) is a classic end-to-end ("global") aligner from the bioinformatics literature. It was long ago available as "align" and "align0" in the FASTA package. The difference was that the "0" version wasn't as biased about avoiding end-gapping, which often allowed favoring high-quality internal matches easier. Smith-Waterman, I suspect you're aware, is a local aligner and is the original basis of BLAST. FASTA had it's own local aligner as well that was slightly different. All of these are essentially heuristic methods for estimating Levenshtein distance relevant to a scoring metric for individual character pairs (in bioinformatics, often given by Dayhoff/"PAM", Henikoff&Henikoff, or other matrices and usually replaced with something simpler and more reasonably reflective of replacements in linguistic word morphology when applied to natural language). Let's not be precious about labels: Levenshtein distance, as referenced in practice at least, is basically edit distance and you have to estimate it because it's not feasible to compute it generally, and it's expensive to compute exactly even in interesting special cases: the water gets deep quick there, and thus we have heuristic methods of long and good repute. Now as to your own problem: several years ago, I had to check the accuracy of short DNA reads against reference sequence known to be correct and I came up with something I called "anchored alignments". The idea is to take your reference string set and "digest" it by finding all locations where a given N-character substring occurs. Choose N so that the table you build is not too big but also so that substrings of length N are not too common. For small alphabets like DNA bases, it's possible to come up with a perfect hash on strings of N characters and make a table and chain the matches in a linked list from each bin. The list entries must identify the sequence and start position of the substring that maps to the bin in whose list they occur. These are "anchors" in the list of strings to be searched at which an NW alignment is likely to be useful. When processing a query string, you take the N characters starting at some offset K in the query string, hash them, look up their bin, and if the list for that bin is nonempty then you go through all the list records and perform alignments between the query string and the search string referenced in the record. When doing these alignments, you line up the query string and the search string at the anchor and extract a substring of the search string that is the same length as the query string and which contains that anchor at the same offset, K. If you choose a long enough anchor length N, and a reasonable set of values of offset K (they can be spread across the query string or be restricted to low offsets) you should get a subset of possible alignments and often will get clearer winners. Typically you will want to use the less end-biased align0-like NW aligner. This method tries to boost NW a bit by restricting it's input and this has a performance gain because you do less alignments and they are more often between similar sequences. Another good thing to do with your NW aligner is to allow it to give up after some amount or length of gapping occurs to cut costs, especially if you know you're not going to see or be interested in middling-quality matches. Finally, this method was used on a system with small alphabets, with K restricted to the first 100 or so positions in the query string and with search strings much larger than the queries (the DNA reads were around 1000 bases and the search strings were on the order of 10000, so I was looking for approximate substring matches justified by an estimate of edit distance specifically). Adapting this methodology to natural language will require some careful thought: you lose on alphabet size but you gain if your query strings and search strings are of similar length. Either way, allowing more than one anchor from different ends of the query string to be used simultaneously might be helpful in further filtering data fed to NW. If you do this, be prepared to possibly send overlapping strings each containing one of the two anchors to the aligner and then reconcile the alignments... or possibly further modify NW to emphasize keeping your anchors mostly intact during an alignment using penalty modification during the algorithm's execution. Hope this is helpful or at least interesting. | Approximate string matching algorithms Here at work, we often need to find a string from the list of strings that is the closest match to some other input string. Currently, we are using Needleman-Wunsch algorithm. The algorithm often returns a lot of false-positives (if we set the minimum-score too low), sometimes it doesn't find a match when it should (when the minimum-score is too high) and, most of the times, we need to check the results by hand. We thought we should try other alternatives. Do you have any experiences with the algorithms? Do you know how the algorithms compare to one another? I'd really appreciate some advice. PS: We're coding in C#, but you shouldn't care about it - I'm asking about the algorithms in general. Oh, I'm sorry I forgot to mention that. No, we're not using it to match duplicate data. We have a list of strings that we are looking for - we call it search-list. And then we need to process texts from various sources (like RSS feeds, web-sites, forums, etc.) - we extract parts of those texts (there are entire sets of rules for that, but that's irrelevant) and we need to match those against the search-list. If the string matches one of the strings in search-list - we need to do some further processing of the thing (which is also irrelevant). We can not perform the normal comparison, because the strings extracted from the outside sources, most of the times, include some extra words etc. Anyway, it's not for duplicate detection. | TITLE:
Approximate string matching algorithms
QUESTION:
Here at work, we often need to find a string from the list of strings that is the closest match to some other input string. Currently, we are using Needleman-Wunsch algorithm. The algorithm often returns a lot of false-positives (if we set the minimum-score too low), sometimes it doesn't find a match when it should (when the minimum-score is too high) and, most of the times, we need to check the results by hand. We thought we should try other alternatives. Do you have any experiences with the algorithms? Do you know how the algorithms compare to one another? I'd really appreciate some advice. PS: We're coding in C#, but you shouldn't care about it - I'm asking about the algorithms in general. Oh, I'm sorry I forgot to mention that. No, we're not using it to match duplicate data. We have a list of strings that we are looking for - we call it search-list. And then we need to process texts from various sources (like RSS feeds, web-sites, forums, etc.) - we extract parts of those texts (there are entire sets of rules for that, but that's irrelevant) and we need to match those against the search-list. If the string matches one of the strings in search-list - we need to do some further processing of the thing (which is also irrelevant). We can not perform the normal comparison, because the strings extracted from the outside sources, most of the times, include some extra words etc. Anyway, it's not for duplicate detection.
ANSWER:
OK, Needleman-Wunsch(NW) is a classic end-to-end ("global") aligner from the bioinformatics literature. It was long ago available as "align" and "align0" in the FASTA package. The difference was that the "0" version wasn't as biased about avoiding end-gapping, which often allowed favoring high-quality internal matches easier. Smith-Waterman, I suspect you're aware, is a local aligner and is the original basis of BLAST. FASTA had it's own local aligner as well that was slightly different. All of these are essentially heuristic methods for estimating Levenshtein distance relevant to a scoring metric for individual character pairs (in bioinformatics, often given by Dayhoff/"PAM", Henikoff&Henikoff, or other matrices and usually replaced with something simpler and more reasonably reflective of replacements in linguistic word morphology when applied to natural language). Let's not be precious about labels: Levenshtein distance, as referenced in practice at least, is basically edit distance and you have to estimate it because it's not feasible to compute it generally, and it's expensive to compute exactly even in interesting special cases: the water gets deep quick there, and thus we have heuristic methods of long and good repute. Now as to your own problem: several years ago, I had to check the accuracy of short DNA reads against reference sequence known to be correct and I came up with something I called "anchored alignments". The idea is to take your reference string set and "digest" it by finding all locations where a given N-character substring occurs. Choose N so that the table you build is not too big but also so that substrings of length N are not too common. For small alphabets like DNA bases, it's possible to come up with a perfect hash on strings of N characters and make a table and chain the matches in a linked list from each bin. The list entries must identify the sequence and start position of the substring that maps to the bin in whose list they occur. These are "anchors" in the list of strings to be searched at which an NW alignment is likely to be useful. When processing a query string, you take the N characters starting at some offset K in the query string, hash them, look up their bin, and if the list for that bin is nonempty then you go through all the list records and perform alignments between the query string and the search string referenced in the record. When doing these alignments, you line up the query string and the search string at the anchor and extract a substring of the search string that is the same length as the query string and which contains that anchor at the same offset, K. If you choose a long enough anchor length N, and a reasonable set of values of offset K (they can be spread across the query string or be restricted to low offsets) you should get a subset of possible alignments and often will get clearer winners. Typically you will want to use the less end-biased align0-like NW aligner. This method tries to boost NW a bit by restricting it's input and this has a performance gain because you do less alignments and they are more often between similar sequences. Another good thing to do with your NW aligner is to allow it to give up after some amount or length of gapping occurs to cut costs, especially if you know you're not going to see or be interested in middling-quality matches. Finally, this method was used on a system with small alphabets, with K restricted to the first 100 or so positions in the query string and with search strings much larger than the queries (the DNA reads were around 1000 bases and the search strings were on the order of 10000, so I was looking for approximate substring matches justified by an estimate of edit distance specifically). Adapting this methodology to natural language will require some careful thought: you lose on alphabet size but you gain if your query strings and search strings are of similar length. Either way, allowing more than one anchor from different ends of the query string to be used simultaneously might be helpful in further filtering data fed to NW. If you do this, be prepared to possibly send overlapping strings each containing one of the two anchors to the aligner and then reconcile the alignments... or possibly further modify NW to emphasize keeping your anchors mostly intact during an alignment using penalty modification during the algorithm's execution. Hope this is helpful or at least interesting. | [
"algorithm",
"string"
] | 46 | 32 | 33,603 | 7 | 0 | 2008-09-08T07:21:20.323000 | 2008-09-08T16:39:52.667000 |
49,267 | 49,410 | Embedded custom-tag in dynamic content (nested tag) not rendering | Embedded custom-tag in dynamic content (nested tag) not rendering. I have a page that pulls dynamic content from a javabean and passes the list of objects to a custom tag for processing into html. Within each object is a bunch of html to be output that contains a second custom tag that I would like to also be rendered. The problem is that the tag invocation is rendered as plaintext. An example might serve me better. 1 Pull information from a database and return it to the page via a javabean. Send this info to a custom tag for outputting. <%-- Declare the bean --%> <%-- Get the info --%> <%-- give it to the tag for processing --%> this tag should output a box div like so *SNIP* class for custom tag def and method setup etc out.println(" "); out.println(" " + importantNotice.getMessage()); out.println(" Posted: " + importantNotice.getDateFrom() + " End: " + importantNotice.getDateTo() "); out.println(" - " + importantNotice.getAuthor() + " "); out.println(" "); *SNIP* This renders fine and as expected This is a very important message. Everyone should pay attenton to it. Posted: 2008-09-08 End: 2008-09-08 - The author 2 If, in the above example, for instance, I were to have a custom tag in the importantNotice.getMessage() String: *SNIP* "This is a very important message. Everyone should pay attenton to it. Quote this " *SNIP* The important notice renders fine but the quote tag will not be processed and simply inserted into the string and put as plain text/html tag. This is a very important message. Everyone should pay attenton to it. Quote this Posted: 2008-09-08 End: 2008-09-08 - The author Rather than This is a very important message. Everyone should pay attenton to it. Quote this Some Guy // or wahtever I choose as the output Posted: 2008-09-08 End: 2008-09-08 - The author I know this has to do with processors and pre-processors but I am not to sure about how to make this work. | Just using JSP is not enough. You should do soimething like JspFragment body = getJspBody(); StringWriter stringWriter = new StringWriter(); StringBuffer buff = stringWriter.getBuffer(); buff.append(" "); body.invoke(stringWriter); buff.append(" "); out.println(stringWriter); to get inner tags rendered (example is for SimpleTag doTag method). However, in the question's code I see that inner tag is comming from a string which is not rendered as a part of JSP, but just some random string. I do not think you can force JSP translator to parse it. You can use regexp in your case or try to redesign your code in a way to have a jsp like this: Quote this I whould go with regexp. | Embedded custom-tag in dynamic content (nested tag) not rendering Embedded custom-tag in dynamic content (nested tag) not rendering. I have a page that pulls dynamic content from a javabean and passes the list of objects to a custom tag for processing into html. Within each object is a bunch of html to be output that contains a second custom tag that I would like to also be rendered. The problem is that the tag invocation is rendered as plaintext. An example might serve me better. 1 Pull information from a database and return it to the page via a javabean. Send this info to a custom tag for outputting. <%-- Declare the bean --%> <%-- Get the info --%> <%-- give it to the tag for processing --%> this tag should output a box div like so *SNIP* class for custom tag def and method setup etc out.println(" "); out.println(" " + importantNotice.getMessage()); out.println(" Posted: " + importantNotice.getDateFrom() + " End: " + importantNotice.getDateTo() "); out.println(" - " + importantNotice.getAuthor() + " "); out.println(" "); *SNIP* This renders fine and as expected This is a very important message. Everyone should pay attenton to it. Posted: 2008-09-08 End: 2008-09-08 - The author 2 If, in the above example, for instance, I were to have a custom tag in the importantNotice.getMessage() String: *SNIP* "This is a very important message. Everyone should pay attenton to it. Quote this " *SNIP* The important notice renders fine but the quote tag will not be processed and simply inserted into the string and put as plain text/html tag. This is a very important message. Everyone should pay attenton to it. Quote this Posted: 2008-09-08 End: 2008-09-08 - The author Rather than This is a very important message. Everyone should pay attenton to it. Quote this Some Guy // or wahtever I choose as the output Posted: 2008-09-08 End: 2008-09-08 - The author I know this has to do with processors and pre-processors but I am not to sure about how to make this work. | TITLE:
Embedded custom-tag in dynamic content (nested tag) not rendering
QUESTION:
Embedded custom-tag in dynamic content (nested tag) not rendering. I have a page that pulls dynamic content from a javabean and passes the list of objects to a custom tag for processing into html. Within each object is a bunch of html to be output that contains a second custom tag that I would like to also be rendered. The problem is that the tag invocation is rendered as plaintext. An example might serve me better. 1 Pull information from a database and return it to the page via a javabean. Send this info to a custom tag for outputting. <%-- Declare the bean --%> <%-- Get the info --%> <%-- give it to the tag for processing --%> this tag should output a box div like so *SNIP* class for custom tag def and method setup etc out.println(" "); out.println(" " + importantNotice.getMessage()); out.println(" Posted: " + importantNotice.getDateFrom() + " End: " + importantNotice.getDateTo() "); out.println(" - " + importantNotice.getAuthor() + " "); out.println(" "); *SNIP* This renders fine and as expected This is a very important message. Everyone should pay attenton to it. Posted: 2008-09-08 End: 2008-09-08 - The author 2 If, in the above example, for instance, I were to have a custom tag in the importantNotice.getMessage() String: *SNIP* "This is a very important message. Everyone should pay attenton to it. Quote this " *SNIP* The important notice renders fine but the quote tag will not be processed and simply inserted into the string and put as plain text/html tag. This is a very important message. Everyone should pay attenton to it. Quote this Posted: 2008-09-08 End: 2008-09-08 - The author Rather than This is a very important message. Everyone should pay attenton to it. Quote this Some Guy // or wahtever I choose as the output Posted: 2008-09-08 End: 2008-09-08 - The author I know this has to do with processors and pre-processors but I am not to sure about how to make this work.
ANSWER:
Just using JSP is not enough. You should do soimething like JspFragment body = getJspBody(); StringWriter stringWriter = new StringWriter(); StringBuffer buff = stringWriter.getBuffer(); buff.append(" "); body.invoke(stringWriter); buff.append(" "); out.println(stringWriter); to get inner tags rendered (example is for SimpleTag doTag method). However, in the question's code I see that inner tag is comming from a string which is not rendered as a part of JSP, but just some random string. I do not think you can force JSP translator to parse it. You can use regexp in your case or try to redesign your code in a way to have a jsp like this: Quote this I whould go with regexp. | [
"java",
"jsp",
"jstl",
"custom-tag"
] | 0 | 1 | 2,139 | 2 | 0 | 2008-09-08T07:28:36.173000 | 2008-09-08T10:12:37.353000 |
49,269 | 49,289 | Reading default application settings in C# | I have a number of application settings (in user scope) for my custom grid control. Most of them are color settings. I have a form where the user can customize these colors and I want to add a button for reverting to default color settings. How can I read the default settings? For example: I have a user setting named CellBackgroundColor in Properties.Settings. At design time I set the value of CellBackgroundColor to Color.White using the IDE. User sets CellBackgroundColor to Color.Black in my program. I save the settings with Properties.Settings.Default.Save(). User clicks on the Restore Default Colors button. Now, Properties.Settings.Default.CellBackgroundColor returns Color.Black. How do I go back to Color.White? | @ozgur, Settings.Default.Properties["property"].DefaultValue // initial value from config file Example: string foo = Settings.Default.Foo; // Foo = "Foo" by default Settings.Default.Foo = "Boo"; Settings.Default.Save(); string modifiedValue = Settings.Default.Foo; // modifiedValue = "Boo" string originalValue = Settings.Default.Properties["Foo"].DefaultValue as string; // originalValue = "Foo" | Reading default application settings in C# I have a number of application settings (in user scope) for my custom grid control. Most of them are color settings. I have a form where the user can customize these colors and I want to add a button for reverting to default color settings. How can I read the default settings? For example: I have a user setting named CellBackgroundColor in Properties.Settings. At design time I set the value of CellBackgroundColor to Color.White using the IDE. User sets CellBackgroundColor to Color.Black in my program. I save the settings with Properties.Settings.Default.Save(). User clicks on the Restore Default Colors button. Now, Properties.Settings.Default.CellBackgroundColor returns Color.Black. How do I go back to Color.White? | TITLE:
Reading default application settings in C#
QUESTION:
I have a number of application settings (in user scope) for my custom grid control. Most of them are color settings. I have a form where the user can customize these colors and I want to add a button for reverting to default color settings. How can I read the default settings? For example: I have a user setting named CellBackgroundColor in Properties.Settings. At design time I set the value of CellBackgroundColor to Color.White using the IDE. User sets CellBackgroundColor to Color.Black in my program. I save the settings with Properties.Settings.Default.Save(). User clicks on the Restore Default Colors button. Now, Properties.Settings.Default.CellBackgroundColor returns Color.Black. How do I go back to Color.White?
ANSWER:
@ozgur, Settings.Default.Properties["property"].DefaultValue // initial value from config file Example: string foo = Settings.Default.Foo; // Foo = "Foo" by default Settings.Default.Foo = "Boo"; Settings.Default.Save(); string modifiedValue = Settings.Default.Foo; // modifiedValue = "Boo" string originalValue = Settings.Default.Properties["Foo"].DefaultValue as string; // originalValue = "Foo" | [
"c#",
".net",
"winforms",
"application-settings"
] | 30 | 42 | 46,634 | 7 | 0 | 2008-09-08T07:30:47.930000 | 2008-09-08T07:55:30.397000 |
49,274 | 49,282 | Safe integer parsing in Ruby | I have a string, say '123', and I want to convert it to the integer 123. I know you can simply do some_string.to_i, but that converts 'lolipops' to 0, which is not the effect I have in mind. I want it to blow up in my face when I try to convert something invalid, with a nice and painful Exception. Otherwise, I can't distinguish between a valid 0 and something that just isn't a number at all. EDIT: I was looking for the standard way of doing it, without regex trickery. | Ruby has this functionality built in: Integer('1001') # => 1001 Integer('1001 nights') # ArgumentError: invalid value for Integer: "1001 nights" As noted in answer by Joseph Pecoraro, you might want to watch for strings that are valid non-decimal numbers, such as those starting with 0x for hex and 0b for binary, and potentially more tricky numbers starting with zero that will be parsed as octal. Ruby 1.9.2 added optional second argument for radix so above issue can be avoided: Integer('23') # => 23 Integer('0x23') # => 35 Integer('023') # => 19 Integer('0x23', 10) # => # Integer('023', 10) # => 23 | Safe integer parsing in Ruby I have a string, say '123', and I want to convert it to the integer 123. I know you can simply do some_string.to_i, but that converts 'lolipops' to 0, which is not the effect I have in mind. I want it to blow up in my face when I try to convert something invalid, with a nice and painful Exception. Otherwise, I can't distinguish between a valid 0 and something that just isn't a number at all. EDIT: I was looking for the standard way of doing it, without regex trickery. | TITLE:
Safe integer parsing in Ruby
QUESTION:
I have a string, say '123', and I want to convert it to the integer 123. I know you can simply do some_string.to_i, but that converts 'lolipops' to 0, which is not the effect I have in mind. I want it to blow up in my face when I try to convert something invalid, with a nice and painful Exception. Otherwise, I can't distinguish between a valid 0 and something that just isn't a number at all. EDIT: I was looking for the standard way of doing it, without regex trickery.
ANSWER:
Ruby has this functionality built in: Integer('1001') # => 1001 Integer('1001 nights') # ArgumentError: invalid value for Integer: "1001 nights" As noted in answer by Joseph Pecoraro, you might want to watch for strings that are valid non-decimal numbers, such as those starting with 0x for hex and 0b for binary, and potentially more tricky numbers starting with zero that will be parsed as octal. Ruby 1.9.2 added optional second argument for radix so above issue can be avoided: Integer('23') # => 23 Integer('0x23') # => 35 Integer('023') # => 19 Integer('0x23', 10) # => # Integer('023', 10) # => 23 | [
"ruby",
"string",
"exception",
"integer",
"string-parsing"
] | 169 | 244 | 99,366 | 8 | 0 | 2008-09-08T07:41:00.293000 | 2008-09-08T07:49:16.170000 |
49,302 | 49,311 | How to Identify Postback event in Page_Load | We have some legacy code that needs to identify in the Page_Load which event caused the postback. At the moment this is implemented by checking the Request data like this... if (Request.Form["__EVENTTARGET"]!= null && (Request.Form["__EVENTTARGET"].IndexOf("BaseGrid") > -1 // BaseGrid event ( e.g. sort) || Request.Form["btnSave"]!= null // Save button This is pretty ugly and breaks if someone renames a control. Is there a better way of doing this? Rewriting each page so that it does not need to check this in Page_Load is not an option at the moment. | This should get you the control that caused the postback: public static Control GetPostBackControl(Page page) { Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET"); if (ctrlname!= null && ctrlname!= string.Empty) { control = page.FindControl(ctrlname); } else { foreach (string ctl in page.Request.Form) { Control c = page.FindControl(ctl); if (c is System.Web.UI.WebControls.Button) { control = c; break; } } } return control; } Read more about this on this page: http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx | How to Identify Postback event in Page_Load We have some legacy code that needs to identify in the Page_Load which event caused the postback. At the moment this is implemented by checking the Request data like this... if (Request.Form["__EVENTTARGET"]!= null && (Request.Form["__EVENTTARGET"].IndexOf("BaseGrid") > -1 // BaseGrid event ( e.g. sort) || Request.Form["btnSave"]!= null // Save button This is pretty ugly and breaks if someone renames a control. Is there a better way of doing this? Rewriting each page so that it does not need to check this in Page_Load is not an option at the moment. | TITLE:
How to Identify Postback event in Page_Load
QUESTION:
We have some legacy code that needs to identify in the Page_Load which event caused the postback. At the moment this is implemented by checking the Request data like this... if (Request.Form["__EVENTTARGET"]!= null && (Request.Form["__EVENTTARGET"].IndexOf("BaseGrid") > -1 // BaseGrid event ( e.g. sort) || Request.Form["btnSave"]!= null // Save button This is pretty ugly and breaks if someone renames a control. Is there a better way of doing this? Rewriting each page so that it does not need to check this in Page_Load is not an option at the moment.
ANSWER:
This should get you the control that caused the postback: public static Control GetPostBackControl(Page page) { Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET"); if (ctrlname!= null && ctrlname!= string.Empty) { control = page.FindControl(ctrlname); } else { foreach (string ctl in page.Request.Form) { Control c = page.FindControl(ctl); if (c is System.Web.UI.WebControls.Button) { control = c; break; } } } return control; } Read more about this on this page: http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx | [
"c#",
"asp.net"
] | 5 | 7 | 8,035 | 3 | 0 | 2008-09-08T08:19:47.063000 | 2008-09-08T08:29:01.067000 |
49,330 | 49,423 | VS 2005 & 2008 library linking | Is it correct to link a static library (.lib) compiled with VS 2005 with a program which is compiled with VS 2008? Both library and my program are written in C++. This program is run on Windows Mobile 6 Professional emulator. This seems to work, there are no linking errors. However the program crashes during startup because strange things happen inside the linked library. E.g. lib can return a vector of characters with size of big negative number. There are no such problems when the program is compiled with VS 2005. What is even more strange the problem is only when using release configuration for the build. When compiling using debug configuration the problem doesn't occur. | VS2005 and VS2008 use different STL implementations. When the VS2005 code returns a vector, the object has memory layout different from what VS2008 expects. That should be the reason for the broken values you see in the returned date. As a rule of thumb, you should always compile all C++ modules of a project with the same compiler and all settings/#defines equal. One particular #define that causes similar behaviour is the SECURE_SCL #define of VS2008. Two modules compiled with different settings will create exactly your problems, because #defining SECURE_SCL introduces more member variables to various C++ library classes. | VS 2005 & 2008 library linking Is it correct to link a static library (.lib) compiled with VS 2005 with a program which is compiled with VS 2008? Both library and my program are written in C++. This program is run on Windows Mobile 6 Professional emulator. This seems to work, there are no linking errors. However the program crashes during startup because strange things happen inside the linked library. E.g. lib can return a vector of characters with size of big negative number. There are no such problems when the program is compiled with VS 2005. What is even more strange the problem is only when using release configuration for the build. When compiling using debug configuration the problem doesn't occur. | TITLE:
VS 2005 & 2008 library linking
QUESTION:
Is it correct to link a static library (.lib) compiled with VS 2005 with a program which is compiled with VS 2008? Both library and my program are written in C++. This program is run on Windows Mobile 6 Professional emulator. This seems to work, there are no linking errors. However the program crashes during startup because strange things happen inside the linked library. E.g. lib can return a vector of characters with size of big negative number. There are no such problems when the program is compiled with VS 2005. What is even more strange the problem is only when using release configuration for the build. When compiling using debug configuration the problem doesn't occur.
ANSWER:
VS2005 and VS2008 use different STL implementations. When the VS2005 code returns a vector, the object has memory layout different from what VS2008 expects. That should be the reason for the broken values you see in the returned date. As a rule of thumb, you should always compile all C++ modules of a project with the same compiler and all settings/#defines equal. One particular #define that causes similar behaviour is the SECURE_SCL #define of VS2008. Two modules compiled with different settings will create exactly your problems, because #defining SECURE_SCL introduces more member variables to various C++ library classes. | [
"visual-studio-2008",
"visual-c++",
"visual-studio-2005",
"linker"
] | 4 | 12 | 2,165 | 3 | 0 | 2008-09-08T08:44:10.937000 | 2008-09-08T10:24:23.363000 |
49,334 | 53,405 | Querying collections of value type in the Criteria API in Hibernate | In my database, I have an entity table (let's call it Entity). Each entity can have a number of entity types, and the set of entity types is static. Therefore, there is a connecting table that contains rows of the entity id and the name of the entity type. In my code, EntityType is an enum, and Entity is a Hibernate-mapped class. in the Entity code, the mapping looks like this: @CollectionOfElements @JoinTable( name = "ENTITY-ENTITY-TYPE", joinColumns = @JoinColumn(name = "ENTITY-ID") ) @Column(name="ENTITY-TYPE") public Set getEntityTypes() { return entityTypes; } Oh, did I mention I'm using annotations? Now, what I'd like to do is create an HQL query or search using a Criteria for all Entity objects of a specific entity type. This page in the Hibernate forum says this is impossible, but then this page is 18 months old. Can anyone tell me if this feature has been implemented in one of the latest releases of Hibernate, or planned for the coming release? | HQL: select entity from Entity entity where:type = some elements(entity.types) I think that you can also write it like: select entity from Entity entity where:type in(entity.types) | Querying collections of value type in the Criteria API in Hibernate In my database, I have an entity table (let's call it Entity). Each entity can have a number of entity types, and the set of entity types is static. Therefore, there is a connecting table that contains rows of the entity id and the name of the entity type. In my code, EntityType is an enum, and Entity is a Hibernate-mapped class. in the Entity code, the mapping looks like this: @CollectionOfElements @JoinTable( name = "ENTITY-ENTITY-TYPE", joinColumns = @JoinColumn(name = "ENTITY-ID") ) @Column(name="ENTITY-TYPE") public Set getEntityTypes() { return entityTypes; } Oh, did I mention I'm using annotations? Now, what I'd like to do is create an HQL query or search using a Criteria for all Entity objects of a specific entity type. This page in the Hibernate forum says this is impossible, but then this page is 18 months old. Can anyone tell me if this feature has been implemented in one of the latest releases of Hibernate, or planned for the coming release? | TITLE:
Querying collections of value type in the Criteria API in Hibernate
QUESTION:
In my database, I have an entity table (let's call it Entity). Each entity can have a number of entity types, and the set of entity types is static. Therefore, there is a connecting table that contains rows of the entity id and the name of the entity type. In my code, EntityType is an enum, and Entity is a Hibernate-mapped class. in the Entity code, the mapping looks like this: @CollectionOfElements @JoinTable( name = "ENTITY-ENTITY-TYPE", joinColumns = @JoinColumn(name = "ENTITY-ID") ) @Column(name="ENTITY-TYPE") public Set getEntityTypes() { return entityTypes; } Oh, did I mention I'm using annotations? Now, what I'd like to do is create an HQL query or search using a Criteria for all Entity objects of a specific entity type. This page in the Hibernate forum says this is impossible, but then this page is 18 months old. Can anyone tell me if this feature has been implemented in one of the latest releases of Hibernate, or planned for the coming release?
ANSWER:
HQL: select entity from Entity entity where:type = some elements(entity.types) I think that you can also write it like: select entity from Entity entity where:type in(entity.types) | [
"hibernate",
"enums",
"hql"
] | 0 | 1 | 2,121 | 2 | 0 | 2008-09-08T08:46:36.610000 | 2008-09-10T04:14:44.810000 |
49,346 | 49,381 | How to prevent a hyperlink from linking | Is it possible to prevent an asp.net Hyperlink control from linking, i.e. so that it appears as a label, without actually having to replace the control with a label? Maybe using CSS or setting an attribute? I know that marking it as disabled works but then it gets displayed differently (greyed out). To clarify my point, I have a list of user names at the top of my page which are built dynamically using a user control. Most of the time these names are linkable to an email page. However if the user has been disabled the name is displayed in grey but currently still links to the email page. I want these disabled users to not link. I know that really I should be replacing them with a label but this does not seem quite as elegant as just removing the linking ability usings CSS say (if thats possible). They are already displayed in a different colour so its obvious that they are disabled users. I just need to switch off the link. | This sounds like a job for JQuery. Just give a specific class name to all of the HyperLink controls that you want the URLs removed and then apply the following JQuery snippet to the bottom of your page: $(document).ready(function() { $('a.NoLink').removeAttr('href') }); All of the HyperLink controls with the class name "NoLink" will automatically have all of their URLs removed and the link will appear to be nothing more than text. A single line of JQuery can solve your problem. | How to prevent a hyperlink from linking Is it possible to prevent an asp.net Hyperlink control from linking, i.e. so that it appears as a label, without actually having to replace the control with a label? Maybe using CSS or setting an attribute? I know that marking it as disabled works but then it gets displayed differently (greyed out). To clarify my point, I have a list of user names at the top of my page which are built dynamically using a user control. Most of the time these names are linkable to an email page. However if the user has been disabled the name is displayed in grey but currently still links to the email page. I want these disabled users to not link. I know that really I should be replacing them with a label but this does not seem quite as elegant as just removing the linking ability usings CSS say (if thats possible). They are already displayed in a different colour so its obvious that they are disabled users. I just need to switch off the link. | TITLE:
How to prevent a hyperlink from linking
QUESTION:
Is it possible to prevent an asp.net Hyperlink control from linking, i.e. so that it appears as a label, without actually having to replace the control with a label? Maybe using CSS or setting an attribute? I know that marking it as disabled works but then it gets displayed differently (greyed out). To clarify my point, I have a list of user names at the top of my page which are built dynamically using a user control. Most of the time these names are linkable to an email page. However if the user has been disabled the name is displayed in grey but currently still links to the email page. I want these disabled users to not link. I know that really I should be replacing them with a label but this does not seem quite as elegant as just removing the linking ability usings CSS say (if thats possible). They are already displayed in a different colour so its obvious that they are disabled users. I just need to switch off the link.
ANSWER:
This sounds like a job for JQuery. Just give a specific class name to all of the HyperLink controls that you want the URLs removed and then apply the following JQuery snippet to the bottom of your page: $(document).ready(function() { $('a.NoLink').removeAttr('href') }); All of the HyperLink controls with the class name "NoLink" will automatically have all of their URLs removed and the link will appear to be nothing more than text. A single line of JQuery can solve your problem. | [
"asp.net",
"css"
] | 5 | 6 | 4,725 | 12 | 0 | 2008-09-08T09:07:39.303000 | 2008-09-08T09:40:32.393000 |
49,352 | 49,398 | How to make cruisecontrol only build one project at a time | I have just set up cruise control.net on our build server, and I am unable to find a setting to tell it to only build one project at a time. Any ideas? | If you are using CruiseControl 1.3 or later you can use an Integration Queue These allow you to control which projects can be built concurrently and which must be serialized. | How to make cruisecontrol only build one project at a time I have just set up cruise control.net on our build server, and I am unable to find a setting to tell it to only build one project at a time. Any ideas? | TITLE:
How to make cruisecontrol only build one project at a time
QUESTION:
I have just set up cruise control.net on our build server, and I am unable to find a setting to tell it to only build one project at a time. Any ideas?
ANSWER:
If you are using CruiseControl 1.3 or later you can use an Integration Queue These allow you to control which projects can be built concurrently and which must be serialized. | [
"build-automation",
"cruisecontrol.net"
] | 3 | 5 | 745 | 1 | 0 | 2008-09-08T09:16:30.750000 | 2008-09-08T09:56:40.560000 |
49,368 | 49,373 | CSS2 Attribute Selectors with Regex | CSS Attribute selectors allow the selection of elements based on attribute values. Unfortunately, I've not used them in years (mainly because they're not supported by all modern browsers). However, I remember distinctly that I was able to use them to adorn all external links with an icon, by using a code similar to the following: a[href=http] { background: url(external-uri); padding-left: 12px; } The above code doesn't work. My question is: How does it work? How do I select all tags whose href attribute starts with "http"? The official CSS spec (linked above) doesn't even mention that this is possible. But I do remember doing this. ( Note: The obvious solution would be to use class attributes for distinction. I want to avoid this because I have little influence of the way the HTML code is built. All I can edit is the CSS code.) | As for CSS 2.1, see http://www.w3.org/TR/CSS21/selector.html#attribute-selectors Executive summary: Attribute selectors may match in four ways:
[att] Match when the element sets the "att" attribute, whatever the value of the attribute. [att=val] Match when the element's "att" attribute value is exactly "val". [att~=val] Match when the element's "att" attribute value is a space-separated list of "words", one of which is exactly "val". If this selector is used, the words in the value must not contain spaces (since they are separated by spaces). [att|=val] Match when the element's "att" attribute value is a hyphen-separated list of "words", beginning with "val". The match always starts at the beginning of the attribute value. This is primarily intended to allow language subcode matches (e.g., the "lang" attribute in HTML) as described in RFC 3066 ([RFC3066]). CSS3 also defines a list of selectors, but the compatibility varies hugely. There's also a nifty test suite that that shows which selectors work in your browser. As for your example, a[href^=http] { background: url(external-uri); padding-left: 12px; } should do the trick. Unfortunately, it is not supported by IE. | CSS2 Attribute Selectors with Regex CSS Attribute selectors allow the selection of elements based on attribute values. Unfortunately, I've not used them in years (mainly because they're not supported by all modern browsers). However, I remember distinctly that I was able to use them to adorn all external links with an icon, by using a code similar to the following: a[href=http] { background: url(external-uri); padding-left: 12px; } The above code doesn't work. My question is: How does it work? How do I select all tags whose href attribute starts with "http"? The official CSS spec (linked above) doesn't even mention that this is possible. But I do remember doing this. ( Note: The obvious solution would be to use class attributes for distinction. I want to avoid this because I have little influence of the way the HTML code is built. All I can edit is the CSS code.) | TITLE:
CSS2 Attribute Selectors with Regex
QUESTION:
CSS Attribute selectors allow the selection of elements based on attribute values. Unfortunately, I've not used them in years (mainly because they're not supported by all modern browsers). However, I remember distinctly that I was able to use them to adorn all external links with an icon, by using a code similar to the following: a[href=http] { background: url(external-uri); padding-left: 12px; } The above code doesn't work. My question is: How does it work? How do I select all tags whose href attribute starts with "http"? The official CSS spec (linked above) doesn't even mention that this is possible. But I do remember doing this. ( Note: The obvious solution would be to use class attributes for distinction. I want to avoid this because I have little influence of the way the HTML code is built. All I can edit is the CSS code.)
ANSWER:
As for CSS 2.1, see http://www.w3.org/TR/CSS21/selector.html#attribute-selectors Executive summary: Attribute selectors may match in four ways:
[att] Match when the element sets the "att" attribute, whatever the value of the attribute. [att=val] Match when the element's "att" attribute value is exactly "val". [att~=val] Match when the element's "att" attribute value is a space-separated list of "words", one of which is exactly "val". If this selector is used, the words in the value must not contain spaces (since they are separated by spaces). [att|=val] Match when the element's "att" attribute value is a hyphen-separated list of "words", beginning with "val". The match always starts at the beginning of the attribute value. This is primarily intended to allow language subcode matches (e.g., the "lang" attribute in HTML) as described in RFC 3066 ([RFC3066]). CSS3 also defines a list of selectors, but the compatibility varies hugely. There's also a nifty test suite that that shows which selectors work in your browser. As for your example, a[href^=http] { background: url(external-uri); padding-left: 12px; } should do the trick. Unfortunately, it is not supported by IE. | [
"css",
"css-selectors"
] | 31 | 34 | 35,722 | 3 | 0 | 2008-09-08T09:30:29.077000 | 2008-09-08T09:32:56.373000 |
49,378 | 60,694 | Deploy MySQL Server + DB with .Net application | HI All, We have a.Net 2.0 application which has a MySQL backend. We want to be able to deploy MySQl and the DB when we install the application and im trying to find the best solution. The current setup is to copy the required files to a folder on the local machine and then perform a "NET START" commands to install and start the mysql service. Then we restore a backup of the DB to this newly created mysql instance using bat files. Its not an ideal solution at all and im trying to come up with something more robust. The issues are User rights on Vista, and all sorts of small things around installing and starting the service. Its far too fragile to be reliable or at least it appears that way when i am testing it. This is a Client/Server type setup so we only need to install one Server per office but i want to make sure its as hassle free as possible and with as few screens as possible. How would you do it? | Not sure where you're at in the project, but if it's a simple and small database you might consider converting it to SQLite. It's not ideal for Client/Server operations, but if it's low volume/transactions it might work. | Deploy MySQL Server + DB with .Net application HI All, We have a.Net 2.0 application which has a MySQL backend. We want to be able to deploy MySQl and the DB when we install the application and im trying to find the best solution. The current setup is to copy the required files to a folder on the local machine and then perform a "NET START" commands to install and start the mysql service. Then we restore a backup of the DB to this newly created mysql instance using bat files. Its not an ideal solution at all and im trying to come up with something more robust. The issues are User rights on Vista, and all sorts of small things around installing and starting the service. Its far too fragile to be reliable or at least it appears that way when i am testing it. This is a Client/Server type setup so we only need to install one Server per office but i want to make sure its as hassle free as possible and with as few screens as possible. How would you do it? | TITLE:
Deploy MySQL Server + DB with .Net application
QUESTION:
HI All, We have a.Net 2.0 application which has a MySQL backend. We want to be able to deploy MySQl and the DB when we install the application and im trying to find the best solution. The current setup is to copy the required files to a folder on the local machine and then perform a "NET START" commands to install and start the mysql service. Then we restore a backup of the DB to this newly created mysql instance using bat files. Its not an ideal solution at all and im trying to come up with something more robust. The issues are User rights on Vista, and all sorts of small things around installing and starting the service. Its far too fragile to be reliable or at least it appears that way when i am testing it. This is a Client/Server type setup so we only need to install one Server per office but i want to make sure its as hassle free as possible and with as few screens as possible. How would you do it?
ANSWER:
Not sure where you're at in the project, but if it's a simple and small database you might consider converting it to SQLite. It's not ideal for Client/Server operations, but if it's low volume/transactions it might work. | [
".net",
"mysql",
"database",
"deployment",
"installation"
] | 9 | 5 | 6,395 | 4 | 0 | 2008-09-08T09:38:22.600000 | 2008-09-13T17:04:59.600000 |
49,379 | 49,428 | How to lock compiled Java classes to prevent decompilation? | How do I lock compiled Java classes to prevent decompilation? I know this must be very well discussed topic on the Internet, but I could not come to any conclusion after referring them. Many people do suggest obfuscator, but they just do renaming of classes, methods, and fields with tough-to-remember character sequences but what about sensitive constant values? For example, you have developed the encryption and decryption component based on a password based encryption technique. Now in this case, any average Java person can use JAD to decompile the class file and easily retrieve the password value (defined as constant) as well as salt and in turn can decrypt the data by writing small independent program! Or should such sensitive components be built in native code (for example, VC++) and call them via JNI? | Some of the more advanced Java bytecode obfuscators do much more than just class name mangling. Zelix KlassMaster, for example, can also scramble your code flow in a way that makes it really hard to follow and works as an excellent code optimizer... Also many of the obfuscators are also able to scramble your string constants and remove unused code. Another possible solution (not necessarily excluding the obfuscation) is to use encrypted JAR files and a custom classloader that does the decryption (preferably using native runtime library). Third (and possibly offering the strongest protection) is to use native ahead of time compilers like GCC or Excelsior JET, for example, that compile your Java code directly to a platform specific native binary. In any case You've got to remember that as the saying goes in Estonian "Locks are for animals". Meaning that every bit of code is available (loaded into memory) during the runtime and given enough skill, determination and motivation, people can and will decompile, unscramble and hack your code... Your job is simply to make the process as uncomfortable as you can and still keep the thing working... | How to lock compiled Java classes to prevent decompilation? How do I lock compiled Java classes to prevent decompilation? I know this must be very well discussed topic on the Internet, but I could not come to any conclusion after referring them. Many people do suggest obfuscator, but they just do renaming of classes, methods, and fields with tough-to-remember character sequences but what about sensitive constant values? For example, you have developed the encryption and decryption component based on a password based encryption technique. Now in this case, any average Java person can use JAD to decompile the class file and easily retrieve the password value (defined as constant) as well as salt and in turn can decrypt the data by writing small independent program! Or should such sensitive components be built in native code (for example, VC++) and call them via JNI? | TITLE:
How to lock compiled Java classes to prevent decompilation?
QUESTION:
How do I lock compiled Java classes to prevent decompilation? I know this must be very well discussed topic on the Internet, but I could not come to any conclusion after referring them. Many people do suggest obfuscator, but they just do renaming of classes, methods, and fields with tough-to-remember character sequences but what about sensitive constant values? For example, you have developed the encryption and decryption component based on a password based encryption technique. Now in this case, any average Java person can use JAD to decompile the class file and easily retrieve the password value (defined as constant) as well as salt and in turn can decrypt the data by writing small independent program! Or should such sensitive components be built in native code (for example, VC++) and call them via JNI?
ANSWER:
Some of the more advanced Java bytecode obfuscators do much more than just class name mangling. Zelix KlassMaster, for example, can also scramble your code flow in a way that makes it really hard to follow and works as an excellent code optimizer... Also many of the obfuscators are also able to scramble your string constants and remove unused code. Another possible solution (not necessarily excluding the obfuscation) is to use encrypted JAR files and a custom classloader that does the decryption (preferably using native runtime library). Third (and possibly offering the strongest protection) is to use native ahead of time compilers like GCC or Excelsior JET, for example, that compile your Java code directly to a platform specific native binary. In any case You've got to remember that as the saying goes in Estonian "Locks are for animals". Meaning that every bit of code is available (loaded into memory) during the runtime and given enough skill, determination and motivation, people can and will decompile, unscramble and hack your code... Your job is simply to make the process as uncomfortable as you can and still keep the thing working... | [
"java",
"jvm",
"decompiling"
] | 105 | 103 | 96,921 | 9 | 0 | 2008-09-08T09:38:58.607000 | 2008-09-08T10:29:19.013000 |
49,382 | 49,530 | What are the preferred conventions in naming attributes, methods and classes in different languages? | Are the naming conventions similar in different languages? If not, what are the differences? | As others have said, things vary a lot, but here's a rough overview of the most commonly used naming conventions in various languages: lowercase, lowercase_with_underscores: Commonly used for local variables and function names (typical C syntax). UPPERCASE, UPPERCASE_WITH_UNDERSCORES: Commonly used for constants and variables that never change. Some (older) languages like BASIC also have a convention for using all upper case for all variable names. CamelCase, javaCamelCase: Typically used for function names and variable names. Some use it only for functions and combine it with lowercase or lowercase_with_underscores for variables. When javaCamelCase is used, it's typically used both for functions and variables. This syntax is also quite common for external APIs, since this is how the Win32 and Java APIs do it. (Even if a library uses a different convention internally they typically export with the (java)CamelCase syntax for function names.) prefix_CamelCase, prefix_lowercase, prefix_lowercase_with_underscores: Commonly used in languages that don't support namespaces (i.e. C). The prefix will usually denote the library or module to which the function or variable belongs. Usually reserved to global variables and global functions. Prefix can also be in UPPERCASE. Some conventions use lowercase prefix for internal functions and variables and UPPERCASE prefix for exported ones. There are of course many other ways to name things, but most conventions are based on one of the ones mentioned above or a variety on those. BTW: I forgot to mention Hungarian notation on purpose. | What are the preferred conventions in naming attributes, methods and classes in different languages? Are the naming conventions similar in different languages? If not, what are the differences? | TITLE:
What are the preferred conventions in naming attributes, methods and classes in different languages?
QUESTION:
Are the naming conventions similar in different languages? If not, what are the differences?
ANSWER:
As others have said, things vary a lot, but here's a rough overview of the most commonly used naming conventions in various languages: lowercase, lowercase_with_underscores: Commonly used for local variables and function names (typical C syntax). UPPERCASE, UPPERCASE_WITH_UNDERSCORES: Commonly used for constants and variables that never change. Some (older) languages like BASIC also have a convention for using all upper case for all variable names. CamelCase, javaCamelCase: Typically used for function names and variable names. Some use it only for functions and combine it with lowercase or lowercase_with_underscores for variables. When javaCamelCase is used, it's typically used both for functions and variables. This syntax is also quite common for external APIs, since this is how the Win32 and Java APIs do it. (Even if a library uses a different convention internally they typically export with the (java)CamelCase syntax for function names.) prefix_CamelCase, prefix_lowercase, prefix_lowercase_with_underscores: Commonly used in languages that don't support namespaces (i.e. C). The prefix will usually denote the library or module to which the function or variable belongs. Usually reserved to global variables and global functions. Prefix can also be in UPPERCASE. Some conventions use lowercase prefix for internal functions and variables and UPPERCASE prefix for exported ones. There are of course many other ways to name things, but most conventions are based on one of the ones mentioned above or a variety on those. BTW: I forgot to mention Hungarian notation on purpose. | [
"programming-languages",
"naming"
] | 1 | 2 | 682 | 6 | 0 | 2008-09-08T09:40:55.217000 | 2008-09-08T11:46:53.430000 |
49,402 | 49,540 | Creating batch jobs in PowerShell | Imagine a DOS style.cmd file which is used to launch interdependent windowed applications in the right order. Example: 1) Launch a server application by calling an exe with parameters. 2) Wait for the server to become initialized (or a fixed amount of time). 3) Launch client application by calling an exe with parameters. What is the simplest way of accomplishing this kind of batch job in PowerShell? | Remember that PowerShell can access.Net objects. The Start-Sleep as suggested by Blair Conrad can be replaced by a call to WaitForInputIdle of the server process so you know when the server is ready before starting the client. $sp = get-process server-application $sp.WaitForInputIdle() You could also use Process.Start to start the process and have it return the exact Process. Then you don't need the get-process. $sp = [diagnostics.process]::start("server-application", "params") $sp.WaitForInputIdle() $cp = [diagnostics.process]::start("client-application", "params") | Creating batch jobs in PowerShell Imagine a DOS style.cmd file which is used to launch interdependent windowed applications in the right order. Example: 1) Launch a server application by calling an exe with parameters. 2) Wait for the server to become initialized (or a fixed amount of time). 3) Launch client application by calling an exe with parameters. What is the simplest way of accomplishing this kind of batch job in PowerShell? | TITLE:
Creating batch jobs in PowerShell
QUESTION:
Imagine a DOS style.cmd file which is used to launch interdependent windowed applications in the right order. Example: 1) Launch a server application by calling an exe with parameters. 2) Wait for the server to become initialized (or a fixed amount of time). 3) Launch client application by calling an exe with parameters. What is the simplest way of accomplishing this kind of batch job in PowerShell?
ANSWER:
Remember that PowerShell can access.Net objects. The Start-Sleep as suggested by Blair Conrad can be replaced by a call to WaitForInputIdle of the server process so you know when the server is ready before starting the client. $sp = get-process server-application $sp.WaitForInputIdle() You could also use Process.Start to start the process and have it return the exact Process. Then you don't need the get-process. $sp = [diagnostics.process]::start("server-application", "params") $sp.WaitForInputIdle() $cp = [diagnostics.process]::start("client-application", "params") | [
"powershell",
"batch-file"
] | 5 | 5 | 3,598 | 3 | 0 | 2008-09-08T10:06:06.903000 | 2008-09-08T12:00:05.800000 |
49,403 | 49,409 | How do you parse a filename in bash? | I have a filename in a format like: system-source-yyyymmdd.dat I'd like to be able to parse out the different bits of the filename using the "-" as a delimiter. | You can use the cut command to get at each of the 3 'fields', e.g.: $ echo "system-source-yyyymmdd.dat" | cut -d'-' -f2 source "-d" specifies the delimiter, "-f" specifies the number of the field you require | How do you parse a filename in bash? I have a filename in a format like: system-source-yyyymmdd.dat I'd like to be able to parse out the different bits of the filename using the "-" as a delimiter. | TITLE:
How do you parse a filename in bash?
QUESTION:
I have a filename in a format like: system-source-yyyymmdd.dat I'd like to be able to parse out the different bits of the filename using the "-" as a delimiter.
ANSWER:
You can use the cut command to get at each of the 3 'fields', e.g.: $ echo "system-source-yyyymmdd.dat" | cut -d'-' -f2 source "-d" specifies the delimiter, "-f" specifies the number of the field you require | [
"bash",
"shell",
"parsing",
"tokenize",
"cut"
] | 27 | 32 | 42,388 | 6 | 0 | 2008-09-08T10:07:03.903000 | 2008-09-08T10:11:32.130000 |
49,404 | 49,414 | SQL Query to get latest price | I have a table containing prices for a lot of different "things" in a MS SQL 2005 table. There are hundreds of records per thing per day and the different things gets price updates at different times. ID uniqueidentifier not null, ThingID int NOT NULL, PriceDateTime datetime NOT NULL, Price decimal(18,4) NOT NULL I need to get today's latest prices for a group of things. The below query works but I'm getting hundreds of rows back and I have to loop trough them and only extract the latest one per ThingID. How can I (e.g. via a GROUP BY) say that I want the latest one per ThingID? Or will I have to use subqueries? SELECT * FROM Thing WHERE ThingID IN (1,2,3,4,5,6) AND PriceDate > cast( convert(varchar(20), getdate(), 106) as DateTime) UPDATE: In an attempt to hide complexity I put the ID column in a an int. In real life it is GUID (and not the sequential kind). I have updated the table def above to use uniqueidentifier. | I think the only solution with your table structure is to work with a subquery: SELECT * FROM Thing WHERE ID IN (SELECT max(ID) FROM Thing WHERE ThingID IN (1,2,3,4) GROUP BY ThingID) (Given the highest ID also means the newest price) However I suggest you add a "IsCurrent" column that is 0 if it's not the latest price or 1 if it is the latest. This will add the possible risk of inconsistent data, but it will speed up the whole process a lot when the table gets bigger (if it is in an index). Then all you need to do is to... SELECT * FROM Thing WHERE ThingID IN (1,2,3,4) AND IsCurrent = 1 UPDATE Okay, Markus updated the question to show that ID is a uniqueid, not an int. That makes writing the query even more complex. SELECT T.* FROM Thing T JOIN (SELECT ThingID, max(PriceDateTime) WHERE ThingID IN (1,2,3,4) GROUP BY ThingID) X ON X.ThingID = T.ThingID AND X.PriceDateTime = T.PriceDateTime WHERE ThingID IN (1,2,3,4) I'd really suggest using either a "IsCurrent" column or go with the other suggestion found in the answers and use "current price" table and a separate "price history" table (which would ultimately be the fastest, because it keeps the price table itself small). (I know that the ThingID at the bottom is redundant. Just try if it is faster with or without that "WHERE". Not sure which version will be faster after the optimizer did its work.) | SQL Query to get latest price I have a table containing prices for a lot of different "things" in a MS SQL 2005 table. There are hundreds of records per thing per day and the different things gets price updates at different times. ID uniqueidentifier not null, ThingID int NOT NULL, PriceDateTime datetime NOT NULL, Price decimal(18,4) NOT NULL I need to get today's latest prices for a group of things. The below query works but I'm getting hundreds of rows back and I have to loop trough them and only extract the latest one per ThingID. How can I (e.g. via a GROUP BY) say that I want the latest one per ThingID? Or will I have to use subqueries? SELECT * FROM Thing WHERE ThingID IN (1,2,3,4,5,6) AND PriceDate > cast( convert(varchar(20), getdate(), 106) as DateTime) UPDATE: In an attempt to hide complexity I put the ID column in a an int. In real life it is GUID (and not the sequential kind). I have updated the table def above to use uniqueidentifier. | TITLE:
SQL Query to get latest price
QUESTION:
I have a table containing prices for a lot of different "things" in a MS SQL 2005 table. There are hundreds of records per thing per day and the different things gets price updates at different times. ID uniqueidentifier not null, ThingID int NOT NULL, PriceDateTime datetime NOT NULL, Price decimal(18,4) NOT NULL I need to get today's latest prices for a group of things. The below query works but I'm getting hundreds of rows back and I have to loop trough them and only extract the latest one per ThingID. How can I (e.g. via a GROUP BY) say that I want the latest one per ThingID? Or will I have to use subqueries? SELECT * FROM Thing WHERE ThingID IN (1,2,3,4,5,6) AND PriceDate > cast( convert(varchar(20), getdate(), 106) as DateTime) UPDATE: In an attempt to hide complexity I put the ID column in a an int. In real life it is GUID (and not the sequential kind). I have updated the table def above to use uniqueidentifier.
ANSWER:
I think the only solution with your table structure is to work with a subquery: SELECT * FROM Thing WHERE ID IN (SELECT max(ID) FROM Thing WHERE ThingID IN (1,2,3,4) GROUP BY ThingID) (Given the highest ID also means the newest price) However I suggest you add a "IsCurrent" column that is 0 if it's not the latest price or 1 if it is the latest. This will add the possible risk of inconsistent data, but it will speed up the whole process a lot when the table gets bigger (if it is in an index). Then all you need to do is to... SELECT * FROM Thing WHERE ThingID IN (1,2,3,4) AND IsCurrent = 1 UPDATE Okay, Markus updated the question to show that ID is a uniqueid, not an int. That makes writing the query even more complex. SELECT T.* FROM Thing T JOIN (SELECT ThingID, max(PriceDateTime) WHERE ThingID IN (1,2,3,4) GROUP BY ThingID) X ON X.ThingID = T.ThingID AND X.PriceDateTime = T.PriceDateTime WHERE ThingID IN (1,2,3,4) I'd really suggest using either a "IsCurrent" column or go with the other suggestion found in the answers and use "current price" table and a separate "price history" table (which would ultimately be the fastest, because it keeps the price table itself small). (I know that the ThingID at the bottom is redundant. Just try if it is faster with or without that "WHERE". Not sure which version will be faster after the optimizer did its work.) | [
"sql",
"sql-server",
"sql-server-2005"
] | 12 | 20 | 36,717 | 10 | 0 | 2008-09-08T10:07:28.677000 | 2008-09-08T10:16:28.780000 |
49,416 | 49,443 | GSM Modems, PCs, SMS and Telephone Calls | What all would be the requirements for the following scenario: A GSM modem connected to a PC running a web based (ASP.NET) application. In the application the user selects a phone number from a list of phone nos. When he clicks on a button named the PC should call the selected phone number. When the person on the phone responds he should be able to have a conversation with the PC user. Similarly there should be a facility to send SMS. Now I don't want any code listings. I just need to know what would be the requirements besides asp.net, database for storing phone numbers, and GSM modem. Any help in terms of reference websites would be highly appreciated. | I'll pick some points of your very broad question and answer them. Note that there are other points where others may be of more help... First, a GSM modem is probably not the way you'd want to go as they usually don't allow for concurrency. So unless you just want one user at the time to use your service, you'd probably need another solution. Also, think about cost issues - at least where I live, providing such a service would be prohibitively expensive using a normal GSM modem and a normal contract - but this is drifting into off-topicness. The next issue will be to get voice data from the client to the server (which will relay it to the phone system - using whatever practical means). Pure browser based functionality won't be of much help, so you would absolutely need something plugin based. Flash may work, seeing they provide access to the microphone, but please don't ask me about the details. I've never done anything like this. Also, privacy would be a concern. While GSM data is encrypted, the path between client and server is not per default. And even if you use SSL, you'd have to convince your users trusting you that you don't record all the conversations going on, but this too is more of a political than a coding issue. Finally, you'd have to think of bandwidth. Voice uses a lot of it and also it requires low latency. If you use a SIP trunk, you'll need the bandwidth twice per user: Once from and to your client and once from and to the SIP trunk. Calculate with 10-64 KBit/s per user and channel. A feasible architecture would probably be to use a SIP trunk (they optimize on using VoIP as much as possible and thus can provide much lower rates than a GSM provider generally does. Also, they allow for concurrency), an Asterisk box ( http://www.asterisk.org - a free PBX), some custom made flash client and a custom made SIP client on the server. All in all, this is quite the undertaking:-) | GSM Modems, PCs, SMS and Telephone Calls What all would be the requirements for the following scenario: A GSM modem connected to a PC running a web based (ASP.NET) application. In the application the user selects a phone number from a list of phone nos. When he clicks on a button named the PC should call the selected phone number. When the person on the phone responds he should be able to have a conversation with the PC user. Similarly there should be a facility to send SMS. Now I don't want any code listings. I just need to know what would be the requirements besides asp.net, database for storing phone numbers, and GSM modem. Any help in terms of reference websites would be highly appreciated. | TITLE:
GSM Modems, PCs, SMS and Telephone Calls
QUESTION:
What all would be the requirements for the following scenario: A GSM modem connected to a PC running a web based (ASP.NET) application. In the application the user selects a phone number from a list of phone nos. When he clicks on a button named the PC should call the selected phone number. When the person on the phone responds he should be able to have a conversation with the PC user. Similarly there should be a facility to send SMS. Now I don't want any code listings. I just need to know what would be the requirements besides asp.net, database for storing phone numbers, and GSM modem. Any help in terms of reference websites would be highly appreciated.
ANSWER:
I'll pick some points of your very broad question and answer them. Note that there are other points where others may be of more help... First, a GSM modem is probably not the way you'd want to go as they usually don't allow for concurrency. So unless you just want one user at the time to use your service, you'd probably need another solution. Also, think about cost issues - at least where I live, providing such a service would be prohibitively expensive using a normal GSM modem and a normal contract - but this is drifting into off-topicness. The next issue will be to get voice data from the client to the server (which will relay it to the phone system - using whatever practical means). Pure browser based functionality won't be of much help, so you would absolutely need something plugin based. Flash may work, seeing they provide access to the microphone, but please don't ask me about the details. I've never done anything like this. Also, privacy would be a concern. While GSM data is encrypted, the path between client and server is not per default. And even if you use SSL, you'd have to convince your users trusting you that you don't record all the conversations going on, but this too is more of a political than a coding issue. Finally, you'd have to think of bandwidth. Voice uses a lot of it and also it requires low latency. If you use a SIP trunk, you'll need the bandwidth twice per user: Once from and to your client and once from and to the SIP trunk. Calculate with 10-64 KBit/s per user and channel. A feasible architecture would probably be to use a SIP trunk (they optimize on using VoIP as much as possible and thus can provide much lower rates than a GSM provider generally does. Also, they allow for concurrency), an Asterisk box ( http://www.asterisk.org - a free PBX), some custom made flash client and a custom made SIP client on the server. All in all, this is quite the undertaking:-) | [
"asp.net"
] | 0 | 1 | 1,916 | 3 | 0 | 2008-09-08T10:17:39.543000 | 2008-09-08T10:39:47.350000 |
49,426 | 49,460 | How do you manage your app when the database goes offline? | Take a.Net Winforms App.. mix in a flakey wireless network connection, stir with a few users who like to simply pull the blue plug out occasionally and for good measure, add a Systems Admin that decides to reboot the SQL server box without warning now and again just to keep everyone on their toes. What are the suggestions and strategies for handling this sort of scenario in respect to: Error Handling - for example, do you wrap every call to the server with a Try/Catch or do you rely on some form of Generic Error Handling to manage this? If so what does it look like? Application Management - for example, do you disable the app and not allow users to interact with it until a connection is detected again? What would you do? | Answer depends on type of your application. There are applications that can work offline - Microsoft Outlook for example. Such applications doesn't treat connectivity exceptions as critical, they can save your work locally and synchronize it later. Another applications such as online games will treat communication problem as critical exception and will quit if connection gets lost. As of error handling, I think that you should control exceptions on all layers rather than relying on some general exception handling piece of code. Your business layer should understand what happened on lower layer (data access layer in our case) and respond correspondingly. Connection lost should not be treated as unexpected exception in my opinion. For good practices of exceptions management I recommend to take a look at Exception Handling Application Block. Concerning application behavior, you should answer yourself on the following question "Does my application have business value for customer in disconnected state?" In many cases it would be beneficial to end user to be able to continues their work in disconnected state. However such behavior tremendously hard to implement. Especially for your scenario Microsoft developed Disconnected Service Agent Application Block | How do you manage your app when the database goes offline? Take a.Net Winforms App.. mix in a flakey wireless network connection, stir with a few users who like to simply pull the blue plug out occasionally and for good measure, add a Systems Admin that decides to reboot the SQL server box without warning now and again just to keep everyone on their toes. What are the suggestions and strategies for handling this sort of scenario in respect to: Error Handling - for example, do you wrap every call to the server with a Try/Catch or do you rely on some form of Generic Error Handling to manage this? If so what does it look like? Application Management - for example, do you disable the app and not allow users to interact with it until a connection is detected again? What would you do? | TITLE:
How do you manage your app when the database goes offline?
QUESTION:
Take a.Net Winforms App.. mix in a flakey wireless network connection, stir with a few users who like to simply pull the blue plug out occasionally and for good measure, add a Systems Admin that decides to reboot the SQL server box without warning now and again just to keep everyone on their toes. What are the suggestions and strategies for handling this sort of scenario in respect to: Error Handling - for example, do you wrap every call to the server with a Try/Catch or do you rely on some form of Generic Error Handling to manage this? If so what does it look like? Application Management - for example, do you disable the app and not allow users to interact with it until a connection is detected again? What would you do?
ANSWER:
Answer depends on type of your application. There are applications that can work offline - Microsoft Outlook for example. Such applications doesn't treat connectivity exceptions as critical, they can save your work locally and synchronize it later. Another applications such as online games will treat communication problem as critical exception and will quit if connection gets lost. As of error handling, I think that you should control exceptions on all layers rather than relying on some general exception handling piece of code. Your business layer should understand what happened on lower layer (data access layer in our case) and respond correspondingly. Connection lost should not be treated as unexpected exception in my opinion. For good practices of exceptions management I recommend to take a look at Exception Handling Application Block. Concerning application behavior, you should answer yourself on the following question "Does my application have business value for customer in disconnected state?" In many cases it would be beneficial to end user to be able to continues their work in disconnected state. However such behavior tremendously hard to implement. Especially for your scenario Microsoft developed Disconnected Service Agent Application Block | [
".net",
"sql-server",
"error-handling"
] | 6 | 3 | 1,137 | 6 | 0 | 2008-09-08T10:25:47.323000 | 2008-09-08T10:59:27.007000 |
49,430 | 57,774 | Animation Extender Problems | I have just started working with the AnimationExtender. I am using it to show a new div with a list gathered from a database when a button is pressed. The problem is the button needs to do a postback to get this list as I don't want to make the call to the database unless it's needed. The postback however stops the animation mid flow and resets it. The button is within an update panel. Ideally I would want the animation to start once the postback is complete and the list has been gathered. I have looked into using the ScriptManager to detect when the postback is complete and have made some progress. I have added two javascript methods to the page. function linkPostback() {
var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(playAnimation) }
function playAnimation() { var onclkBehavior = $find("ctl00_btnOpenList").get_OnClickBehavior().get_animation(); onclkBehavior.play(); } And I’ve changed the btnOpenList.OnClientClick=”linkPostback();” This almost solves the problem. I’m still get some animation stutter. The animation starts to play before the postback and then plays properly after postback. Using the onclkBehavior.pause() has no effect. I can get around this by setting the AnimationExtender.Enabled = false and setting it to true in the buttons postback event. This however works only once as now the AnimationExtender is enabled again. I have also tried disabling the AnimationExtender via javascript but this has no effect. Is there a way of playing the animations only via javascript calls? I need to decouple the automatic link to the buttons click event so I can control when the animation is fired. Hope that makes sense. Thanks DG | The flow you are seeing is something like this: Click on button AnimationExtender catches action and call clickOn callback linkPostback starts asynchronous request for page and then returns flow to AnimationExtender Animation begins pageRequest returns and calls playAnimation, which starts the animation again I think there are at least two ways around this issue. It seems you have almost all the javascript you need, you just need to work around AnimationExtender starting the animation on a click. Option 1: Hide the AnimationExtender button and add a new button of your own that plays the animation. This should be as simple as setting the AE button's style to "display: none;" and having your own button call linkPostback(). Option 2: Re-disable the Animation Extender once the animation has finished with. This should work, as long as the playAnimation call is blocking, which it probably is: function linkPostback() {
var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(playAnimation) }
function playAnimation() {
AnimationExtender.Enabled = true; var onclkBehavior = $find("ctl00_btnOpenList").get_OnClickBehavior().get_animation(); onclkBehavior.play(); AnimationExtender.Enabled = false; } As an aside, it seems your general approach may face issues if there is a delay in receiving the pageRequest. It may be a bit weird to click a button and several seconds later have the animation happen. It may be better to either pre-load the data, or to pre-fill the div with some "Loading..." thing, make it about the right size, and then populate the actual contents when it arrives. | Animation Extender Problems I have just started working with the AnimationExtender. I am using it to show a new div with a list gathered from a database when a button is pressed. The problem is the button needs to do a postback to get this list as I don't want to make the call to the database unless it's needed. The postback however stops the animation mid flow and resets it. The button is within an update panel. Ideally I would want the animation to start once the postback is complete and the list has been gathered. I have looked into using the ScriptManager to detect when the postback is complete and have made some progress. I have added two javascript methods to the page. function linkPostback() {
var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(playAnimation) }
function playAnimation() { var onclkBehavior = $find("ctl00_btnOpenList").get_OnClickBehavior().get_animation(); onclkBehavior.play(); } And I’ve changed the btnOpenList.OnClientClick=”linkPostback();” This almost solves the problem. I’m still get some animation stutter. The animation starts to play before the postback and then plays properly after postback. Using the onclkBehavior.pause() has no effect. I can get around this by setting the AnimationExtender.Enabled = false and setting it to true in the buttons postback event. This however works only once as now the AnimationExtender is enabled again. I have also tried disabling the AnimationExtender via javascript but this has no effect. Is there a way of playing the animations only via javascript calls? I need to decouple the automatic link to the buttons click event so I can control when the animation is fired. Hope that makes sense. Thanks DG | TITLE:
Animation Extender Problems
QUESTION:
I have just started working with the AnimationExtender. I am using it to show a new div with a list gathered from a database when a button is pressed. The problem is the button needs to do a postback to get this list as I don't want to make the call to the database unless it's needed. The postback however stops the animation mid flow and resets it. The button is within an update panel. Ideally I would want the animation to start once the postback is complete and the list has been gathered. I have looked into using the ScriptManager to detect when the postback is complete and have made some progress. I have added two javascript methods to the page. function linkPostback() {
var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(playAnimation) }
function playAnimation() { var onclkBehavior = $find("ctl00_btnOpenList").get_OnClickBehavior().get_animation(); onclkBehavior.play(); } And I’ve changed the btnOpenList.OnClientClick=”linkPostback();” This almost solves the problem. I’m still get some animation stutter. The animation starts to play before the postback and then plays properly after postback. Using the onclkBehavior.pause() has no effect. I can get around this by setting the AnimationExtender.Enabled = false and setting it to true in the buttons postback event. This however works only once as now the AnimationExtender is enabled again. I have also tried disabling the AnimationExtender via javascript but this has no effect. Is there a way of playing the animations only via javascript calls? I need to decouple the automatic link to the buttons click event so I can control when the animation is fired. Hope that makes sense. Thanks DG
ANSWER:
The flow you are seeing is something like this: Click on button AnimationExtender catches action and call clickOn callback linkPostback starts asynchronous request for page and then returns flow to AnimationExtender Animation begins pageRequest returns and calls playAnimation, which starts the animation again I think there are at least two ways around this issue. It seems you have almost all the javascript you need, you just need to work around AnimationExtender starting the animation on a click. Option 1: Hide the AnimationExtender button and add a new button of your own that plays the animation. This should be as simple as setting the AE button's style to "display: none;" and having your own button call linkPostback(). Option 2: Re-disable the Animation Extender once the animation has finished with. This should work, as long as the playAnimation call is blocking, which it probably is: function linkPostback() {
var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(playAnimation) }
function playAnimation() {
AnimationExtender.Enabled = true; var onclkBehavior = $find("ctl00_btnOpenList").get_OnClickBehavior().get_animation(); onclkBehavior.play(); AnimationExtender.Enabled = false; } As an aside, it seems your general approach may face issues if there is a delay in receiving the pageRequest. It may be a bit weird to click a button and several seconds later have the animation happen. It may be better to either pre-load the data, or to pre-fill the div with some "Loading..." thing, make it about the right size, and then populate the actual contents when it arrives. | [
"c#",
"animationextender"
] | 2 | 1 | 3,389 | 2 | 0 | 2008-09-08T10:29:53.943000 | 2008-09-11T22:09:33.987000 |
49,431 | 49,539 | Trigger UpdatePanel on mouse over (as tooltip) | I need to display additional information, like a tooltip, but it's a lot of info (about 500 - 600 characters) on the items in a RadioButtonList. I now trigger the update on a PanelUpdate when the user selects an item in the RadioButtonList, using OnSelectedIndexChanged and AutoPostBack. What I would like to do, is trigger this on onMouseHover (ie. the user holds the mouse a second or two over the item) rather than mouse click but I cannot find a way to do this. | You could try setting an AsyncPostBackTrigger on the updatePanel to watch the value of a hidden field. Then in the javascript onMouseHover event, increment the hidden value. This would fire the AsyncPostBackTrigger, updating the UpdatePanel. | Trigger UpdatePanel on mouse over (as tooltip) I need to display additional information, like a tooltip, but it's a lot of info (about 500 - 600 characters) on the items in a RadioButtonList. I now trigger the update on a PanelUpdate when the user selects an item in the RadioButtonList, using OnSelectedIndexChanged and AutoPostBack. What I would like to do, is trigger this on onMouseHover (ie. the user holds the mouse a second or two over the item) rather than mouse click but I cannot find a way to do this. | TITLE:
Trigger UpdatePanel on mouse over (as tooltip)
QUESTION:
I need to display additional information, like a tooltip, but it's a lot of info (about 500 - 600 characters) on the items in a RadioButtonList. I now trigger the update on a PanelUpdate when the user selects an item in the RadioButtonList, using OnSelectedIndexChanged and AutoPostBack. What I would like to do, is trigger this on onMouseHover (ie. the user holds the mouse a second or two over the item) rather than mouse click but I cannot find a way to do this.
ANSWER:
You could try setting an AsyncPostBackTrigger on the updatePanel to watch the value of a hidden field. Then in the javascript onMouseHover event, increment the hidden value. This would fire the AsyncPostBackTrigger, updating the UpdatePanel. | [
"asp.net",
"javascript",
"asp.net-ajax"
] | 3 | 1 | 1,192 | 1 | 0 | 2008-09-08T10:30:47.920000 | 2008-09-08T11:59:28.907000 |
49,442 | 89,185 | When to create Interface Builder plug-in for custom view? | When do you recommend integrating a custom view into Interface Builder with a plug-in? When skimming through Apple's Interface Builder Plug-In Programming Guide I found: Are your custom objects going to be used by only one application? Do your custom objects rely on state information found only in your application? Would it be problematic to encapsulate your custom views in a standalone library or framework? If you answered yes to any of the preceding questions, your objects may not be good candidates for a plug-in. That answers some of my questions, but I would still like your thoughts on when it's a good idea. What are the benefits and how big of a time investment is it? | It's perfectly reasonable to push the view and controller classes that your application uses out into a separate framework — embedded in your application wrapper — for which you also produce an Interface Builder plug-in. Among other reasons, classes that are commonly used in your application can then be configured at their point of use in Interface Builder, rather than in scattered -awakeFromNib implementations. It's also the only way you can have your objects expose bindings that can be set up in Interface Builder. It's a bit of coding, but for view and controller classes that are used in more than one place, and which require additional set-up before they're actually used, you'll probably save a bunch of time overall. And your experience developing with your own controller and view classes will be like developing with Cocoa's. | When to create Interface Builder plug-in for custom view? When do you recommend integrating a custom view into Interface Builder with a plug-in? When skimming through Apple's Interface Builder Plug-In Programming Guide I found: Are your custom objects going to be used by only one application? Do your custom objects rely on state information found only in your application? Would it be problematic to encapsulate your custom views in a standalone library or framework? If you answered yes to any of the preceding questions, your objects may not be good candidates for a plug-in. That answers some of my questions, but I would still like your thoughts on when it's a good idea. What are the benefits and how big of a time investment is it? | TITLE:
When to create Interface Builder plug-in for custom view?
QUESTION:
When do you recommend integrating a custom view into Interface Builder with a plug-in? When skimming through Apple's Interface Builder Plug-In Programming Guide I found: Are your custom objects going to be used by only one application? Do your custom objects rely on state information found only in your application? Would it be problematic to encapsulate your custom views in a standalone library or framework? If you answered yes to any of the preceding questions, your objects may not be good candidates for a plug-in. That answers some of my questions, but I would still like your thoughts on when it's a good idea. What are the benefits and how big of a time investment is it?
ANSWER:
It's perfectly reasonable to push the view and controller classes that your application uses out into a separate framework — embedded in your application wrapper — for which you also produce an Interface Builder plug-in. Among other reasons, classes that are commonly used in your application can then be configured at their point of use in Interface Builder, rather than in scattered -awakeFromNib implementations. It's also the only way you can have your objects expose bindings that can be set up in Interface Builder. It's a bit of coding, but for view and controller classes that are used in more than one place, and which require additional set-up before they're actually used, you'll probably save a bunch of time overall. And your experience developing with your own controller and view classes will be like developing with Cocoa's. | [
"objective-c",
"cocoa",
"macos",
"interface-builder"
] | 9 | 9 | 3,694 | 2 | 0 | 2008-09-08T10:39:44.950000 | 2008-09-18T01:26:31.450000 |
49,450 | 49,483 | How do I export (and then import) a Subversion repository? | I'm just about wrapped up on a project where I was using a commercial SVN provider to store the source code. The web host the customer ultimately picked includes a repository as part of the hosting package, so, now that the project is over, I'd like to relocate the repository to their web host and discontinue the commercial account. How would I go about doing this? | If you want to move the repository and keep history, you'll probably need filesystem access on both hosts. The simplest solution, if your backend is FSFS (the default on recent versions), is to make a filesystem copy of the entire repository folder. If you have a Berkley DB backend, if you're not sure of what your backend is, or if you're changing SVN version numbers, you're going to want to use svnadmin to dump your old repository and load it into your new repository. Using svnadmin dump will give you a single file backup that you can copy to the new system. Then you can create the new (empty) repository and use svnadmin load, which will essentially replay all the commits along with its metadata (author, timestamp, etc). You can read more about the dump/load process here: http://svnbook.red-bean.com/en/1.8/svn.reposadmin.maint.html#svn.reposadmin.maint.migrate Also, if you do svnadmin load, make sure you use the --force-uuid option, or otherwise people are going to have problems switching to the new repository. Subversion uses a UUID to identify the repository internally, and it won't let you switch a working copy to a different repository. If you don't have filesystem access, there may be other third party options out there (or you can write something) to help you migrate: essentially you'd have to use the svn log to replay each revision on the new repository, and then fix up the metadata afterwards. You'll need the pre-revprop-change and post-revprop-change hook scripts in place to do this, which sort of assumes filesystem access, so YMMV. Or, if you don't want to keep the history, you can use your working copy to import into the new repository. But hopefully this isn't the case. | How do I export (and then import) a Subversion repository? I'm just about wrapped up on a project where I was using a commercial SVN provider to store the source code. The web host the customer ultimately picked includes a repository as part of the hosting package, so, now that the project is over, I'd like to relocate the repository to their web host and discontinue the commercial account. How would I go about doing this? | TITLE:
How do I export (and then import) a Subversion repository?
QUESTION:
I'm just about wrapped up on a project where I was using a commercial SVN provider to store the source code. The web host the customer ultimately picked includes a repository as part of the hosting package, so, now that the project is over, I'd like to relocate the repository to their web host and discontinue the commercial account. How would I go about doing this?
ANSWER:
If you want to move the repository and keep history, you'll probably need filesystem access on both hosts. The simplest solution, if your backend is FSFS (the default on recent versions), is to make a filesystem copy of the entire repository folder. If you have a Berkley DB backend, if you're not sure of what your backend is, or if you're changing SVN version numbers, you're going to want to use svnadmin to dump your old repository and load it into your new repository. Using svnadmin dump will give you a single file backup that you can copy to the new system. Then you can create the new (empty) repository and use svnadmin load, which will essentially replay all the commits along with its metadata (author, timestamp, etc). You can read more about the dump/load process here: http://svnbook.red-bean.com/en/1.8/svn.reposadmin.maint.html#svn.reposadmin.maint.migrate Also, if you do svnadmin load, make sure you use the --force-uuid option, or otherwise people are going to have problems switching to the new repository. Subversion uses a UUID to identify the repository internally, and it won't let you switch a working copy to a different repository. If you don't have filesystem access, there may be other third party options out there (or you can write something) to help you migrate: essentially you'd have to use the svn log to replay each revision on the new repository, and then fix up the metadata afterwards. You'll need the pre-revprop-change and post-revprop-change hook scripts in place to do this, which sort of assumes filesystem access, so YMMV. Or, if you don't want to keep the history, you can use your working copy to import into the new repository. But hopefully this isn't the case. | [
"svn"
] | 86 | 70 | 157,324 | 11 | 0 | 2008-09-08T10:50:39.587000 | 2008-09-08T11:11:30.987000 |
49,456 | 53,044 | How to recover a deleted branch in TFS? | I deleted a branch in TFS and just found out that I need the changes that were on it. How do I recover the branch or the changes done on it? | Specifically in Visual Studio go to "Tools-Options" then Select "Source Control-visual Studio Team Founation Server" and check the "Show deleted items in the Source Control explorer". Having done that - you can then right click a folder and say "Undelete" | How to recover a deleted branch in TFS? I deleted a branch in TFS and just found out that I need the changes that were on it. How do I recover the branch or the changes done on it? | TITLE:
How to recover a deleted branch in TFS?
QUESTION:
I deleted a branch in TFS and just found out that I need the changes that were on it. How do I recover the branch or the changes done on it?
ANSWER:
Specifically in Visual Studio go to "Tools-Options" then Select "Source Control-visual Studio Team Founation Server" and check the "Show deleted items in the Source Control explorer". Having done that - you can then right click a folder and say "Undelete" | [
"version-control",
"tfs"
] | 35 | 60 | 13,718 | 2 | 0 | 2008-09-08T10:55:58.763000 | 2008-09-09T22:25:44.183000 |
49,458 | 49,526 | What's the state of play with "Visual Inheritance" | We have an application that has to be flexible in how it displays it's main form to the user - depending on the user, the form should be slightly different, maybe an extra button here or there, or some other nuance. In order to stop writing code to explicitly remove or add controls etc, I turned to visual inheritance to solve the problem - in what I thought was a neat, clean and logical OO style - turns out that half the time inherited forms have a hard time rendering themeselves in VS for no good reason etc - and I get the feeling that developers and to some extent Microsoft have shunned the practice of Visual Inheritance - can you confirm this, am I missing something here? Regards. | I thought they had more or less sorted the desktop designer issues in 2005. Have you tried the usual culprits? No abstract control types No constructor arguments in any form Initialisation moved to Form_Load as opposed to the Ctor No controls in the same project as the usercontrol/form that they are put inside Close all documents -> Clean -> Rebuild Restart VS I seemed to think that as long as you did all of the above it worked..... mostly. | What's the state of play with "Visual Inheritance" We have an application that has to be flexible in how it displays it's main form to the user - depending on the user, the form should be slightly different, maybe an extra button here or there, or some other nuance. In order to stop writing code to explicitly remove or add controls etc, I turned to visual inheritance to solve the problem - in what I thought was a neat, clean and logical OO style - turns out that half the time inherited forms have a hard time rendering themeselves in VS for no good reason etc - and I get the feeling that developers and to some extent Microsoft have shunned the practice of Visual Inheritance - can you confirm this, am I missing something here? Regards. | TITLE:
What's the state of play with "Visual Inheritance"
QUESTION:
We have an application that has to be flexible in how it displays it's main form to the user - depending on the user, the form should be slightly different, maybe an extra button here or there, or some other nuance. In order to stop writing code to explicitly remove or add controls etc, I turned to visual inheritance to solve the problem - in what I thought was a neat, clean and logical OO style - turns out that half the time inherited forms have a hard time rendering themeselves in VS for no good reason etc - and I get the feeling that developers and to some extent Microsoft have shunned the practice of Visual Inheritance - can you confirm this, am I missing something here? Regards.
ANSWER:
I thought they had more or less sorted the desktop designer issues in 2005. Have you tried the usual culprits? No abstract control types No constructor arguments in any form Initialisation moved to Form_Load as opposed to the Ctor No controls in the same project as the usercontrol/form that they are put inside Close all documents -> Clean -> Rebuild Restart VS I seemed to think that as long as you did all of the above it worked..... mostly. | [
"visual-studio",
"winforms",
"forms",
"visual-inheritance"
] | 8 | 6 | 1,250 | 6 | 0 | 2008-09-08T10:58:06.513000 | 2008-09-08T11:43:39.397000 |
49,461 | 49,479 | VB.NET FormatNumber equivalent in C#? | Is there a C# equivalent for the VB.NET FormatNumber function? I.e.: JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2); | In both C# and VB.NET you can use either the.ToString() function or the String.Format() method to format the text. Using the.ToString() method your example could be written as: JSArrayString += "^" + (inv.RRP * oCountry.ExchangeRate).ToString("#0.00") Alternatively using the String.Format() it could written as: JSArrayString = String.Format("{0}^{1:#0.00}",JSArrayString,(inv.RRP * oCountry.ExchangeRate)) In both of the above cases I have used custom formatting for the currency with # representing an optional place holder and 0 representing a 0 or value if one exists. Other formatting characters can be used to help with formatting such as D2 for 2 decimal places or C to display as currency. In this case you would not want to use the C formatter as this would have inserted the currency symbol and further separators which were not required. See " String.Format("{0}", "formatting string"}; " or " String Format for Int " for more information and examples on how to use String.Format and the different formatting options. | VB.NET FormatNumber equivalent in C#? Is there a C# equivalent for the VB.NET FormatNumber function? I.e.: JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2); | TITLE:
VB.NET FormatNumber equivalent in C#?
QUESTION:
Is there a C# equivalent for the VB.NET FormatNumber function? I.e.: JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2);
ANSWER:
In both C# and VB.NET you can use either the.ToString() function or the String.Format() method to format the text. Using the.ToString() method your example could be written as: JSArrayString += "^" + (inv.RRP * oCountry.ExchangeRate).ToString("#0.00") Alternatively using the String.Format() it could written as: JSArrayString = String.Format("{0}^{1:#0.00}",JSArrayString,(inv.RRP * oCountry.ExchangeRate)) In both of the above cases I have used custom formatting for the currency with # representing an optional place holder and 0 representing a 0 or value if one exists. Other formatting characters can be used to help with formatting such as D2 for 2 decimal places or C to display as currency. In this case you would not want to use the C formatter as this would have inserted the currency symbol and further separators which were not required. See " String.Format("{0}", "formatting string"}; " or " String Format for Int " for more information and examples on how to use String.Format and the different formatting options. | [
"c#",
".net",
"vb.net"
] | 5 | 10 | 16,462 | 4 | 0 | 2008-09-08T10:59:34.433000 | 2008-09-08T11:08:46.737000 |
49,473 | 49,498 | Is Bouncy Castle API Thread Safe? | Is Bouncy Castle API Thread Safe? Especially, org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher org.bouncycastle.crypto.paddings.PKCS7Padding org.bouncycastle.crypto.engines.AESFastEngine org.bouncycastle.crypto.modes.CBCBlockCipher I am planning to write a singleton Spring bean for basic level cryptography support in my app. Since it is a web application, there are greater chances of multiple threads accessing this component at a time. So tread safety is essential here. Please let me know if you have come across such situations using Bouncy Castle. | It really does not matter if the API/Code is thread safe. CBC encryption in itself is not thread safe. Some terminology - E(X) = Enctrypt message X D(X) = Dectrypt X. (Note that D(E(X)) = X) IV = Initialization vector. A random sequence to bootstrap the CBC algorithm CBC = Cipher block chaining. A really simple CBC implementation can look like: P1, P2, P3 = Plain text messages 1. Generate an IV, just random bits. 2. Calculate E( P1 xor IV) call this C1 3. Calculate E( P2 xor C1) call this C2 4. Calculate E( P3 xor C2) call this C3. As you can see, the result of encrypting P1, P2 and P3 (in that order) is different from encrypting P2, P1 and P3 (in that order). So, in a CBC implementation, order is important. Any algorithm where order is important can not, by definition, be thread safe. You can make a Singleton factory that delivers encryption objects, but you cant trust them to be thread safe. | Is Bouncy Castle API Thread Safe? Is Bouncy Castle API Thread Safe? Especially, org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher org.bouncycastle.crypto.paddings.PKCS7Padding org.bouncycastle.crypto.engines.AESFastEngine org.bouncycastle.crypto.modes.CBCBlockCipher I am planning to write a singleton Spring bean for basic level cryptography support in my app. Since it is a web application, there are greater chances of multiple threads accessing this component at a time. So tread safety is essential here. Please let me know if you have come across such situations using Bouncy Castle. | TITLE:
Is Bouncy Castle API Thread Safe?
QUESTION:
Is Bouncy Castle API Thread Safe? Especially, org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher org.bouncycastle.crypto.paddings.PKCS7Padding org.bouncycastle.crypto.engines.AESFastEngine org.bouncycastle.crypto.modes.CBCBlockCipher I am planning to write a singleton Spring bean for basic level cryptography support in my app. Since it is a web application, there are greater chances of multiple threads accessing this component at a time. So tread safety is essential here. Please let me know if you have come across such situations using Bouncy Castle.
ANSWER:
It really does not matter if the API/Code is thread safe. CBC encryption in itself is not thread safe. Some terminology - E(X) = Enctrypt message X D(X) = Dectrypt X. (Note that D(E(X)) = X) IV = Initialization vector. A random sequence to bootstrap the CBC algorithm CBC = Cipher block chaining. A really simple CBC implementation can look like: P1, P2, P3 = Plain text messages 1. Generate an IV, just random bits. 2. Calculate E( P1 xor IV) call this C1 3. Calculate E( P2 xor C1) call this C2 4. Calculate E( P3 xor C2) call this C3. As you can see, the result of encrypting P1, P2 and P3 (in that order) is different from encrypting P2, P1 and P3 (in that order). So, in a CBC implementation, order is important. Any algorithm where order is important can not, by definition, be thread safe. You can make a Singleton factory that delivers encryption objects, but you cant trust them to be thread safe. | [
"java",
"cryptography",
"bouncycastle"
] | 12 | 13 | 5,292 | 2 | 0 | 2008-09-08T11:04:13.190000 | 2008-09-08T11:23:51.583000 |
49,500 | 49,504 | Apache rewrite based on subdomain | I'm trying to redirect requests for a wildcard domain to a sub-directory. ie. something.blah.example.com --> blah.example.com/something I don't know how to get the subdomain name to use in the rewrite rule. Final Solution: RewriteCond %{HTTP_HOST}!^blah\.example\.com RewriteCond %{HTTP_HOST} ^([^.]+) RewriteRule ^(.*) /%1/$1 [L] Or as pointed out by pilif RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.example\.com$ | You should have a look at the URL Rewriting Guide from the apache documentation. The following is untested, but it should to the trick: RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.domain\.com$ RewriteRule ^/(.*)$ http://blah.domain.com/%1/$1 [L,R] This only works if the subdomain contains no dots. Otherwise, you'd have to alter the Regexp in RewriteCond to match any character which should still work due to the anchoring, but this certainly feels safer. | Apache rewrite based on subdomain I'm trying to redirect requests for a wildcard domain to a sub-directory. ie. something.blah.example.com --> blah.example.com/something I don't know how to get the subdomain name to use in the rewrite rule. Final Solution: RewriteCond %{HTTP_HOST}!^blah\.example\.com RewriteCond %{HTTP_HOST} ^([^.]+) RewriteRule ^(.*) /%1/$1 [L] Or as pointed out by pilif RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.example\.com$ | TITLE:
Apache rewrite based on subdomain
QUESTION:
I'm trying to redirect requests for a wildcard domain to a sub-directory. ie. something.blah.example.com --> blah.example.com/something I don't know how to get the subdomain name to use in the rewrite rule. Final Solution: RewriteCond %{HTTP_HOST}!^blah\.example\.com RewriteCond %{HTTP_HOST} ^([^.]+) RewriteRule ^(.*) /%1/$1 [L] Or as pointed out by pilif RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.example\.com$
ANSWER:
You should have a look at the URL Rewriting Guide from the apache documentation. The following is untested, but it should to the trick: RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.domain\.com$ RewriteRule ^/(.*)$ http://blah.domain.com/%1/$1 [L,R] This only works if the subdomain contains no dots. Otherwise, you'd have to alter the Regexp in RewriteCond to match any character which should still work due to the anchoring, but this certainly feels safer. | [
"apache",
"redirect",
"mod-rewrite",
"subdomain",
"wildcard-subdomain"
] | 32 | 36 | 41,752 | 3 | 0 | 2008-09-08T11:24:42.563000 | 2008-09-08T11:30:27.947000 |
49,510 | 49,512 | How do you set your Cocoa application as the default web browser? | How do you set your Cocoa application as the default web browser? I want to create an application that is launched by default when the user clicks on an HTTP or HTTPS link in other applications (Mail, iChat etc.). | There are four steps to making an app that can act as the default web browser. The first three steps allow your app to act as a role handler for the relevant URL schemes (HTTP and HTTPS) and the final step makes it the default role handler for those schemes. 1) Add the URL schemes your app can handle to your application's info.plist file To add support for http:// and https:// you'd need to add the following to your application's info.plist file. This tells the OS that your application is capable of handling HTTP and HTTP URLs. CFBundleURLTypes CFBundleURLName http URL CFBundleURLSchemes http CFBundleURLName Secure http URL CFBundleURLSchemes https 2) Write an URL handler method This method will be called by the OS when it wants to use your application to open a URL. It doesn't matter which object you add this method to, that'll be explicitly passed to the Event Manager in the next step. The URL handler method should look something like this: - (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent { // Get the URL NSString *urlStr = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
//TODO: Your custom URL handling code here } 3) Register the URL handler method Next, tell the event manager which object and method to call when it wants to use your app to load an URL. In the code here I'm passed self as the event handler, assuming that we're calling setEventHandler from the same object that defines the getUrl:withReplyEvent: method. You should add this code somewhere in your application's initialisation code. NSAppleEventManager *em = [NSAppleEventManager sharedAppleEventManager]; [em setEventHandler:self andSelector:@selector(getUrl:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL]; Some applications, including early versions of Adobe AIR, use the alternative WWW!/OURL AppleEvent to request that an application opens URLs, so to be compatible with those applications you should also add the following: [em setEventHandler:self andSelector:@selector(getUrl:withReplyEvent:) forEventClass:'WWW!' andEventID:'OURL']; 4) Set your app as the default browser Everything we've done so far as told the OS that your application is a browser, now we need to make it the default browser. We've got to use the Launch Services API to do this. In this case we're setting our app to be the default role handler for HTTP and HTTPS links: CFStringRef bundleID = (CFStringRef)[[NSBundle mainBundle] bundleIdentifier]; OSStatus httpResult = LSSetDefaultHandlerForURLScheme(CFSTR("http"), bundleID); OSStatus httpsResult = LSSetDefaultHandlerForURLScheme(CFSTR("https"), bundleID); //TODO: Check httpResult and httpsResult for errors (It's probably best to ask the user's permission before changing their default browser.) Custom URL schemes It's worth noting that you can also use these same steps to handle your own custom URL schemes. If you're creating a custom URL scheme it's a good idea to base it on your app's bundle identifier to avoid clashes with other apps. So if your bundle ID is com.example.MyApp you should consider using x-com-example-myapp:// URLs. | How do you set your Cocoa application as the default web browser? How do you set your Cocoa application as the default web browser? I want to create an application that is launched by default when the user clicks on an HTTP or HTTPS link in other applications (Mail, iChat etc.). | TITLE:
How do you set your Cocoa application as the default web browser?
QUESTION:
How do you set your Cocoa application as the default web browser? I want to create an application that is launched by default when the user clicks on an HTTP or HTTPS link in other applications (Mail, iChat etc.).
ANSWER:
There are four steps to making an app that can act as the default web browser. The first three steps allow your app to act as a role handler for the relevant URL schemes (HTTP and HTTPS) and the final step makes it the default role handler for those schemes. 1) Add the URL schemes your app can handle to your application's info.plist file To add support for http:// and https:// you'd need to add the following to your application's info.plist file. This tells the OS that your application is capable of handling HTTP and HTTP URLs. CFBundleURLTypes CFBundleURLName http URL CFBundleURLSchemes http CFBundleURLName Secure http URL CFBundleURLSchemes https 2) Write an URL handler method This method will be called by the OS when it wants to use your application to open a URL. It doesn't matter which object you add this method to, that'll be explicitly passed to the Event Manager in the next step. The URL handler method should look something like this: - (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent { // Get the URL NSString *urlStr = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
//TODO: Your custom URL handling code here } 3) Register the URL handler method Next, tell the event manager which object and method to call when it wants to use your app to load an URL. In the code here I'm passed self as the event handler, assuming that we're calling setEventHandler from the same object that defines the getUrl:withReplyEvent: method. You should add this code somewhere in your application's initialisation code. NSAppleEventManager *em = [NSAppleEventManager sharedAppleEventManager]; [em setEventHandler:self andSelector:@selector(getUrl:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL]; Some applications, including early versions of Adobe AIR, use the alternative WWW!/OURL AppleEvent to request that an application opens URLs, so to be compatible with those applications you should also add the following: [em setEventHandler:self andSelector:@selector(getUrl:withReplyEvent:) forEventClass:'WWW!' andEventID:'OURL']; 4) Set your app as the default browser Everything we've done so far as told the OS that your application is a browser, now we need to make it the default browser. We've got to use the Launch Services API to do this. In this case we're setting our app to be the default role handler for HTTP and HTTPS links: CFStringRef bundleID = (CFStringRef)[[NSBundle mainBundle] bundleIdentifier]; OSStatus httpResult = LSSetDefaultHandlerForURLScheme(CFSTR("http"), bundleID); OSStatus httpsResult = LSSetDefaultHandlerForURLScheme(CFSTR("https"), bundleID); //TODO: Check httpResult and httpsResult for errors (It's probably best to ask the user's permission before changing their default browser.) Custom URL schemes It's worth noting that you can also use these same steps to handle your own custom URL schemes. If you're creating a custom URL scheme it's a good idea to base it on your app's bundle identifier to avoid clashes with other apps. So if your bundle ID is com.example.MyApp you should consider using x-com-example-myapp:// URLs. | [
"objective-c",
"cocoa"
] | 39 | 81 | 14,719 | 4 | 0 | 2008-09-08T11:32:29.503000 | 2008-09-08T11:33:41.763000 |
49,511 | 49,523 | Using a wiki as a central development project repository | I have played with the idea of using a wiki (MediaWiki) to centralize all project information for a development project. This was done using extensions that pull information from SVN (using SVNKit ) and by linking to Bugzilla to extract work assigned to a developer or work remaining for a release. Examples: would return a summary would return Do you think that this would be useful? If so then what other integrations would you think would be valuable? | I think this would be extremly useful. Depending on the size of a project team members come and go. And a wiki is a good tool to keep the history and the "spirit" of a project available to new team members. I did that in many projects, and though the projects were already finished, all the informations are available. One more idea: also try to integrate meeting schedules, minutes etc. If your team communicates via IM, try to integrate a log of the conversations. | Using a wiki as a central development project repository I have played with the idea of using a wiki (MediaWiki) to centralize all project information for a development project. This was done using extensions that pull information from SVN (using SVNKit ) and by linking to Bugzilla to extract work assigned to a developer or work remaining for a release. Examples: would return a summary would return Do you think that this would be useful? If so then what other integrations would you think would be valuable? | TITLE:
Using a wiki as a central development project repository
QUESTION:
I have played with the idea of using a wiki (MediaWiki) to centralize all project information for a development project. This was done using extensions that pull information from SVN (using SVNKit ) and by linking to Bugzilla to extract work assigned to a developer or work remaining for a release. Examples: would return a summary would return Do you think that this would be useful? If so then what other integrations would you think would be valuable?
ANSWER:
I think this would be extremly useful. Depending on the size of a project team members come and go. And a wiki is a good tool to keep the history and the "spirit" of a project available to new team members. I did that in many projects, and though the projects were already finished, all the informations are available. One more idea: also try to integrate meeting schedules, minutes etc. If your team communicates via IM, try to integrate a log of the conversations. | [
"svn",
"integration",
"wiki",
"projects",
"bugzilla"
] | 7 | 3 | 1,385 | 5 | 0 | 2008-09-08T11:32:49.517000 | 2008-09-08T11:38:13.187000 |
49,547 | 2,068,407 | How do we control web page caching, across all browsers? | Our investigations have shown us that not all browsers respect the HTTP cache directives in a uniform manner. For security reasons we do not want certain pages in our application to be cached, ever, by the web browser. This must work for at least the following browsers: Internet Explorer 6+ Firefox 1.5+ Safari 3+ Opera 9+ Chrome Our requirement came from a security test. After logging out from our website you could press the back button and view cached pages. | Introduction The correct minimum set of headers that works across all mentioned clients (and proxies): Cache-Control: no-cache, no-store, must-revalidate Pragma: no-cache Expires: 0 The Cache-Control is per the HTTP 1.1 spec for clients and proxies (and implicitly required by some clients next to Expires ). The Pragma is per the HTTP 1.0 spec for prehistoric clients. The Expires is per the HTTP 1.0 and 1.1 specs for clients and proxies. In HTTP 1.1, the Cache-Control takes precedence over Expires, so it's after all for HTTP 1.0 proxies only. If you don't care about IE6 and its broken caching when serving pages over HTTPS with only no-store, then you could omit Cache-Control: no-cache. Cache-Control: no-store, must-revalidate Pragma: no-cache Expires: 0 If you don't care about IE6 nor HTTP 1.0 clients (HTTP 1.1 was introduced in 1997), then you could omit Pragma. Cache-Control: no-store, must-revalidate Expires: 0 If you don't care about HTTP 1.0 proxies either, then you could omit Expires. Cache-Control: no-store, must-revalidate On the other hand, if the server auto-includes a valid Date header, then you could theoretically omit Cache-Control too and rely on Expires only. Date: Wed, 24 Aug 2016 18:32:02 GMT Expires: 0 But that may fail if e.g. the end-user manipulates the operating system date and the client software is relying on it. Other Cache-Control parameters such as max-age are irrelevant if the abovementioned Cache-Control parameters are specified. The Last-Modified header as included in most other answers here is only interesting if you actually want to cache the request, so you don't need to specify it at all. How to set it? Using PHP: header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1. header("Pragma: no-cache"); // HTTP 1.0. header("Expires: 0"); // Proxies. Using Java Servlet, or Node.js: response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. response.setHeader("Pragma", "no-cache"); // HTTP 1.0. response.setHeader("Expires", "0"); // Proxies. Using ASP.NET-MVC Response.Cache.SetCacheability(HttpCacheability.NoCache); // HTTP 1.1. Response.Cache.AppendCacheExtension("no-store, must-revalidate"); Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0. Response.AppendHeader("Expires", "0"); // Proxies. Using ASP.NET Web API: // `response` is an instance of System.Net.Http.HttpResponseMessage response.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true, NoStore = true, MustRevalidate = true }; response.Headers.Pragma.ParseAdd("no-cache"); // We can't use `response.Content.Headers.Expires` directly // since it allows only `DateTimeOffset?` values. response.Content?.Headers.TryAddWithoutValidation("Expires", 0.ToString()); Using ASP.NET: Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0. Response.AppendHeader("Expires", "0"); // Proxies. Using ASP.NET Core v3 // using Microsoft.Net.Http.Headers Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate"; Response.Headers[HeaderNames.Expires] = "0"; Response.Headers[HeaderNames.Pragma] = "no-cache"; Using ASP: Response.addHeader "Cache-Control", "no-cache, no-store, must-revalidate" ' HTTP 1.1. Response.addHeader "Pragma", "no-cache" ' HTTP 1.0. Response.addHeader "Expires", "0" ' Proxies. Using Ruby on Rails: headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1. headers["Pragma"] = "no-cache" # HTTP 1.0. headers["Expires"] = "0" # Proxies. Using Python/Flask: response = make_response(render_template(...)) response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1. response.headers["Pragma"] = "no-cache" # HTTP 1.0. response.headers["Expires"] = "0" # Proxies. Using Python/Django: response["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1. response["Pragma"] = "no-cache" # HTTP 1.0. response["Expires"] = "0" # Proxies. Using Python/Pyramid: request.response.headerlist.extend( ( ('Cache-Control', 'no-cache, no-store, must-revalidate'), ('Pragma', 'no-cache'), ('Expires', '0') ) ) Using Go: responseWriter.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1. responseWriter.Header().Set("Pragma", "no-cache") // HTTP 1.0. responseWriter.Header().Set("Expires", "0") // Proxies. Using Clojure (require Ring utils): (require '[ring.util.response:as r]) (-> response (r/header "Cache-Control" "no-cache, no-store, must-revalidate") (r/header "Pragma" "no-cache") (r/header "Expires" 0)) Using Apache.htaccess file: Header set Cache-Control "no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires 0 Using Firebase Hosting firebase.json: "headers": [ { "key": "Cache-Control", "value": "no-cache, no-store, must-revalidate" }, { "key": "Pragma", "value": "no-cache" }, { "key": "Expires", "value": "0" } ] Using HTML: HTML meta tags vs HTTP response headers Important to know is that when an HTML page is served over an HTTP connection, and a header is present in both the HTTP response headers and the HTML tags, then the one specified in the HTTP response header will get precedence over the HTML meta tag. The HTML meta tag will only be used when the page is viewed from a local disk file system via a file:// URL. See also W3 HTML spec chapter 5.2.2. Take care with this when you don't specify them programmatically because the webserver can namely include some default values. Generally, you'd better just not specify the HTML meta tags to avoid confusion by starters and rely on hard HTTP response headers. Moreover, specifically those tags are invalid in HTML5. Only the http-equiv values listed in HTML5 specification are allowed. Verifying the actual HTTP response headers To verify the one and the other, you can see/debug them in the HTTP traffic monitor of the web browser's developer toolset. You can get there by pressing F12 in Chrome/Firefox23+/IE9+, and then opening the "Network" or "Net" tab panel, and then clicking the HTTP request of interest to uncover all detail about the HTTP request and response. The below screenshot is from Chrome: I want to set those headers on file downloads too First of all, this question and answer are targeted on "web pages" (HTML pages), not "file downloads" (PDF, zip, Excel, etc). You'd better have them cached and make use of some file version identifier somewhere in the URI path or query string to force a redownload on a changed file. When applying those no-cache headers on file downloads anyway, then beware of the IE7/8 bug when serving a file download over HTTPS instead of HTTP. For detail, see IE cannot download foo.jsf. IE was not able to open this internet site. The requested site is either unavailable or cannot be found. | How do we control web page caching, across all browsers? Our investigations have shown us that not all browsers respect the HTTP cache directives in a uniform manner. For security reasons we do not want certain pages in our application to be cached, ever, by the web browser. This must work for at least the following browsers: Internet Explorer 6+ Firefox 1.5+ Safari 3+ Opera 9+ Chrome Our requirement came from a security test. After logging out from our website you could press the back button and view cached pages. | TITLE:
How do we control web page caching, across all browsers?
QUESTION:
Our investigations have shown us that not all browsers respect the HTTP cache directives in a uniform manner. For security reasons we do not want certain pages in our application to be cached, ever, by the web browser. This must work for at least the following browsers: Internet Explorer 6+ Firefox 1.5+ Safari 3+ Opera 9+ Chrome Our requirement came from a security test. After logging out from our website you could press the back button and view cached pages.
ANSWER:
Introduction The correct minimum set of headers that works across all mentioned clients (and proxies): Cache-Control: no-cache, no-store, must-revalidate Pragma: no-cache Expires: 0 The Cache-Control is per the HTTP 1.1 spec for clients and proxies (and implicitly required by some clients next to Expires ). The Pragma is per the HTTP 1.0 spec for prehistoric clients. The Expires is per the HTTP 1.0 and 1.1 specs for clients and proxies. In HTTP 1.1, the Cache-Control takes precedence over Expires, so it's after all for HTTP 1.0 proxies only. If you don't care about IE6 and its broken caching when serving pages over HTTPS with only no-store, then you could omit Cache-Control: no-cache. Cache-Control: no-store, must-revalidate Pragma: no-cache Expires: 0 If you don't care about IE6 nor HTTP 1.0 clients (HTTP 1.1 was introduced in 1997), then you could omit Pragma. Cache-Control: no-store, must-revalidate Expires: 0 If you don't care about HTTP 1.0 proxies either, then you could omit Expires. Cache-Control: no-store, must-revalidate On the other hand, if the server auto-includes a valid Date header, then you could theoretically omit Cache-Control too and rely on Expires only. Date: Wed, 24 Aug 2016 18:32:02 GMT Expires: 0 But that may fail if e.g. the end-user manipulates the operating system date and the client software is relying on it. Other Cache-Control parameters such as max-age are irrelevant if the abovementioned Cache-Control parameters are specified. The Last-Modified header as included in most other answers here is only interesting if you actually want to cache the request, so you don't need to specify it at all. How to set it? Using PHP: header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1. header("Pragma: no-cache"); // HTTP 1.0. header("Expires: 0"); // Proxies. Using Java Servlet, or Node.js: response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. response.setHeader("Pragma", "no-cache"); // HTTP 1.0. response.setHeader("Expires", "0"); // Proxies. Using ASP.NET-MVC Response.Cache.SetCacheability(HttpCacheability.NoCache); // HTTP 1.1. Response.Cache.AppendCacheExtension("no-store, must-revalidate"); Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0. Response.AppendHeader("Expires", "0"); // Proxies. Using ASP.NET Web API: // `response` is an instance of System.Net.Http.HttpResponseMessage response.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true, NoStore = true, MustRevalidate = true }; response.Headers.Pragma.ParseAdd("no-cache"); // We can't use `response.Content.Headers.Expires` directly // since it allows only `DateTimeOffset?` values. response.Content?.Headers.TryAddWithoutValidation("Expires", 0.ToString()); Using ASP.NET: Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0. Response.AppendHeader("Expires", "0"); // Proxies. Using ASP.NET Core v3 // using Microsoft.Net.Http.Headers Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate"; Response.Headers[HeaderNames.Expires] = "0"; Response.Headers[HeaderNames.Pragma] = "no-cache"; Using ASP: Response.addHeader "Cache-Control", "no-cache, no-store, must-revalidate" ' HTTP 1.1. Response.addHeader "Pragma", "no-cache" ' HTTP 1.0. Response.addHeader "Expires", "0" ' Proxies. Using Ruby on Rails: headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1. headers["Pragma"] = "no-cache" # HTTP 1.0. headers["Expires"] = "0" # Proxies. Using Python/Flask: response = make_response(render_template(...)) response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1. response.headers["Pragma"] = "no-cache" # HTTP 1.0. response.headers["Expires"] = "0" # Proxies. Using Python/Django: response["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1. response["Pragma"] = "no-cache" # HTTP 1.0. response["Expires"] = "0" # Proxies. Using Python/Pyramid: request.response.headerlist.extend( ( ('Cache-Control', 'no-cache, no-store, must-revalidate'), ('Pragma', 'no-cache'), ('Expires', '0') ) ) Using Go: responseWriter.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1. responseWriter.Header().Set("Pragma", "no-cache") // HTTP 1.0. responseWriter.Header().Set("Expires", "0") // Proxies. Using Clojure (require Ring utils): (require '[ring.util.response:as r]) (-> response (r/header "Cache-Control" "no-cache, no-store, must-revalidate") (r/header "Pragma" "no-cache") (r/header "Expires" 0)) Using Apache.htaccess file: Header set Cache-Control "no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires 0 Using Firebase Hosting firebase.json: "headers": [ { "key": "Cache-Control", "value": "no-cache, no-store, must-revalidate" }, { "key": "Pragma", "value": "no-cache" }, { "key": "Expires", "value": "0" } ] Using HTML: HTML meta tags vs HTTP response headers Important to know is that when an HTML page is served over an HTTP connection, and a header is present in both the HTTP response headers and the HTML tags, then the one specified in the HTTP response header will get precedence over the HTML meta tag. The HTML meta tag will only be used when the page is viewed from a local disk file system via a file:// URL. See also W3 HTML spec chapter 5.2.2. Take care with this when you don't specify them programmatically because the webserver can namely include some default values. Generally, you'd better just not specify the HTML meta tags to avoid confusion by starters and rely on hard HTTP response headers. Moreover, specifically those tags are invalid in HTML5. Only the http-equiv values listed in HTML5 specification are allowed. Verifying the actual HTTP response headers To verify the one and the other, you can see/debug them in the HTTP traffic monitor of the web browser's developer toolset. You can get there by pressing F12 in Chrome/Firefox23+/IE9+, and then opening the "Network" or "Net" tab panel, and then clicking the HTTP request of interest to uncover all detail about the HTTP request and response. The below screenshot is from Chrome: I want to set those headers on file downloads too First of all, this question and answer are targeted on "web pages" (HTML pages), not "file downloads" (PDF, zip, Excel, etc). You'd better have them cached and make use of some file version identifier somewhere in the URI path or query string to force a redownload on a changed file. When applying those no-cache headers on file downloads anyway, then beware of the IE7/8 bug when serving a file download over HTTPS instead of HTTP. For detail, see IE cannot download foo.jsf. IE was not able to open this internet site. The requested site is either unavailable or cannot be found. | [
"http",
"caching",
"https",
"http-headers",
"cross-browser"
] | 1,894 | 3,145 | 1,274,723 | 30 | 0 | 2008-09-08T12:08:49.213000 | 2010-01-14T23:50:18.593000 |
49,551 | 49,609 | LINQ and Database Permissions | I'm still trying to get my head around LINQ and accessing a SQL Database. I was always taught that you should only have execute permissions of stored procedures to your data. You should never have select / insert / update / delete. (This is because of performance and security) To get the data out of LINQ you obviously need select permissions. I know you can use stored procs with LINQ, but since I can't do joins what's the point? Have I missed something??? | 1) We're programmers, not DBA fascists. If your requirements state that the database must be locked down 100%, Linq is not for you. I'm not a DBA, so I believe that most of the performance/security hype is just that. Linq is for me. 2) You can do joins with linq. @Philippe: Linq automatically transforms evaluations into query parameters, so it provides some sql injection protection. However, you still have to closely evaluate your requirements to determine how much security you need and at what levels. Linq makes dealing with the database much easier, but it makes it easier to put secuirty design on the back burner, which is a bad thing. | LINQ and Database Permissions I'm still trying to get my head around LINQ and accessing a SQL Database. I was always taught that you should only have execute permissions of stored procedures to your data. You should never have select / insert / update / delete. (This is because of performance and security) To get the data out of LINQ you obviously need select permissions. I know you can use stored procs with LINQ, but since I can't do joins what's the point? Have I missed something??? | TITLE:
LINQ and Database Permissions
QUESTION:
I'm still trying to get my head around LINQ and accessing a SQL Database. I was always taught that you should only have execute permissions of stored procedures to your data. You should never have select / insert / update / delete. (This is because of performance and security) To get the data out of LINQ you obviously need select permissions. I know you can use stored procs with LINQ, but since I can't do joins what's the point? Have I missed something???
ANSWER:
1) We're programmers, not DBA fascists. If your requirements state that the database must be locked down 100%, Linq is not for you. I'm not a DBA, so I believe that most of the performance/security hype is just that. Linq is for me. 2) You can do joins with linq. @Philippe: Linq automatically transforms evaluations into query parameters, so it provides some sql injection protection. However, you still have to closely evaluate your requirements to determine how much security you need and at what levels. Linq makes dealing with the database much easier, but it makes it easier to put secuirty design on the back burner, which is a bad thing. | [
"linq-to-sql",
"permissions"
] | 2 | 2 | 1,726 | 4 | 0 | 2008-09-08T12:15:05.563000 | 2008-09-08T12:49:51.393000 |
49,562 | 63,996 | Where do I start designing a Custom Control that contains child objects? | I think this is a fun engineering-level question. I need to design a control which displays a line chart. What I want to be able to do is use a designer to add multiple Pens which actually describe the data and presentation so that it ends up with Xaml something along these lines:... My first thought is to extend ItemsControl for the Chart class. Will that get me where I want to go or should I be looking at it from a different direction such as extending Panel? The major requirement is to be able to use it in a designer without adding any C# code. In order for that to even be feasible, it needs to retain its structure in the tree-view model. In other words, if I were working with this in Expression Blend or Mobiform Aurora, I would be able to select the chart from the logical tree or select any of the individual pens to edit their properties. | I would go with Chart as an ItemsControl and its ItemsPanel be a Canvas(For some light use I would go with Grid as ItemsPanel). And each Pen will be a CustomControl derived from PolyLine class. Does that make any sense? | Where do I start designing a Custom Control that contains child objects? I think this is a fun engineering-level question. I need to design a control which displays a line chart. What I want to be able to do is use a designer to add multiple Pens which actually describe the data and presentation so that it ends up with Xaml something along these lines:... My first thought is to extend ItemsControl for the Chart class. Will that get me where I want to go or should I be looking at it from a different direction such as extending Panel? The major requirement is to be able to use it in a designer without adding any C# code. In order for that to even be feasible, it needs to retain its structure in the tree-view model. In other words, if I were working with this in Expression Blend or Mobiform Aurora, I would be able to select the chart from the logical tree or select any of the individual pens to edit their properties. | TITLE:
Where do I start designing a Custom Control that contains child objects?
QUESTION:
I think this is a fun engineering-level question. I need to design a control which displays a line chart. What I want to be able to do is use a designer to add multiple Pens which actually describe the data and presentation so that it ends up with Xaml something along these lines:... My first thought is to extend ItemsControl for the Chart class. Will that get me where I want to go or should I be looking at it from a different direction such as extending Panel? The major requirement is to be able to use it in a designer without adding any C# code. In order for that to even be feasible, it needs to retain its structure in the tree-view model. In other words, if I were working with this in Expression Blend or Mobiform Aurora, I would be able to select the chart from the logical tree or select any of the individual pens to edit their properties.
ANSWER:
I would go with Chart as an ItemsControl and its ItemsPanel be a Canvas(For some light use I would go with Grid as ItemsPanel). And each Pen will be a CustomControl derived from PolyLine class. Does that make any sense? | [
"wpf",
"xaml"
] | 2 | 2 | 640 | 3 | 0 | 2008-09-08T12:22:31.457000 | 2008-09-15T15:34:23.933000 |
49,564 | 49,590 | How to implement file upload progress bar on web? | I would like display something more meaningful that animated gif while users upload file to my web application. What possibilities do I have? Edit: I am using.Net but I don't mind if somebody shows me platform agnostic version. | Here are a couple of versions of what you're looking for for some common JavaScript toolkits. Mootools - http://digitarald.de/project/fancyupload/ Extjs - http://extjs.com/learn/Extension:UploadForm | How to implement file upload progress bar on web? I would like display something more meaningful that animated gif while users upload file to my web application. What possibilities do I have? Edit: I am using.Net but I don't mind if somebody shows me platform agnostic version. | TITLE:
How to implement file upload progress bar on web?
QUESTION:
I would like display something more meaningful that animated gif while users upload file to my web application. What possibilities do I have? Edit: I am using.Net but I don't mind if somebody shows me platform agnostic version.
ANSWER:
Here are a couple of versions of what you're looking for for some common JavaScript toolkits. Mootools - http://digitarald.de/project/fancyupload/ Extjs - http://extjs.com/learn/Extension:UploadForm | [
".net",
"javascript",
"ajax"
] | 19 | 5 | 20,671 | 7 | 0 | 2008-09-08T12:24:25.103000 | 2008-09-08T12:41:40.880000 |
49,582 | 49,585 | Re-Running Database Development Scripts | In our current database development evironment we have automated build procceses check all the sql code out of svn create database scripts and apply them to the various development/qa databases. This is all well and good, and is a tremdous improvement over what we did in the past, but we have a problem with rerunning scripts. Obviously this isn't a problem with some scripts like altering procedures, because you can run them over and over without adversly affecting the system. Right now to add metadata and run statements like create/alter table statements we add code to check and see if the objects exists, and if they do, don't run them. Our problem is that we really only get one shot to run the script, because once the script has been run, the objects are in the environment and system won't run the script again. If something needs to change once it's been deployed, we have a difficult process of running update scripts agaist the update scripts and hoping that everything falls in the correct order and all of the PKs line up between the environments (the databases are, shall we say, "special"). Short of dropping the database and starting the process from scratch (the last most current release), does anyone have a more elegant solution to this? | I'm not sure how best to approach the problem in your specific environment, but I'd suggest reading up on Rail's migrations feature for some inspiration on how to get started. http://wiki.rubyonrails.org/rails/pages/UnderstandingMigrations | Re-Running Database Development Scripts In our current database development evironment we have automated build procceses check all the sql code out of svn create database scripts and apply them to the various development/qa databases. This is all well and good, and is a tremdous improvement over what we did in the past, but we have a problem with rerunning scripts. Obviously this isn't a problem with some scripts like altering procedures, because you can run them over and over without adversly affecting the system. Right now to add metadata and run statements like create/alter table statements we add code to check and see if the objects exists, and if they do, don't run them. Our problem is that we really only get one shot to run the script, because once the script has been run, the objects are in the environment and system won't run the script again. If something needs to change once it's been deployed, we have a difficult process of running update scripts agaist the update scripts and hoping that everything falls in the correct order and all of the PKs line up between the environments (the databases are, shall we say, "special"). Short of dropping the database and starting the process from scratch (the last most current release), does anyone have a more elegant solution to this? | TITLE:
Re-Running Database Development Scripts
QUESTION:
In our current database development evironment we have automated build procceses check all the sql code out of svn create database scripts and apply them to the various development/qa databases. This is all well and good, and is a tremdous improvement over what we did in the past, but we have a problem with rerunning scripts. Obviously this isn't a problem with some scripts like altering procedures, because you can run them over and over without adversly affecting the system. Right now to add metadata and run statements like create/alter table statements we add code to check and see if the objects exists, and if they do, don't run them. Our problem is that we really only get one shot to run the script, because once the script has been run, the objects are in the environment and system won't run the script again. If something needs to change once it's been deployed, we have a difficult process of running update scripts agaist the update scripts and hoping that everything falls in the correct order and all of the PKs line up between the environments (the databases are, shall we say, "special"). Short of dropping the database and starting the process from scratch (the last most current release), does anyone have a more elegant solution to this?
ANSWER:
I'm not sure how best to approach the problem in your specific environment, but I'd suggest reading up on Rail's migrations feature for some inspiration on how to get started. http://wiki.rubyonrails.org/rails/pages/UnderstandingMigrations | [
"sql-server",
"database",
"version-control",
"sdlc"
] | 2 | 2 | 589 | 6 | 0 | 2008-09-08T12:34:47.763000 | 2008-09-08T12:38:15.147000 |
49,596 | 49,620 | String initialization with and without explicit trailing terminator | What is the difference between char str1[32] = "\0"; and char str2[32] = ""; | Since you already declared the sizes, the two declarations are exactly equal. However, if you do not specify the sizes, you can see that the first declaration makes a larger string: char a[] = "a\0"; char b[] = "a";
printf("%i %i\n", sizeof(a), sizeof(b)); prints 3 2 This is because a ends with two nulls (the explicit one and the implicit one) while b ends only with the implicit one. | String initialization with and without explicit trailing terminator What is the difference between char str1[32] = "\0"; and char str2[32] = ""; | TITLE:
String initialization with and without explicit trailing terminator
QUESTION:
What is the difference between char str1[32] = "\0"; and char str2[32] = "";
ANSWER:
Since you already declared the sizes, the two declarations are exactly equal. However, if you do not specify the sizes, you can see that the first declaration makes a larger string: char a[] = "a\0"; char b[] = "a";
printf("%i %i\n", sizeof(a), sizeof(b)); prints 3 2 This is because a ends with two nulls (the explicit one and the implicit one) while b ends only with the implicit one. | [
"c"
] | 15 | 23 | 9,989 | 4 | 0 | 2008-09-08T12:45:16.660000 | 2008-09-08T12:53:59.167000 |
49,599 | 49,654 | Binding custom functions to DOM events in prototype? | Jquery has a great language construct that looks like this: $(document).ready(function() { $("a").click(function() { alert("Hello world!"); }); }); As you might guess this, once the document has loaded, binds a custom function to the onClick event of all a tags. The question is, how can I achieve this same kind of behavior in Prototype? | Prototype 1.6 provides the dom:loaded event on document: document.observe("dom:loaded", function() { $$('a').each(function(elem) { elem.observe("click", function() { alert("Hello World"); }); }); }); I also use the each iterator on the array returned by $$(). | Binding custom functions to DOM events in prototype? Jquery has a great language construct that looks like this: $(document).ready(function() { $("a").click(function() { alert("Hello world!"); }); }); As you might guess this, once the document has loaded, binds a custom function to the onClick event of all a tags. The question is, how can I achieve this same kind of behavior in Prototype? | TITLE:
Binding custom functions to DOM events in prototype?
QUESTION:
Jquery has a great language construct that looks like this: $(document).ready(function() { $("a").click(function() { alert("Hello world!"); }); }); As you might guess this, once the document has loaded, binds a custom function to the onClick event of all a tags. The question is, how can I achieve this same kind of behavior in Prototype?
ANSWER:
Prototype 1.6 provides the dom:loaded event on document: document.observe("dom:loaded", function() { $$('a').each(function(elem) { elem.observe("click", function() { alert("Hello World"); }); }); }); I also use the each iterator on the array returned by $$(). | [
"javascript",
"dom",
"prototypejs"
] | 3 | 8 | 8,078 | 3 | 0 | 2008-09-08T12:46:08.873000 | 2008-09-08T13:03:10.877000 |
49,601 | 49,606 | Is there a barebones Windows version control system that's suitable for only one guy? | I'm trying to find a source control for my own personal use that's as simple as possible. The main feature I need is being able to read/pull a past version of my code. I am the only developer. I've looked at a lot of different version control systems, but they all seem way more complicated than I need. I need one that's simple, runs under Windows, and doesn't expose itself to the network. Specifically, the version control system should not require exposing an HTTP interface, it should interact with the local filesystem only. It just needs to be a version control system geared for one guy and one guy only. Graphical UI is a plus. Does anyone know of software would satisfy what I'm looking for? Thanks! -Mike | Subversion is great -- you can run the server yourself or use something like assembla.com to host your code (although that exposes it to the network). There are numerous gui applications like tortoise svn that would allow you to interact w/ the source control repo | Is there a barebones Windows version control system that's suitable for only one guy? I'm trying to find a source control for my own personal use that's as simple as possible. The main feature I need is being able to read/pull a past version of my code. I am the only developer. I've looked at a lot of different version control systems, but they all seem way more complicated than I need. I need one that's simple, runs under Windows, and doesn't expose itself to the network. Specifically, the version control system should not require exposing an HTTP interface, it should interact with the local filesystem only. It just needs to be a version control system geared for one guy and one guy only. Graphical UI is a plus. Does anyone know of software would satisfy what I'm looking for? Thanks! -Mike | TITLE:
Is there a barebones Windows version control system that's suitable for only one guy?
QUESTION:
I'm trying to find a source control for my own personal use that's as simple as possible. The main feature I need is being able to read/pull a past version of my code. I am the only developer. I've looked at a lot of different version control systems, but they all seem way more complicated than I need. I need one that's simple, runs under Windows, and doesn't expose itself to the network. Specifically, the version control system should not require exposing an HTTP interface, it should interact with the local filesystem only. It just needs to be a version control system geared for one guy and one guy only. Graphical UI is a plus. Does anyone know of software would satisfy what I'm looking for? Thanks! -Mike
ANSWER:
Subversion is great -- you can run the server yourself or use something like assembla.com to host your code (although that exposes it to the network). There are numerous gui applications like tortoise svn that would allow you to interact w/ the source control repo | [
"windows",
"version-control"
] | 33 | 40 | 21,491 | 26 | 0 | 2008-09-08T12:46:57.670000 | 2008-09-08T12:49:13.780000 |
49,602 | 49,604 | How to limit result set size for arbitrary query in Ingres? | In Oracle, the number of rows returned in an arbitrary query can be limited by filtering on the "virtual" rownum column. Consider the following example, which will return, at most, 10 rows. SELECT * FROM all_tables WHERE rownum <= 10 Is there a simple, generic way to do something similar in Ingres? | Blatantly changing my answer. "Limit 10" works for MySql and others, Ingres uses Select First 10 * from myTable Ref | How to limit result set size for arbitrary query in Ingres? In Oracle, the number of rows returned in an arbitrary query can be limited by filtering on the "virtual" rownum column. Consider the following example, which will return, at most, 10 rows. SELECT * FROM all_tables WHERE rownum <= 10 Is there a simple, generic way to do something similar in Ingres? | TITLE:
How to limit result set size for arbitrary query in Ingres?
QUESTION:
In Oracle, the number of rows returned in an arbitrary query can be limited by filtering on the "virtual" rownum column. Consider the following example, which will return, at most, 10 rows. SELECT * FROM all_tables WHERE rownum <= 10 Is there a simple, generic way to do something similar in Ingres?
ANSWER:
Blatantly changing my answer. "Limit 10" works for MySql and others, Ingres uses Select First 10 * from myTable Ref | [
"sql",
"oracle",
"ingres"
] | 4 | 6 | 7,828 | 4 | 0 | 2008-09-08T12:47:26.780000 | 2008-09-08T12:48:50.520000 |
49,630 | 49,687 | Problems with mouseout event | I'm using JavaScript to hide an image and show some text thats hidden under it. But, when the text is shown if you scroll over it, it fires the mouseout event on the container, that then hides the text and shows the image again, and it just goes into a weird loop. The html looks like this: some content some more content And the javascript (It uses scriptaculous): function jsHoverIn(id) { if(!visible[id]) { new Effect.Fade ("image" + id, {queue: { position: 'end', scope: id } }); new Effect.Appear ("text" + id, {queue: { position: 'end', scope: id } }); visible[id] = true; } } function jsHoverOut (id) { var scope = Effect.Queues.get(id); scope.each(function(effect) { effect.cancel(); });
new Effect.Fade ("text" + id, {queue: { position: 'end', scope: id } }); new Effect.Appear ("image" + id, {queue: { position: 'end', scope: id } }); visible[id] = false; } This seems really simple, but i just cant wrap my head around it. | I'd give the container div: position: relative; and add a third div in the container (should be the last child of the container) with: position: absolute; top: 0; bottom: 0; left: 0; right: 0; and catch the mouseover and mouseout events on this div instead. Because it has no child elements, you shouldn't get spurious mouseover and mouseout events propagating to it. Edit: What I believe happens, is that when the cursor moves from a parent element onto a child element, a mouseout event occurs on the parent element, and a mouseover event occurs on the child element. However, if the mouseover handler on the child element does not catch the event and stop it propagating, the parent element will also receive the mouseover event. | Problems with mouseout event I'm using JavaScript to hide an image and show some text thats hidden under it. But, when the text is shown if you scroll over it, it fires the mouseout event on the container, that then hides the text and shows the image again, and it just goes into a weird loop. The html looks like this: some content some more content And the javascript (It uses scriptaculous): function jsHoverIn(id) { if(!visible[id]) { new Effect.Fade ("image" + id, {queue: { position: 'end', scope: id } }); new Effect.Appear ("text" + id, {queue: { position: 'end', scope: id } }); visible[id] = true; } } function jsHoverOut (id) { var scope = Effect.Queues.get(id); scope.each(function(effect) { effect.cancel(); });
new Effect.Fade ("text" + id, {queue: { position: 'end', scope: id } }); new Effect.Appear ("image" + id, {queue: { position: 'end', scope: id } }); visible[id] = false; } This seems really simple, but i just cant wrap my head around it. | TITLE:
Problems with mouseout event
QUESTION:
I'm using JavaScript to hide an image and show some text thats hidden under it. But, when the text is shown if you scroll over it, it fires the mouseout event on the container, that then hides the text and shows the image again, and it just goes into a weird loop. The html looks like this: some content some more content And the javascript (It uses scriptaculous): function jsHoverIn(id) { if(!visible[id]) { new Effect.Fade ("image" + id, {queue: { position: 'end', scope: id } }); new Effect.Appear ("text" + id, {queue: { position: 'end', scope: id } }); visible[id] = true; } } function jsHoverOut (id) { var scope = Effect.Queues.get(id); scope.each(function(effect) { effect.cancel(); });
new Effect.Fade ("text" + id, {queue: { position: 'end', scope: id } }); new Effect.Appear ("image" + id, {queue: { position: 'end', scope: id } }); visible[id] = false; } This seems really simple, but i just cant wrap my head around it.
ANSWER:
I'd give the container div: position: relative; and add a third div in the container (should be the last child of the container) with: position: absolute; top: 0; bottom: 0; left: 0; right: 0; and catch the mouseover and mouseout events on this div instead. Because it has no child elements, you shouldn't get spurious mouseover and mouseout events propagating to it. Edit: What I believe happens, is that when the cursor moves from a parent element onto a child element, a mouseout event occurs on the parent element, and a mouseover event occurs on the child element. However, if the mouseover handler on the child element does not catch the event and stop it propagating, the parent element will also receive the mouseover event. | [
"javascript",
"html",
"events",
"scriptaculous"
] | 6 | 5 | 6,385 | 6 | 0 | 2008-09-08T12:55:33.890000 | 2008-09-08T13:20:28.900000 |
49,652 | 70,367 | Are there any good automated test suites for Perl? | Can someone suggest some good automated test suite framework for Perl? | It really depends on what you're trying to do, but here's some background for much of this. First, you would generally write your test programs with Test::More or Test::Simple as the core testing program: use Test::More tests => 2;
is 3, 3, 'basic equality should work'; ok!0, '... and zero should be false'; Internally, Test::Builder is called to output those test results as TAP ( Test Anything Protocol ). Test::Harness (a thin wrapper around TAP::Harness), reads and interprets the TAP, telling you if your tests passed or failed. The "prove" tool mentioned above is bundled with Test::Harness, so let's say that save the above in the t/ directory (the standard Perl testing directory) as "numbers.t", then you can run it with this command: prove --verbose t/numbers.t Or to run all tests in that directory (recursively, assuming you want to descend into subdirectories): prove --verbose -r t/ (--verbose, of course, is optional). As a side note, don't use TestUnit. Many people recommend it, but it was abandoned a long time ago and doesn't integrate with modern testing tools. | Are there any good automated test suites for Perl? Can someone suggest some good automated test suite framework for Perl? | TITLE:
Are there any good automated test suites for Perl?
QUESTION:
Can someone suggest some good automated test suite framework for Perl?
ANSWER:
It really depends on what you're trying to do, but here's some background for much of this. First, you would generally write your test programs with Test::More or Test::Simple as the core testing program: use Test::More tests => 2;
is 3, 3, 'basic equality should work'; ok!0, '... and zero should be false'; Internally, Test::Builder is called to output those test results as TAP ( Test Anything Protocol ). Test::Harness (a thin wrapper around TAP::Harness), reads and interprets the TAP, telling you if your tests passed or failed. The "prove" tool mentioned above is bundled with Test::Harness, so let's say that save the above in the t/ directory (the standard Perl testing directory) as "numbers.t", then you can run it with this command: prove --verbose t/numbers.t Or to run all tests in that directory (recursively, assuming you want to descend into subdirectories): prove --verbose -r t/ (--verbose, of course, is optional). As a side note, don't use TestUnit. Many people recommend it, but it was abandoned a long time ago and doesn't integrate with modern testing tools. | [
"perl",
"testing"
] | 9 | 24 | 2,913 | 14 | 0 | 2008-09-08T13:01:08.387000 | 2008-09-16T08:30:52.367000 |
49,662 | 49,666 | Software evaluation licensing | My company is looking to start distributing some software we developed and would like to be able to let people try the software out before buying. We'd also like to make sure it can't be copied and distributed to our customers' customers. One model we've seen is tying a license to a MAC address so the software will only work on one machine. What I'm wondering is, what's a good way to generate a license key with different information embedded in it such as license expiration date, MAC address, and different software restrictions? | I'd suggest you take the pieces of information you want in the key, and hash it with md5, and then just take the first X characters (where X is a key length you think is manageable). Cryptographically, it's far from perfect, but this is the sort of area where you want to put in the minimum amount of effort which will stop a casual attacker - anything more quickly becomes a black hole. Oh, I should also point out, you will want to provide the expiration date (and any other information you might want to read out yourself) in plain text (or slightly obfuscated) as part of the key as well if you go down this path - The md5 is just to stop the end user from changing he expiration date to extend the license. The easiest thing would be a key file like this... # License key for XYZZY expiry-date=2009-01-01 other-info=blah key=[md5 has of MAC address, expiry date, other-info] | Software evaluation licensing My company is looking to start distributing some software we developed and would like to be able to let people try the software out before buying. We'd also like to make sure it can't be copied and distributed to our customers' customers. One model we've seen is tying a license to a MAC address so the software will only work on one machine. What I'm wondering is, what's a good way to generate a license key with different information embedded in it such as license expiration date, MAC address, and different software restrictions? | TITLE:
Software evaluation licensing
QUESTION:
My company is looking to start distributing some software we developed and would like to be able to let people try the software out before buying. We'd also like to make sure it can't be copied and distributed to our customers' customers. One model we've seen is tying a license to a MAC address so the software will only work on one machine. What I'm wondering is, what's a good way to generate a license key with different information embedded in it such as license expiration date, MAC address, and different software restrictions?
ANSWER:
I'd suggest you take the pieces of information you want in the key, and hash it with md5, and then just take the first X characters (where X is a key length you think is manageable). Cryptographically, it's far from perfect, but this is the sort of area where you want to put in the minimum amount of effort which will stop a casual attacker - anything more quickly becomes a black hole. Oh, I should also point out, you will want to provide the expiration date (and any other information you might want to read out yourself) in plain text (or slightly obfuscated) as part of the key as well if you go down this path - The md5 is just to stop the end user from changing he expiration date to extend the license. The easiest thing would be a key file like this... # License key for XYZZY expiry-date=2009-01-01 other-info=blah key=[md5 has of MAC address, expiry date, other-info] | [
"licensing"
] | 13 | 8 | 11,305 | 10 | 0 | 2008-09-08T13:06:22.273000 | 2008-09-08T13:09:12.983000 |
49,663 | 49,679 | Where can I find thorough DCOM documentation? | I work on an application that uses DCOM to communicate between what are essentially several peers; in the course of normal use, instances on separate machines serve a variety of objects to one another. Historically, for this to work we have used some magic incantations, chief among which is that on every machine the user must log into an account of the same name (note that these are local accounts; there is no domain available). Obviously, this is an aspect of our user experience that could be improved. I would like to better understand how DCOM authentication works, but I am having difficulty assembling the whole story from the MSDN documentation for CoInitializeSecurity(), CoSetProxyBlanket(), and the like. Are there any thorough explanations available of how, exactly, DCOM operations are accepted or denied? Books, journals, web, any format is fine. | Programming Windows Security by Keith Brown includes a thorough discussion of DCOM security. I can highly recommend this book. | Where can I find thorough DCOM documentation? I work on an application that uses DCOM to communicate between what are essentially several peers; in the course of normal use, instances on separate machines serve a variety of objects to one another. Historically, for this to work we have used some magic incantations, chief among which is that on every machine the user must log into an account of the same name (note that these are local accounts; there is no domain available). Obviously, this is an aspect of our user experience that could be improved. I would like to better understand how DCOM authentication works, but I am having difficulty assembling the whole story from the MSDN documentation for CoInitializeSecurity(), CoSetProxyBlanket(), and the like. Are there any thorough explanations available of how, exactly, DCOM operations are accepted or denied? Books, journals, web, any format is fine. | TITLE:
Where can I find thorough DCOM documentation?
QUESTION:
I work on an application that uses DCOM to communicate between what are essentially several peers; in the course of normal use, instances on separate machines serve a variety of objects to one another. Historically, for this to work we have used some magic incantations, chief among which is that on every machine the user must log into an account of the same name (note that these are local accounts; there is no domain available). Obviously, this is an aspect of our user experience that could be improved. I would like to better understand how DCOM authentication works, but I am having difficulty assembling the whole story from the MSDN documentation for CoInitializeSecurity(), CoSetProxyBlanket(), and the like. Are there any thorough explanations available of how, exactly, DCOM operations are accepted or denied? Books, journals, web, any format is fine.
ANSWER:
Programming Windows Security by Keith Brown includes a thorough discussion of DCOM security. I can highly recommend this book. | [
"windows",
"security",
"rpc",
"dcom"
] | 2 | 1 | 603 | 2 | 0 | 2008-09-08T13:06:32.880000 | 2008-09-08T13:15:14.967000 |
49,664 | 519,435 | Sources of inspiration for navigation breadcrumbs | I'm looking for sources of inspiration and/or design patterns for navigation 'breadcrumbs'. So far I have found the breadcrumb collection on Pattern Tap. Does anyone know of any other sources? | http://www.greepit.com/2009/02/06/breadcrumb-inspiration-for-designers/ | Sources of inspiration for navigation breadcrumbs I'm looking for sources of inspiration and/or design patterns for navigation 'breadcrumbs'. So far I have found the breadcrumb collection on Pattern Tap. Does anyone know of any other sources? | TITLE:
Sources of inspiration for navigation breadcrumbs
QUESTION:
I'm looking for sources of inspiration and/or design patterns for navigation 'breadcrumbs'. So far I have found the breadcrumb collection on Pattern Tap. Does anyone know of any other sources?
ANSWER:
http://www.greepit.com/2009/02/06/breadcrumb-inspiration-for-designers/ | [
"html",
"css",
"design-patterns",
"navigation"
] | 8 | 2 | 2,387 | 8 | 0 | 2008-09-08T13:07:58.197000 | 2009-02-06T07:29:34.240000 |
49,699 | 65,731 | Anyone know of Objective-J syntax highlighting in vi? | I have been looking at the new Objective-J / Cappuccino javascript framework from 280North. They provide plug-ins for SubEthaEdit and TextMate to handle syntax highlighting, but I primarily use vi. Does anyone know of a way to get Objective-J syntax highlighting in vi, or a good way to convert whatever format the other two editors use? | The Objective-J Tools package ( http://cappuccino.org/download ) and the source on github now include a vim highlight module. | Anyone know of Objective-J syntax highlighting in vi? I have been looking at the new Objective-J / Cappuccino javascript framework from 280North. They provide plug-ins for SubEthaEdit and TextMate to handle syntax highlighting, but I primarily use vi. Does anyone know of a way to get Objective-J syntax highlighting in vi, or a good way to convert whatever format the other two editors use? | TITLE:
Anyone know of Objective-J syntax highlighting in vi?
QUESTION:
I have been looking at the new Objective-J / Cappuccino javascript framework from 280North. They provide plug-ins for SubEthaEdit and TextMate to handle syntax highlighting, but I primarily use vi. Does anyone know of a way to get Objective-J syntax highlighting in vi, or a good way to convert whatever format the other two editors use?
ANSWER:
The Objective-J Tools package ( http://cappuccino.org/download ) and the source on github now include a vim highlight module. | [
"javascript",
"vi",
"cappuccino",
"objective-j"
] | 10 | 7 | 2,904 | 4 | 0 | 2008-09-08T13:23:50.373000 | 2008-09-15T19:03:16.210000 |
49,718 | 49,733 | Templates In VB | I've got some VB code (actually VBA) which is basically the same except for the type on which it operates. Since I think the DRY principle is a good guiding principle for software development, I want to write one routine for all of the different types which need to be operated on. For example if I had two snippets of code like these: Dim i as Obj1 Set i = RoutineThatReturnsObj1() i.property = newvalue
Dim i as Obj2 Set i = RoutineThatReturnsObj2() i.property = newvalue I'd like to have something like this to handle both instances: Sub MyRoutine(o as ObjectType, r as RoutineToInitializeObject, newvalue as value) Dim i as o Set i = r i.property = newvalue End Sub If I were using C++ I'd generate a template and say no more about it. But I'm using VBA. I'm fairly sure there's no capability like C++ templates in the VBA language definition but is there any other means by which I might achieve the same effect? I'm guessing the answer is no but I ask here because maybe there is some feature of VBA that I've missed. | There's nothing in VB6 that will do that. If you update to Visual Studio Tools for Office with.Net you can use generics: Function MyRoutine(Of O)(R As Delegate, newvalue As Object) As O Dim i As O = CType(r.Method.Invoke(Nothing, Nothing), O)
'you need another parameter to tell it which property to use' ' and then use reflection to set the value' i.property = newvalue return i End Function | Templates In VB I've got some VB code (actually VBA) which is basically the same except for the type on which it operates. Since I think the DRY principle is a good guiding principle for software development, I want to write one routine for all of the different types which need to be operated on. For example if I had two snippets of code like these: Dim i as Obj1 Set i = RoutineThatReturnsObj1() i.property = newvalue
Dim i as Obj2 Set i = RoutineThatReturnsObj2() i.property = newvalue I'd like to have something like this to handle both instances: Sub MyRoutine(o as ObjectType, r as RoutineToInitializeObject, newvalue as value) Dim i as o Set i = r i.property = newvalue End Sub If I were using C++ I'd generate a template and say no more about it. But I'm using VBA. I'm fairly sure there's no capability like C++ templates in the VBA language definition but is there any other means by which I might achieve the same effect? I'm guessing the answer is no but I ask here because maybe there is some feature of VBA that I've missed. | TITLE:
Templates In VB
QUESTION:
I've got some VB code (actually VBA) which is basically the same except for the type on which it operates. Since I think the DRY principle is a good guiding principle for software development, I want to write one routine for all of the different types which need to be operated on. For example if I had two snippets of code like these: Dim i as Obj1 Set i = RoutineThatReturnsObj1() i.property = newvalue
Dim i as Obj2 Set i = RoutineThatReturnsObj2() i.property = newvalue I'd like to have something like this to handle both instances: Sub MyRoutine(o as ObjectType, r as RoutineToInitializeObject, newvalue as value) Dim i as o Set i = r i.property = newvalue End Sub If I were using C++ I'd generate a template and say no more about it. But I'm using VBA. I'm fairly sure there's no capability like C++ templates in the VBA language definition but is there any other means by which I might achieve the same effect? I'm guessing the answer is no but I ask here because maybe there is some feature of VBA that I've missed.
ANSWER:
There's nothing in VB6 that will do that. If you update to Visual Studio Tools for Office with.Net you can use generics: Function MyRoutine(Of O)(R As Delegate, newvalue As Object) As O Dim i As O = CType(r.Method.Invoke(Nothing, Nothing), O)
'you need another parameter to tell it which property to use' ' and then use reflection to set the value' i.property = newvalue return i End Function | [
"vba",
"templates"
] | 2 | 1 | 1,661 | 1 | 0 | 2008-09-08T13:33:55.140000 | 2008-09-08T13:43:28.097000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.