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
40,352
40,366
Whats the difference between RuntimeTypeHandle and Type?
And why would I use one over the other in my code?
Caution: This answer appears to be out of date. It was posted before.NET 4 became available, which apparently introduced some optimizations regarding Type and thus rendered the information in this answer obsolete. See this more recent answer for details. According to this blog post (from 2006) by Vance Morrison, RuntimeTypeHandle is a value type ( struct ) that wraps an unmanaged pointer, so Type.GetTypeHandle(obj).Equals(anotherHandle) is faster to use for strict "is exactly the same type" comparisons than obj.GetType().Equals(anotherType) — the latter creates System.Type instances which are, apparently, heavier. However, it's also less obvious, and definitely falls under the category "micro-optimization" so if you're wondering when you need one over the other, you should probably just use System.Type.
Whats the difference between RuntimeTypeHandle and Type? And why would I use one over the other in my code?
TITLE: Whats the difference between RuntimeTypeHandle and Type? QUESTION: And why would I use one over the other in my code? ANSWER: Caution: This answer appears to be out of date. It was posted before.NET 4 became available, which apparently introduced some optimizations regarding Type and thus rendered the information in this answer obsolete. See this more recent answer for details. According to this blog post (from 2006) by Vance Morrison, RuntimeTypeHandle is a value type ( struct ) that wraps an unmanaged pointer, so Type.GetTypeHandle(obj).Equals(anotherHandle) is faster to use for strict "is exactly the same type" comparisons than obj.GetType().Equals(anotherType) — the latter creates System.Type instances which are, apparently, heavier. However, it's also less obvious, and definitely falls under the category "micro-optimization" so if you're wondering when you need one over the other, you should probably just use System.Type.
[ "c#", ".net", "reflection" ]
18
12
4,149
2
0
2008-09-02T19:20:08.060000
2008-09-02T19:28:14.047000
40,361
41,152
Can I create a value for a missing tag in XPath?
I have an application which extracts data from an XML file using XPath. If a node in that XML source file is missing I want to return the value "N/A" (much like the Oracle NVL function). The trick is that the application doesn't support XSLT; I'd like to do this using XPath and XPath alone. Is that possible?
It can be done but only if the return value when the node does exist is the string value of the node, not the node itself. The XPath substring(concat("N/A", /foo/baz), 4 * number(boolean(/foo/baz))) will return the string value of the baz element if it exists, otherwise the string "N/A". To generalize the approach: substring(concat($null-value, $node), (string-length($null-value) + 1) * number(boolean($node))) where $null-value is the null value string and $node the expression to select the node. Note that if $node evaluates to a node-set that contains more than one node, the string value of the first node is used.
Can I create a value for a missing tag in XPath? I have an application which extracts data from an XML file using XPath. If a node in that XML source file is missing I want to return the value "N/A" (much like the Oracle NVL function). The trick is that the application doesn't support XSLT; I'd like to do this using XPath and XPath alone. Is that possible?
TITLE: Can I create a value for a missing tag in XPath? QUESTION: I have an application which extracts data from an XML file using XPath. If a node in that XML source file is missing I want to return the value "N/A" (much like the Oracle NVL function). The trick is that the application doesn't support XSLT; I'd like to do this using XPath and XPath alone. Is that possible? ANSWER: It can be done but only if the return value when the node does exist is the string value of the node, not the node itself. The XPath substring(concat("N/A", /foo/baz), 4 * number(boolean(/foo/baz))) will return the string value of the baz element if it exists, otherwise the string "N/A". To generalize the approach: substring(concat($null-value, $node), (string-length($null-value) + 1) * number(boolean($node))) where $null-value is the null value string and $node the expression to select the node. Note that if $node evaluates to a node-set that contains more than one node, the string value of the first node is used.
[ "xml", "xslt", "xpath" ]
10
5
6,747
5
0
2008-09-02T19:25:38.793000
2008-09-03T03:58:06.863000
40,372
40,378
How can you export the saved username and passwords in FireFox 2?
I need to reformat my machine but I have so many user/passwords stored in FF2 that I just keep putting it off. Yes I know about backing up the entire profile and restoring it. But for some reason my profile has many issues and I want to start fresh with that as well. Are the username and passwords stored in a text file or is there some way to export them and import after I reformat?
There is a Firefox add-on called Password Exporter. It can export to XML or CSV files that can be imported in another browser or computer.
How can you export the saved username and passwords in FireFox 2? I need to reformat my machine but I have so many user/passwords stored in FF2 that I just keep putting it off. Yes I know about backing up the entire profile and restoring it. But for some reason my profile has many issues and I want to start fresh with that as well. Are the username and passwords stored in a text file or is there some way to export them and import after I reformat?
TITLE: How can you export the saved username and passwords in FireFox 2? QUESTION: I need to reformat my machine but I have so many user/passwords stored in FF2 that I just keep putting it off. Yes I know about backing up the entire profile and restoring it. But for some reason my profile has many issues and I want to start fresh with that as well. Are the username and passwords stored in a text file or is there some way to export them and import after I reformat? ANSWER: There is a Firefox add-on called Password Exporter. It can export to XML or CSV files that can be imported in another browser or computer.
[ "firefox" ]
3
3
10,212
6
0
2008-09-02T19:31:26.190000
2008-09-02T19:34:09.850000
40,376
41,157
Handle signals in the Java Virtual Machine
Is it possible to handle POSIX signals within the Java Virtual Machine? At least SIGINT and SIGKILL should be quite platform independent.
The JVM responds to signals on its own. Some will cause the JVM to shutdown gracefully, which includes running shutdown hooks. Other signals will cause the JVM to abort without running shutdown hooks. Shutdown hooks are added using Runtime.addShutdownHook(Thread). I don't think the JDK provides an official way to handle signals within your Java application. However, I did find this IBM article, which describes using some undocumented sun.misc.Signal class to do exactly that. The article dates from 2002 and uses JDK 1.3.1, but I've confirmed that the sun.misc.Signal class still exists in JDK 1.6.0.
Handle signals in the Java Virtual Machine Is it possible to handle POSIX signals within the Java Virtual Machine? At least SIGINT and SIGKILL should be quite platform independent.
TITLE: Handle signals in the Java Virtual Machine QUESTION: Is it possible to handle POSIX signals within the Java Virtual Machine? At least SIGINT and SIGKILL should be quite platform independent. ANSWER: The JVM responds to signals on its own. Some will cause the JVM to shutdown gracefully, which includes running shutdown hooks. Other signals will cause the JVM to abort without running shutdown hooks. Shutdown hooks are added using Runtime.addShutdownHook(Thread). I don't think the JDK provides an official way to handle signals within your Java application. However, I did find this IBM article, which describes using some undocumented sun.misc.Signal class to do exactly that. The article dates from 2002 and uses JDK 1.3.1, but I've confirmed that the sun.misc.Signal class still exists in JDK 1.6.0.
[ "java", "jvm", "process", "posix", "signals" ]
14
14
7,871
2
0
2008-09-02T19:33:15.907000
2008-09-03T04:08:58.537000
40,402
40,427
What is the command to truncate a SQL Server log file?
I need to empty an LDF file before sending to a colleague. How do I force SQL Server to truncate the log?
if I remember well... in query analyzer or equivalent: BACKUP LOG databasename WITH TRUNCATE_ONLY DBCC SHRINKFILE ( databasename_Log, 1)
What is the command to truncate a SQL Server log file? I need to empty an LDF file before sending to a colleague. How do I force SQL Server to truncate the log?
TITLE: What is the command to truncate a SQL Server log file? QUESTION: I need to empty an LDF file before sending to a colleague. How do I force SQL Server to truncate the log? ANSWER: if I remember well... in query analyzer or equivalent: BACKUP LOG databasename WITH TRUNCATE_ONLY DBCC SHRINKFILE ( databasename_Log, 1)
[ "sql-server", "truncate", "logging" ]
223
135
561,389
7
0
2008-09-02T19:44:50.463000
2008-09-02T19:53:31.410000
40,413
40,419
How to traverse a maze programmatically when you've hit a dead end
Moving through the maze forward is pretty easy, but I can't seem to figure out how to back up through the maze to try a new route once you hit a dead end without going back too far?
Use backtracking by keeping a stack of previous direction decisions.
How to traverse a maze programmatically when you've hit a dead end Moving through the maze forward is pretty easy, but I can't seem to figure out how to back up through the maze to try a new route once you hit a dead end without going back too far?
TITLE: How to traverse a maze programmatically when you've hit a dead end QUESTION: Moving through the maze forward is pretty easy, but I can't seem to figure out how to back up through the maze to try a new route once you hit a dead end without going back too far? ANSWER: Use backtracking by keeping a stack of previous direction decisions.
[ "c#", "artificial-intelligence", "maze" ]
1
4
2,594
3
0
2008-09-02T19:47:38.163000
2008-09-02T19:50:36.800000
40,423
40,616
How would you implement Erlang-like send and receive in C++?
Actually, this question seems to have two parts: How to implement pattern matching? How to implement send and receive (i.e. the Actor model)? For the pattern matching part, I've been looking into various projects like App and Prop. These look pretty nice, but couldn't get them to work on a recent version (4.x) of g++. The Felix language also seems to support pattern matching pretty well, but isn't really C++. As for the Actor model, there are existing implementations like ACT++ and Theron, but I couldn't find anything but papers on the former, and the latter is single-threaded only [see answers]. Personally, I've implemented actors using threading and a thread-safe message queue. Messages are hash-like structures, and used these together with a number of preprocessor macros to implemented simple pattern matching. Right now, I can use the following code to send a message: (new Message(this)) ->set("foo", "bar") ->set("baz", 123) ->send(recipient); And the following to do simple pattern matching ( qDebug and qPrintable are Qt-specific): receive_and_match(m) match_key("foo") { qDebug("foo: %s", qPrintable(m->value("foo").toString())); } or_match_key("baz") { qDebug("baz: %d", m->value("baz").toInt()); } or_match_ignore end_receive However, this looks a bit hackish to me, and isn't very robust. How would you do it? Did I miss any existing work?
One of the important things about erlang is how the features are used to make robust systems. The send/recieve model is no-sharing, and explicitly copying. The processes themselves are lightweight threads. If you did desire the robust properties of the erlang model, you would be best to use real processes and IPC rather than threads. If you want robust message passing though you may end up wanting to serialize and deserialise the contents. Especially with type safety. Pattern matching in C++ isn't always pretty but there will be a good pattern for this - you will end up creating a dispatcher object that uses some form of polymorphism to get what you want. Although if you are not careful you end up with xml over pipes:) Really, if you want the erlang model you really want to use erlang. If there are slow bits, I'm sure you can augment your program using a foreign function internet. The problem about re-implementing parts, is you won't get a good cohesive library and solution. The solutions you have already don't look much like C++ anymore.
How would you implement Erlang-like send and receive in C++? Actually, this question seems to have two parts: How to implement pattern matching? How to implement send and receive (i.e. the Actor model)? For the pattern matching part, I've been looking into various projects like App and Prop. These look pretty nice, but couldn't get them to work on a recent version (4.x) of g++. The Felix language also seems to support pattern matching pretty well, but isn't really C++. As for the Actor model, there are existing implementations like ACT++ and Theron, but I couldn't find anything but papers on the former, and the latter is single-threaded only [see answers]. Personally, I've implemented actors using threading and a thread-safe message queue. Messages are hash-like structures, and used these together with a number of preprocessor macros to implemented simple pattern matching. Right now, I can use the following code to send a message: (new Message(this)) ->set("foo", "bar") ->set("baz", 123) ->send(recipient); And the following to do simple pattern matching ( qDebug and qPrintable are Qt-specific): receive_and_match(m) match_key("foo") { qDebug("foo: %s", qPrintable(m->value("foo").toString())); } or_match_key("baz") { qDebug("baz: %d", m->value("baz").toInt()); } or_match_ignore end_receive However, this looks a bit hackish to me, and isn't very robust. How would you do it? Did I miss any existing work?
TITLE: How would you implement Erlang-like send and receive in C++? QUESTION: Actually, this question seems to have two parts: How to implement pattern matching? How to implement send and receive (i.e. the Actor model)? For the pattern matching part, I've been looking into various projects like App and Prop. These look pretty nice, but couldn't get them to work on a recent version (4.x) of g++. The Felix language also seems to support pattern matching pretty well, but isn't really C++. As for the Actor model, there are existing implementations like ACT++ and Theron, but I couldn't find anything but papers on the former, and the latter is single-threaded only [see answers]. Personally, I've implemented actors using threading and a thread-safe message queue. Messages are hash-like structures, and used these together with a number of preprocessor macros to implemented simple pattern matching. Right now, I can use the following code to send a message: (new Message(this)) ->set("foo", "bar") ->set("baz", 123) ->send(recipient); And the following to do simple pattern matching ( qDebug and qPrintable are Qt-specific): receive_and_match(m) match_key("foo") { qDebug("foo: %s", qPrintable(m->value("foo").toString())); } or_match_key("baz") { qDebug("baz: %d", m->value("baz").toInt()); } or_match_ignore end_receive However, this looks a bit hackish to me, and isn't very robust. How would you do it? Did I miss any existing work? ANSWER: One of the important things about erlang is how the features are used to make robust systems. The send/recieve model is no-sharing, and explicitly copying. The processes themselves are lightweight threads. If you did desire the robust properties of the erlang model, you would be best to use real processes and IPC rather than threads. If you want robust message passing though you may end up wanting to serialize and deserialise the contents. Especially with type safety. Pattern matching in C++ isn't always pretty but there will be a good pattern for this - you will end up creating a dispatcher object that uses some form of polymorphism to get what you want. Although if you are not careful you end up with xml over pipes:) Really, if you want the erlang model you really want to use erlang. If there are slow bits, I'm sure you can augment your program using a foreign function internet. The problem about re-implementing parts, is you won't get a good cohesive library and solution. The solutions you have already don't look much like C++ anymore.
[ "c++", "erlang" ]
10
4
3,312
7
0
2008-09-02T19:52:33.660000
2008-09-02T20:49:18.967000
40,452
40,479
HTTP POST - I'm stuck
I have to POST some parameters to a URL outside my network, and the developers on the other side asked me to not use HTTP Parameters: instead I have to post my key-values in HTTP Headers. The fact is that I don't really understand what they mean: I tried to use a ajax-like post, with XmlHttp objects, and also I tried to write in the header with something like Request.Headers.Add(key,value); but I cannot (exception from the framework); I tried the other way around, using the Response object like Response.AppendHeader("key", "value"); and then redirect to the page... but this doesn't work, as well. It's evident, I think, that I'm stuck there, any help? EDIT I forgot to tell you that my environment is.Net 2.0, c#, on Win server 2003. The exception I got is System.PlatformNotSupportedException was unhandled by user code Message="Operation is not supported on this platform." Source="System.Web" This looks like it's caused by my tentative to Request.Add, MS an year ago published some security fixes that don't permit this.
Like @lassevk said, a redirect won't work. You should use the WebRequest class to do an HTTP POST from your page or application. There's an example here.
HTTP POST - I'm stuck I have to POST some parameters to a URL outside my network, and the developers on the other side asked me to not use HTTP Parameters: instead I have to post my key-values in HTTP Headers. The fact is that I don't really understand what they mean: I tried to use a ajax-like post, with XmlHttp objects, and also I tried to write in the header with something like Request.Headers.Add(key,value); but I cannot (exception from the framework); I tried the other way around, using the Response object like Response.AppendHeader("key", "value"); and then redirect to the page... but this doesn't work, as well. It's evident, I think, that I'm stuck there, any help? EDIT I forgot to tell you that my environment is.Net 2.0, c#, on Win server 2003. The exception I got is System.PlatformNotSupportedException was unhandled by user code Message="Operation is not supported on this platform." Source="System.Web" This looks like it's caused by my tentative to Request.Add, MS an year ago published some security fixes that don't permit this.
TITLE: HTTP POST - I'm stuck QUESTION: I have to POST some parameters to a URL outside my network, and the developers on the other side asked me to not use HTTP Parameters: instead I have to post my key-values in HTTP Headers. The fact is that I don't really understand what they mean: I tried to use a ajax-like post, with XmlHttp objects, and also I tried to write in the header with something like Request.Headers.Add(key,value); but I cannot (exception from the framework); I tried the other way around, using the Response object like Response.AppendHeader("key", "value"); and then redirect to the page... but this doesn't work, as well. It's evident, I think, that I'm stuck there, any help? EDIT I forgot to tell you that my environment is.Net 2.0, c#, on Win server 2003. The exception I got is System.PlatformNotSupportedException was unhandled by user code Message="Operation is not supported on this platform." Source="System.Web" This looks like it's caused by my tentative to Request.Add, MS an year ago published some security fixes that don't permit this. ANSWER: Like @lassevk said, a redirect won't work. You should use the WebRequest class to do an HTTP POST from your page or application. There's an example here.
[ "asp.net", "forms", "http", "post" ]
5
1
3,702
9
0
2008-09-02T20:04:28.920000
2008-09-02T20:14:11.157000
40,456
40,619
sql missing rows when grouped by DAY, MONTH, YEAR
If I select from a table group by the month, day, year, it only returns rows with records and leaves out combinations without any records, making it appear at a glance that every day or month has activity, you have to look at the date column actively for gaps. How can I get a row for every day/month/year, even when no data is present, in T-SQL?
My developer got back to me with this code, underscores converted to dashes because StackOverflow was mangling underscores -- no numbers table required. Our example is complicated a bit by a join to another table, but maybe the code example will help someone someday. declare @career-fair-id int select @career-fair-id = 125 create table #data ([date] datetime null, [cumulative] int null) declare @event-date datetime, @current-process-date datetime, @day-count int select @event-date = (select careerfairdate from tbl-career-fair where careerfairid = @career-fair-id) select @current-process-date = dateadd(day, -90, @event-date) while @event-date <> @current-process-date begin select @current-process-date = dateadd(day, 1, @current-process-date) select @day-count = (select count(*) from tbl-career-fair-junction where attendanceregister <= @current-process-date and careerfairid = @career-fair-id) if @current-process-date <= getdate() insert into #data ([date], [cumulative]) values(@current-process-date, @day-count) end select * from #data drop table #data
sql missing rows when grouped by DAY, MONTH, YEAR If I select from a table group by the month, day, year, it only returns rows with records and leaves out combinations without any records, making it appear at a glance that every day or month has activity, you have to look at the date column actively for gaps. How can I get a row for every day/month/year, even when no data is present, in T-SQL?
TITLE: sql missing rows when grouped by DAY, MONTH, YEAR QUESTION: If I select from a table group by the month, day, year, it only returns rows with records and leaves out combinations without any records, making it appear at a glance that every day or month has activity, you have to look at the date column actively for gaps. How can I get a row for every day/month/year, even when no data is present, in T-SQL? ANSWER: My developer got back to me with this code, underscores converted to dashes because StackOverflow was mangling underscores -- no numbers table required. Our example is complicated a bit by a join to another table, but maybe the code example will help someone someday. declare @career-fair-id int select @career-fair-id = 125 create table #data ([date] datetime null, [cumulative] int null) declare @event-date datetime, @current-process-date datetime, @day-count int select @event-date = (select careerfairdate from tbl-career-fair where careerfairid = @career-fair-id) select @current-process-date = dateadd(day, -90, @event-date) while @event-date <> @current-process-date begin select @current-process-date = dateadd(day, 1, @current-process-date) select @day-count = (select count(*) from tbl-career-fair-junction where attendanceregister <= @current-process-date and careerfairid = @career-fair-id) if @current-process-date <= getdate() insert into #data ([date], [cumulative]) values(@current-process-date, @day-count) end select * from #data drop table #data
[ "t-sql", "date", "grouping" ]
4
1
4,390
5
0
2008-09-02T20:06:25.343000
2008-09-02T20:50:00.510000
40,465
40,497
How to get an array of distinct property values from in memory lists?
I have a List of Foo. Foo has a string property named Bar. I'd like to use LINQ to get a string[] of distinct values for Foo.Bar in List of Foo. How can I do this?
I'd go lambdas... wayyy nicer var bars = Foos.Select(f => f.Bar).Distinct().ToArray(); works the same as what @lassevk posted. I'd also add that you might want to keep from converting to an array until the last minute. LINQ does some optimizations behind the scenes, queries stay in its query form until explicitly needed. So you might want to build everything you need into the query first so any possible optimization is applied altogether. By evaluation I means asking for something that explicitly requires evalution like "Count()" or "ToArray()" etc.
How to get an array of distinct property values from in memory lists? I have a List of Foo. Foo has a string property named Bar. I'd like to use LINQ to get a string[] of distinct values for Foo.Bar in List of Foo. How can I do this?
TITLE: How to get an array of distinct property values from in memory lists? QUESTION: I have a List of Foo. Foo has a string property named Bar. I'd like to use LINQ to get a string[] of distinct values for Foo.Bar in List of Foo. How can I do this? ANSWER: I'd go lambdas... wayyy nicer var bars = Foos.Select(f => f.Bar).Distinct().ToArray(); works the same as what @lassevk posted. I'd also add that you might want to keep from converting to an array until the last minute. LINQ does some optimizations behind the scenes, queries stay in its query form until explicitly needed. So you might want to build everything you need into the query first so any possible optimization is applied altogether. By evaluation I means asking for something that explicitly requires evalution like "Count()" or "ToArray()" etc.
[ "c#", ".net", "performance", "linq", "filtering" ]
4
5
6,407
4
0
2008-09-02T20:08:51.607000
2008-09-02T20:18:09.713000
40,471
40,878
What are the differences between a HashMap and a Hashtable in Java?
What are the differences between a HashMap and a Hashtable in Java? Which is more efficient for non-threaded applications?
There are several differences between HashMap and Hashtable in Java: Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable. Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.
What are the differences between a HashMap and a Hashtable in Java? What are the differences between a HashMap and a Hashtable in Java? Which is more efficient for non-threaded applications?
TITLE: What are the differences between a HashMap and a Hashtable in Java? QUESTION: What are the differences between a HashMap and a Hashtable in Java? Which is more efficient for non-threaded applications? ANSWER: There are several differences between HashMap and Hashtable in Java: Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable. Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.
[ "java", "collections", "hashmap", "hashtable" ]
4,318
4,233
1,745,963
35
0
2008-09-02T20:12:00.117000
2008-09-02T23:02:37.180000
40,495
40,562
Bug tracker setup with Git integration?
I know I can do most of this by hacking Trac and using Git hooks, but I was wondering if someone has / knows of something ready. Commenting on (and closing) tickets from commit messages would be nice, specially if the diff appears inline with the comment/closing remark. sha1 hashes should be auto-linked to gitweb/cigt/custom git browser. I tried the GitPlugin for Trac, but the code browser was soo slow... any alternatives?
Redmine can do some of what you're asking for. Integration works in one direction, you must reference issues in commit messages, and then this data will be available in redmine. The data is then available in two views. The bug display will include a list of matched commits. The repository display will link commits to bug display pages. Redmine keeps a local (bare) repository for each project. This can be the primary repo or a remote mirror. On updates, redmine parses the commit messages and updates an internal cross reference table of change_set,issue. If the redmine repository is only used as a mirror, it will need to be updated. Updates can happen via cron or via external hook. We use a redmine github plugin and a github post-receive hook to keep redmine in sync with a primary github repository. It works, but it is still a bit clumsy.
Bug tracker setup with Git integration? I know I can do most of this by hacking Trac and using Git hooks, but I was wondering if someone has / knows of something ready. Commenting on (and closing) tickets from commit messages would be nice, specially if the diff appears inline with the comment/closing remark. sha1 hashes should be auto-linked to gitweb/cigt/custom git browser. I tried the GitPlugin for Trac, but the code browser was soo slow... any alternatives?
TITLE: Bug tracker setup with Git integration? QUESTION: I know I can do most of this by hacking Trac and using Git hooks, but I was wondering if someone has / knows of something ready. Commenting on (and closing) tickets from commit messages would be nice, specially if the diff appears inline with the comment/closing remark. sha1 hashes should be auto-linked to gitweb/cigt/custom git browser. I tried the GitPlugin for Trac, but the code browser was soo slow... any alternatives? ANSWER: Redmine can do some of what you're asking for. Integration works in one direction, you must reference issues in commit messages, and then this data will be available in redmine. The data is then available in two views. The bug display will include a list of matched commits. The repository display will link commits to bug display pages. Redmine keeps a local (bare) repository for each project. This can be the primary repo or a remote mirror. On updates, redmine parses the commit messages and updates an internal cross reference table of change_set,issue. If the redmine repository is only used as a mirror, it will need to be updated. Updates can happen via cron or via external hook. We use a redmine github plugin and a github post-receive hook to keep redmine in sync with a primary github repository. It works, but it is still a bit clumsy.
[ "git", "integration", "version-control", "bug-tracking" ]
36
20
50,726
11
0
2008-09-02T20:17:11.963000
2008-09-02T20:33:57.350000
40,525
40,617
Call Functions within Function - Flash Actionscript 2.0
I'm trying to call a function after I load some XML into Actionscript, and I'm just wondering how I call that function. Example: //Function Declarations function parentFunction() { function callMe() { textField.text = "lawl"; } } Now, how do I call the "callMe()" function in a different part of the code, like an onRelease function? on(release) { callMe(); //doesn't work parentFunction().callMe(); //doesn't work parentFunction.callMe(); //doesn't work } ActionScript 2.0 is just so wonky! Any ideas?
Are you forced to declare callMe inside of parentFunction? I assume so because otherwise you would just do function parent() { } function callMe() { } To be clear, a function can't own another function unless you provide some scope for that function to live in. So in JavaScript, you would do this by using the prototype object to declare the callMe function as a method of the object that parentFunction returned. http://www.howtocreate.co.uk/tutorials/javascript/objects For ActionScript, read this article on Adobe's website: http://www.adobe.com/devnet/flex/articles/as_collections_03.html EDIT: After some more reading it appears the way you did things, you are actually declaring callMe as a private function. See this article which should make the whole private/public javascript issue a lot more understandable.
Call Functions within Function - Flash Actionscript 2.0 I'm trying to call a function after I load some XML into Actionscript, and I'm just wondering how I call that function. Example: //Function Declarations function parentFunction() { function callMe() { textField.text = "lawl"; } } Now, how do I call the "callMe()" function in a different part of the code, like an onRelease function? on(release) { callMe(); //doesn't work parentFunction().callMe(); //doesn't work parentFunction.callMe(); //doesn't work } ActionScript 2.0 is just so wonky! Any ideas?
TITLE: Call Functions within Function - Flash Actionscript 2.0 QUESTION: I'm trying to call a function after I load some XML into Actionscript, and I'm just wondering how I call that function. Example: //Function Declarations function parentFunction() { function callMe() { textField.text = "lawl"; } } Now, how do I call the "callMe()" function in a different part of the code, like an onRelease function? on(release) { callMe(); //doesn't work parentFunction().callMe(); //doesn't work parentFunction.callMe(); //doesn't work } ActionScript 2.0 is just so wonky! Any ideas? ANSWER: Are you forced to declare callMe inside of parentFunction? I assume so because otherwise you would just do function parent() { } function callMe() { } To be clear, a function can't own another function unless you provide some scope for that function to live in. So in JavaScript, you would do this by using the prototype object to declare the callMe function as a method of the object that parentFunction returned. http://www.howtocreate.co.uk/tutorials/javascript/objects For ActionScript, read this article on Adobe's website: http://www.adobe.com/devnet/flex/articles/as_collections_03.html EDIT: After some more reading it appears the way you did things, you are actually declaring callMe as a private function. See this article which should make the whole private/public javascript issue a lot more understandable.
[ "flash", "actionscript", "actionscript-2" ]
2
2
34,735
5
0
2008-09-02T20:25:54.780000
2008-09-02T20:49:29.013000
40,535
2,745,475
Asp.Net MVC: How to determine if you're currently on a specific view
I need to determine if I'm on a particular view. My use case is that I'd like to decorate navigation elements with an "on" class for the current view. Is there a built in way of doing this?
Here what i am using. I think this is actually generated by the MVC project template in VS: public static bool IsCurrentAction(this HtmlHelper helper, string actionName, string controllerName) { string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"]; string currentActionName = (string)helper.ViewContext.RouteData.Values["action"]; if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase)) return true; return false; }
Asp.Net MVC: How to determine if you're currently on a specific view I need to determine if I'm on a particular view. My use case is that I'd like to decorate navigation elements with an "on" class for the current view. Is there a built in way of doing this?
TITLE: Asp.Net MVC: How to determine if you're currently on a specific view QUESTION: I need to determine if I'm on a particular view. My use case is that I'd like to decorate navigation elements with an "on" class for the current view. Is there a built in way of doing this? ANSWER: Here what i am using. I think this is actually generated by the MVC project template in VS: public static bool IsCurrentAction(this HtmlHelper helper, string actionName, string controllerName) { string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"]; string currentActionName = (string)helper.ViewContext.RouteData.Values["action"]; if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase)) return true; return false; }
[ "c#", "asp.net-mvc" ]
11
8
3,761
3
0
2008-09-02T20:27:28.287000
2010-04-30T15:05:08.063000
40,568
1,016,737
Are square brackets permitted in URLs?
Are square brackets in URLs allowed? I noticed that Apache commons HttpClient (3.0.1) throws an IOException, wget and Firefox however accept square brackets. URL example: http://example.com/path/to/file[3].html My HTTP client encounters such URLs but I'm not sure whether to patch the code or to throw an exception (as it actually should be).
RFC 3986 states A host identified by an Internet Protocol literal address, version 6 [RFC3513] or later, is distinguished by enclosing the IP literal within square brackets ("[" and "]"). This is the only place where square bracket characters are allowed in the URI syntax. So you should not be seeing such URI's in the wild in theory, as they should arrive encoded.
Are square brackets permitted in URLs? Are square brackets in URLs allowed? I noticed that Apache commons HttpClient (3.0.1) throws an IOException, wget and Firefox however accept square brackets. URL example: http://example.com/path/to/file[3].html My HTTP client encounters such URLs but I'm not sure whether to patch the code or to throw an exception (as it actually should be).
TITLE: Are square brackets permitted in URLs? QUESTION: Are square brackets in URLs allowed? I noticed that Apache commons HttpClient (3.0.1) throws an IOException, wget and Firefox however accept square brackets. URL example: http://example.com/path/to/file[3].html My HTTP client encounters such URLs but I'm not sure whether to patch the code or to throw an exception (as it actually should be). ANSWER: RFC 3986 states A host identified by an Internet Protocol literal address, version 6 [RFC3513] or later, is distinguished by enclosing the IP literal within square brackets ("[" and "]"). This is the only place where square bracket characters are allowed in the URI syntax. So you should not be seeing such URI's in the wild in theory, as they should arrive encoded.
[ "apache", "http", "url", "syntax", "square-bracket" ]
62
63
68,523
10
0
2008-09-02T20:35:24.150000
2009-06-19T07:23:04.400000
40,577
40,822
Datetime arithmetic with a string in Ruby
In Ruby, I'm trying to do the following. def self.stats(since) return Events.find(:all,:select => 'count(*) as this_count',:conditions => ['Date(event_date) >=?', (Time.now - since)]).first.this_count end where "since" is a string representing an amount of time ('1 hour', '1 day', '3 days') and so on. Any suggestions?
I hacked this together with the ActiveSupport gem: require 'active_support' def string_to_date(date_string) parts = date_string.split return parts[0].to_i.send(parts[1]) end sinces = ['1 hour', '1 day', '3 days'] sinces.each do |since| puts "#{since} ago: #{string_to_date(since).ago(Time.now)}" end [edit] To answer your question, you might try it like that::conditions => ['Date)event_date) >=?', (string_to_date(since).ago(Time.now))]
Datetime arithmetic with a string in Ruby In Ruby, I'm trying to do the following. def self.stats(since) return Events.find(:all,:select => 'count(*) as this_count',:conditions => ['Date(event_date) >=?', (Time.now - since)]).first.this_count end where "since" is a string representing an amount of time ('1 hour', '1 day', '3 days') and so on. Any suggestions?
TITLE: Datetime arithmetic with a string in Ruby QUESTION: In Ruby, I'm trying to do the following. def self.stats(since) return Events.find(:all,:select => 'count(*) as this_count',:conditions => ['Date(event_date) >=?', (Time.now - since)]).first.this_count end where "since" is a string representing an amount of time ('1 hour', '1 day', '3 days') and so on. Any suggestions? ANSWER: I hacked this together with the ActiveSupport gem: require 'active_support' def string_to_date(date_string) parts = date_string.split return parts[0].to_i.send(parts[1]) end sinces = ['1 hour', '1 day', '3 days'] sinces.each do |since| puts "#{since} ago: #{string_to_date(since).ago(Time.now)}" end [edit] To answer your question, you might try it like that::conditions => ['Date)event_date) >=?', (string_to_date(since).ago(Time.now))]
[ "ruby", "datetime", "time" ]
0
2
1,993
3
0
2008-09-02T20:37:53.660000
2008-09-02T22:25:03.653000
40,586
40,593
cx_Oracle: how do I get the ORA-xxxxx error number?
In a try/except block, how do I extract the Oracle error number?
try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, e: error, = e print "Code:", error.code print "Message:", error.message This results in the following output: Code: 1476 Message: ORA-01476: divisor is equal to zero
cx_Oracle: how do I get the ORA-xxxxx error number? In a try/except block, how do I extract the Oracle error number?
TITLE: cx_Oracle: how do I get the ORA-xxxxx error number? QUESTION: In a try/except block, how do I extract the Oracle error number? ANSWER: try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, e: error, = e print "Code:", error.code print "Message:", error.message This results in the following output: Code: 1476 Message: ORA-01476: divisor is equal to zero
[ "python", "oracle", "cx-oracle" ]
2
13
4,635
1
0
2008-09-02T20:40:29.597000
2008-09-02T20:41:33.540000
40,590
40,800
jQuery and Prototype Selector Madness
Both the jQuery and Prototpye JavaScript libraries refuse to allow me to use a variable to select an list item element by index number although they accept a hard coded number. For example, in Prototype this works: $$('li')[5].addClassName('active'); But this will not work no matter how I try to cast the variable as a number or integer: $$('li')[currentPage].addClassName('active'); In jQuery I get similar weirdness. This will work: jQuery('li').eq(5).addClass("active"); But this will not work again even though the value of currentPage is 5 and its type is number: jQuery('li').eq(currentPage).addClass("active"); I'm trying to create a JavaScript pagination system and I need to set the class on the active page button. The list item elements are created dynamically depending upon the number of pages I need.
It looks like I just needed to be more specific in my element selector although it is weird that a hard coded number would work. jQuery('#pagination-digg li').eq(currentPage).addClass("active");
jQuery and Prototype Selector Madness Both the jQuery and Prototpye JavaScript libraries refuse to allow me to use a variable to select an list item element by index number although they accept a hard coded number. For example, in Prototype this works: $$('li')[5].addClassName('active'); But this will not work no matter how I try to cast the variable as a number or integer: $$('li')[currentPage].addClassName('active'); In jQuery I get similar weirdness. This will work: jQuery('li').eq(5).addClass("active"); But this will not work again even though the value of currentPage is 5 and its type is number: jQuery('li').eq(currentPage).addClass("active"); I'm trying to create a JavaScript pagination system and I need to set the class on the active page button. The list item elements are created dynamically depending upon the number of pages I need.
TITLE: jQuery and Prototype Selector Madness QUESTION: Both the jQuery and Prototpye JavaScript libraries refuse to allow me to use a variable to select an list item element by index number although they accept a hard coded number. For example, in Prototype this works: $$('li')[5].addClassName('active'); But this will not work no matter how I try to cast the variable as a number or integer: $$('li')[currentPage].addClassName('active'); In jQuery I get similar weirdness. This will work: jQuery('li').eq(5).addClass("active"); But this will not work again even though the value of currentPage is 5 and its type is number: jQuery('li').eq(currentPage).addClass("active"); I'm trying to create a JavaScript pagination system and I need to set the class on the active page button. The list item elements are created dynamically depending upon the number of pages I need. ANSWER: It looks like I just needed to be more specific in my element selector although it is weird that a hard coded number would work. jQuery('#pagination-digg li').eq(currentPage).addClass("active");
[ "jquery", "prototypejs", "css-selectors", "addclass" ]
5
2
2,256
3
0
2008-09-02T20:41:21.717000
2008-09-02T22:13:31.013000
40,602
40,747
What kind of problems are state machines good for?
What kind of programming problems are state machines most suited for? I have read about parsers being implemented using state machines, but would like to find out about problems that scream out to be implemented as a state machine.
The easiest answer is probably that they are suited for practically any problem. Don't forget that a computer itself is also a state machine. Regardless of that, state machines are typically used for problems where there is some stream of input and the activity that needs to be done at a given moment depends the last elements seen in that stream at that point. Examples of this stream of input: some text file in the case of parsing, a string for regular expressions, events such as player entered room for game AI, etc. Examples of activities: be ready to read a number (after another number followed by a + have appear in the input in a parser for a calculator), turn around (after player approached and then sneezed), perform jumping kick (after player pressed left, left, right, up, up).
What kind of problems are state machines good for? What kind of programming problems are state machines most suited for? I have read about parsers being implemented using state machines, but would like to find out about problems that scream out to be implemented as a state machine.
TITLE: What kind of problems are state machines good for? QUESTION: What kind of programming problems are state machines most suited for? I have read about parsers being implemented using state machines, but would like to find out about problems that scream out to be implemented as a state machine. ANSWER: The easiest answer is probably that they are suited for practically any problem. Don't forget that a computer itself is also a state machine. Regardless of that, state machines are typically used for problems where there is some stream of input and the activity that needs to be done at a given moment depends the last elements seen in that stream at that point. Examples of this stream of input: some text file in the case of parsing, a string for regular expressions, events such as player entered room for game AI, etc. Examples of activities: be ready to read a number (after another number followed by a + have appear in the input in a parser for a calculator), turn around (after player approached and then sneezed), perform jumping kick (after player pressed left, left, right, up, up).
[ "algorithm", "state" ]
18
16
6,132
15
0
2008-09-02T20:44:35.577000
2008-09-02T21:40:38.627000
40,603
40,623
MSI Installer fails without removing a previous install
I have built an MSI that I would like to deploy, and update frequently. Unfortunately, when you install the MSI, and then try to install a newer version of the same MSI, it fails with a message like "Another version of this product is already installed. Installation of this version cannot continue..." appears. The MSI was built with a Visual Studio 2008 Setup Project. I have tried setting the "Remove Previous Versions" property to both true and false, in an effort to just make newer versions overwrite the older install, but nothing has worked. At a previous company I know I did not have this problem with installers built by Wise and Advanced Installer. Is there a setting I am missing? Or is my desired functionality not supported by the VS 2008 Setup Project?
I have built numerous MSIs with VS 2005 Pro that do this correctly. Are you sure that the 'Version' property of the deployment project has been incremented? This property is independent of the version of the assemblies in the application, and this is the error message you will see if the Version property of the MSI is the same as it was for the one you are trying to overwrite.
MSI Installer fails without removing a previous install I have built an MSI that I would like to deploy, and update frequently. Unfortunately, when you install the MSI, and then try to install a newer version of the same MSI, it fails with a message like "Another version of this product is already installed. Installation of this version cannot continue..." appears. The MSI was built with a Visual Studio 2008 Setup Project. I have tried setting the "Remove Previous Versions" property to both true and false, in an effort to just make newer versions overwrite the older install, but nothing has worked. At a previous company I know I did not have this problem with installers built by Wise and Advanced Installer. Is there a setting I am missing? Or is my desired functionality not supported by the VS 2008 Setup Project?
TITLE: MSI Installer fails without removing a previous install QUESTION: I have built an MSI that I would like to deploy, and update frequently. Unfortunately, when you install the MSI, and then try to install a newer version of the same MSI, it fails with a message like "Another version of this product is already installed. Installation of this version cannot continue..." appears. The MSI was built with a Visual Studio 2008 Setup Project. I have tried setting the "Remove Previous Versions" property to both true and false, in an effort to just make newer versions overwrite the older install, but nothing has worked. At a previous company I know I did not have this problem with installers built by Wise and Advanced Installer. Is there a setting I am missing? Or is my desired functionality not supported by the VS 2008 Setup Project? ANSWER: I have built numerous MSIs with VS 2005 Pro that do this correctly. Are you sure that the 'Version' property of the deployment project has been incremented? This property is independent of the version of the assemblies in the application, and this is the error message you will see if the Version property of the MSI is the same as it was for the one you are trying to overwrite.
[ "windows-installer", "versioning" ]
10
9
7,811
5
0
2008-09-02T20:44:44.393000
2008-09-02T20:52:03.190000
40,608
40,613
Loading JSON with PHP
I've been using PHP for too long, but I'm new to JavaScript integration in some places. I'm trying to find the fastest way to pass database information into a page where it can be modified and displayed dynamically in JavaScript. Right now, I'm looking at loading a JSON with PHP echo statements because it's fast and effective, but I saw that I could use PHP's JSON library (PHP 5.2). Has anybody tried the new JSON library, and is it better than my earlier method?
Use the library. If you try to generate it manually, I predict with 99% certainty that the resulting text will be invalid in some way. Especially with more esoteric features like Unicode strings or exponential notation.
Loading JSON with PHP I've been using PHP for too long, but I'm new to JavaScript integration in some places. I'm trying to find the fastest way to pass database information into a page where it can be modified and displayed dynamically in JavaScript. Right now, I'm looking at loading a JSON with PHP echo statements because it's fast and effective, but I saw that I could use PHP's JSON library (PHP 5.2). Has anybody tried the new JSON library, and is it better than my earlier method?
TITLE: Loading JSON with PHP QUESTION: I've been using PHP for too long, but I'm new to JavaScript integration in some places. I'm trying to find the fastest way to pass database information into a page where it can be modified and displayed dynamically in JavaScript. Right now, I'm looking at loading a JSON with PHP echo statements because it's fast and effective, but I saw that I could use PHP's JSON library (PHP 5.2). Has anybody tried the new JSON library, and is it better than my earlier method? ANSWER: Use the library. If you try to generate it manually, I predict with 99% certainty that the resulting text will be invalid in some way. Especially with more esoteric features like Unicode strings or exponential notation.
[ "php", "json" ]
7
16
2,682
3
0
2008-09-02T20:46:38.617000
2008-09-02T20:48:02.963000
40,622
41,729
Is Flex development without FlexBuilder realistic?
Is it realistic to try and learn and code a Flex 3 application without purchasing FlexBuilder? Since the SDK and BlazeDS are open source, it seems technically possible to develop without Flex Builder, but how realistic is it. I would like to test out Flex but don't want to get into a situation where I am dependent on the purchase of FlexBuilder (at least not until I am confident and competent enough with the technology to recommend purchase to my employer). I am experimenting right now, so I'm taking a long time and the trial license on my Windows machine has expired. Also Linux is my primary development platform and there is only an alpha available for Linux. Most of the documentation I've found seem to use Flex Builder. Maybe I should use Laszlo...
I've been using Flex since version 2 and Flex3/BlazeDS since it came out of beta. I also have some experience with Lazzlo and the difference is day and night (Flex rocks!). I have not regretted once using Flex. Regarding FlexBuilder, it is worth every penny. While it is completely possible and reasonable to write Flex application without FlexBuilder, the productivity gains of using it will more than recoup the investment. Try the evaluation for 30 days and compare it to some of the other options suggested about (I'm going to try FlashDevelop). Some things you get with FlexBuilder include: Code completion Visual editor Debugger (it is fantastic!!) Profiler (also very good) Regarding Linux, the alpha version of FlexBuilder does not have a visual editor. Other than that, I understand it is reasonably feature complete, still free, and many of the Adobe employees I've talked with that use Linux are happy with it.
Is Flex development without FlexBuilder realistic? Is it realistic to try and learn and code a Flex 3 application without purchasing FlexBuilder? Since the SDK and BlazeDS are open source, it seems technically possible to develop without Flex Builder, but how realistic is it. I would like to test out Flex but don't want to get into a situation where I am dependent on the purchase of FlexBuilder (at least not until I am confident and competent enough with the technology to recommend purchase to my employer). I am experimenting right now, so I'm taking a long time and the trial license on my Windows machine has expired. Also Linux is my primary development platform and there is only an alpha available for Linux. Most of the documentation I've found seem to use Flex Builder. Maybe I should use Laszlo...
TITLE: Is Flex development without FlexBuilder realistic? QUESTION: Is it realistic to try and learn and code a Flex 3 application without purchasing FlexBuilder? Since the SDK and BlazeDS are open source, it seems technically possible to develop without Flex Builder, but how realistic is it. I would like to test out Flex but don't want to get into a situation where I am dependent on the purchase of FlexBuilder (at least not until I am confident and competent enough with the technology to recommend purchase to my employer). I am experimenting right now, so I'm taking a long time and the trial license on my Windows machine has expired. Also Linux is my primary development platform and there is only an alpha available for Linux. Most of the documentation I've found seem to use Flex Builder. Maybe I should use Laszlo... ANSWER: I've been using Flex since version 2 and Flex3/BlazeDS since it came out of beta. I also have some experience with Lazzlo and the difference is day and night (Flex rocks!). I have not regretted once using Flex. Regarding FlexBuilder, it is worth every penny. While it is completely possible and reasonable to write Flex application without FlexBuilder, the productivity gains of using it will more than recoup the investment. Try the evaluation for 30 days and compare it to some of the other options suggested about (I'm going to try FlashDevelop). Some things you get with FlexBuilder include: Code completion Visual editor Debugger (it is fantastic!!) Profiler (also very good) Regarding Linux, the alpha version of FlexBuilder does not have a visual editor. Other than that, I understand it is reasonably feature complete, still free, and many of the Adobe employees I've talked with that use Linux are happy with it.
[ "apache-flex", "flexbuilder" ]
14
8
4,842
12
0
2008-09-02T20:51:52.097000
2008-09-03T14:02:29.030000
40,632
40,643
I just don't get continuations!
What are they and what are they good for? I do not have a CS degree and my background is VB6 -> ASP -> ASP.NET/C#. Can anyone explain it in a clear and concise manner?
Imagine if every single line in your program was a separate function. Each accepts, as a parameter, the next line/function to execute. Using this model, you can "pause" execution at any line and continue it later. You can also do inventive things like temporarily hop up the execution stack to retrieve a value, or save the current execution state to a database to retrieve later.
I just don't get continuations! What are they and what are they good for? I do not have a CS degree and my background is VB6 -> ASP -> ASP.NET/C#. Can anyone explain it in a clear and concise manner?
TITLE: I just don't get continuations! QUESTION: What are they and what are they good for? I do not have a CS degree and my background is VB6 -> ASP -> ASP.NET/C#. Can anyone explain it in a clear and concise manner? ANSWER: Imagine if every single line in your program was a separate function. Each accepts, as a parameter, the next line/function to execute. Using this model, you can "pause" execution at any line and continue it later. You can also do inventive things like temporarily hop up the execution stack to retrieve a value, or save the current execution state to a database to retrieve later.
[ "functional-programming", "continuations", "callcc" ]
34
42
3,501
9
0
2008-09-02T20:55:13.353000
2008-09-02T20:57:53.410000
40,637
40,785
Insert current date in Excel template at creation
I'm building an excel template (*.xlt) for a user here, and one of the things I want to do is have it insert the current date when a new document is created (ie, when they double-click the file in windows explorer). How do I do this? Update: I should have added that I would prefer not to use any vba (macro). If that's the only option, then so be it, but I'd really like to avoid forcing my user to remember to click some 'allow macro content' button.
You could use the worksheet function =TODAY(), but obviously this would be updated to the current date whenever the workbook is recalculated. The only other method I can think of is, as 1729 said, to code the Workbook_Open event: Private Sub Workbook_Open() ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = Date End Sub You can reduce the problem of needing the user to accept macros each time by digitaly signing the template (in VBA IDE Tools | Digital Signature...) and select a digital certificate, however, you will need to get a certificate from a commercial certification authority (see http://msdn.microsoft.com/en-us/library/ms995347.aspx ). The user will need to select to always trust this certificate the first time they run the template, but thereafter, they will not be prompted again.
Insert current date in Excel template at creation I'm building an excel template (*.xlt) for a user here, and one of the things I want to do is have it insert the current date when a new document is created (ie, when they double-click the file in windows explorer). How do I do this? Update: I should have added that I would prefer not to use any vba (macro). If that's the only option, then so be it, but I'd really like to avoid forcing my user to remember to click some 'allow macro content' button.
TITLE: Insert current date in Excel template at creation QUESTION: I'm building an excel template (*.xlt) for a user here, and one of the things I want to do is have it insert the current date when a new document is created (ie, when they double-click the file in windows explorer). How do I do this? Update: I should have added that I would prefer not to use any vba (macro). If that's the only option, then so be it, but I'd really like to avoid forcing my user to remember to click some 'allow macro content' button. ANSWER: You could use the worksheet function =TODAY(), but obviously this would be updated to the current date whenever the workbook is recalculated. The only other method I can think of is, as 1729 said, to code the Workbook_Open event: Private Sub Workbook_Open() ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = Date End Sub You can reduce the problem of needing the user to accept macros each time by digitaly signing the template (in VBA IDE Tools | Digital Signature...) and select a digital certificate, however, you will need to get a certificate from a commercial certification authority (see http://msdn.microsoft.com/en-us/library/ms995347.aspx ). The user will need to select to always trust this certificate the first time they run the template, but thereafter, they will not be prompted again.
[ "excel", "templates" ]
4
4
6,362
3
0
2008-09-02T20:56:12.837000
2008-09-02T22:06:16.660000
40,663
40,678
Validating a HUGE XML file
I'm trying to find a way to validate a large XML file against an XSD. I saw the question...best way to validate an XML... but the answers all pointed to using the Xerces library for validation. The only problem is, when I use that library to validate a 180 MB file then I get an OutOfMemoryException. Are there any other tools,libraries, strategies for validating a larger than normal XML file? EDIT: The SAX solution worked for java validation, but the other two suggestions for the libxml tool were very helpful as well for validation outside of java.
Instead of using a DOMParser, use a SAXParser. This reads from an input stream or reader so you can keep the XML on disk instead of loading it all into memory. SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); factory.setNamespaceAware(true); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(new SimpleErrorHandler()); reader.parse(new InputSource(new FileReader ("document.xml")));
Validating a HUGE XML file I'm trying to find a way to validate a large XML file against an XSD. I saw the question...best way to validate an XML... but the answers all pointed to using the Xerces library for validation. The only problem is, when I use that library to validate a 180 MB file then I get an OutOfMemoryException. Are there any other tools,libraries, strategies for validating a larger than normal XML file? EDIT: The SAX solution worked for java validation, but the other two suggestions for the libxml tool were very helpful as well for validation outside of java.
TITLE: Validating a HUGE XML file QUESTION: I'm trying to find a way to validate a large XML file against an XSD. I saw the question...best way to validate an XML... but the answers all pointed to using the Xerces library for validation. The only problem is, when I use that library to validate a 180 MB file then I get an OutOfMemoryException. Are there any other tools,libraries, strategies for validating a larger than normal XML file? EDIT: The SAX solution worked for java validation, but the other two suggestions for the libxml tool were very helpful as well for validation outside of java. ANSWER: Instead of using a DOMParser, use a SAXParser. This reads from an input stream or reader so you can keep the XML on disk instead of loading it all into memory. SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); factory.setNamespaceAware(true); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(new SimpleErrorHandler()); reader.parse(new InputSource(new FileReader ("document.xml")));
[ "java", "xml", "validation", "xsd" ]
31
30
12,965
4
0
2008-09-02T21:04:39.430000
2008-09-02T21:09:16.440000
40,665
40,684
*= in Sybase SQL
I'm maintaining some code that uses a *= operator in a query to a Sybase database and I can't find documentation on it. Does anyone know what *= does? I assume that it is some sort of a join. select * from a, b where a.id *= b.id I can't figure out how this is different from: select * from a, b where a.id = b.id
From http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc34982_1500/html/mig_gde/mig_gde160.htm: Inner and outer tables The terms outer table and inner table describe the placement of the tables in an outer join: In a left join, the outer table and inner table are the left and right tables respectively. The outer table and inner table are also referred to as the row-preserving and null-supplying tables, respectively. In a right join, the outer table and inner table are the right and left tables respectively. For example, in the queries below, T1 is the outer table and T2 is the inner table: T1 left join T2 T2 right join T1 Or, using Transact-SQL syntax: T1 *= T2 T2 =* T1
*= in Sybase SQL I'm maintaining some code that uses a *= operator in a query to a Sybase database and I can't find documentation on it. Does anyone know what *= does? I assume that it is some sort of a join. select * from a, b where a.id *= b.id I can't figure out how this is different from: select * from a, b where a.id = b.id
TITLE: *= in Sybase SQL QUESTION: I'm maintaining some code that uses a *= operator in a query to a Sybase database and I can't find documentation on it. Does anyone know what *= does? I assume that it is some sort of a join. select * from a, b where a.id *= b.id I can't figure out how this is different from: select * from a, b where a.id = b.id ANSWER: From http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc34982_1500/html/mig_gde/mig_gde160.htm: Inner and outer tables The terms outer table and inner table describe the placement of the tables in an outer join: In a left join, the outer table and inner table are the left and right tables respectively. The outer table and inner table are also referred to as the row-preserving and null-supplying tables, respectively. In a right join, the outer table and inner table are the right and left tables respectively. For example, in the queries below, T1 is the outer table and T2 is the inner table: T1 left join T2 T2 right join T1 Or, using Transact-SQL syntax: T1 *= T2 T2 =* T1
[ "sql", "t-sql", "join", "sybase" ]
10
15
22,252
5
0
2008-09-02T21:05:07.307000
2008-09-02T21:11:33.190000
40,680
41,149
How do I get the full url of the page I am on in C#
I need to be able to get at the full URL of the page I am on from a user control. Is it just a matter of concatenating a bunch of Request variables together? If so which ones? Or is there a more simpiler way?
I usually use Request.Url.ToString() to get the full url (including querystring), no concatenation required.
How do I get the full url of the page I am on in C# I need to be able to get at the full URL of the page I am on from a user control. Is it just a matter of concatenating a bunch of Request variables together? If so which ones? Or is there a more simpiler way?
TITLE: How do I get the full url of the page I am on in C# QUESTION: I need to be able to get at the full URL of the page I am on from a user control. Is it just a matter of concatenating a bunch of Request variables together? If so which ones? Or is there a more simpiler way? ANSWER: I usually use Request.Url.ToString() to get the full url (including querystring), no concatenation required.
[ "c#", "asp.net", "user-controls" ]
178
160
226,395
11
0
2008-09-02T21:09:44.113000
2008-09-03T03:49:18.537000
40,689
41,566
Tips / Resources for building a Google Chrome plugin
After test driving Google Chrome for 30 minutes or so, I like it, even if it seems bare-bones at the moment. The obvious way to add a few things I can't live without would be through plugins. Does anyone have any links to resources on how to get started building a plugin/addon for Chrome? Thanks.
Matt Cutts (the Google SEO guru) has a Q&A about chrome, and writes about it: Q: But I can’t install extension X! Google Chrome is dead to me if I can’t use extension X! A: Then you’ll have to use another browser for a while. Google Chrome currently doesn’t support browser extensions (it does support plug-ins, such as Flash). I’m sure that extensions/add-ons are something that the Chrome team would like to do down the road, but the Chrome team will be a bit busy for a while, what with the feedback from the launch plus working on Mac and Linux support. I’d suggest that you give Google Chrome a try for a few days to see if enjoy browsing even without extension X. A lot of really cool extension-like behaviors such as resize-able textareas and drag-and-drop file upload are already built into Google Chrome.
Tips / Resources for building a Google Chrome plugin After test driving Google Chrome for 30 minutes or so, I like it, even if it seems bare-bones at the moment. The obvious way to add a few things I can't live without would be through plugins. Does anyone have any links to resources on how to get started building a plugin/addon for Chrome? Thanks.
TITLE: Tips / Resources for building a Google Chrome plugin QUESTION: After test driving Google Chrome for 30 minutes or so, I like it, even if it seems bare-bones at the moment. The obvious way to add a few things I can't live without would be through plugins. Does anyone have any links to resources on how to get started building a plugin/addon for Chrome? Thanks. ANSWER: Matt Cutts (the Google SEO guru) has a Q&A about chrome, and writes about it: Q: But I can’t install extension X! Google Chrome is dead to me if I can’t use extension X! A: Then you’ll have to use another browser for a while. Google Chrome currently doesn’t support browser extensions (it does support plug-ins, such as Flash). I’m sure that extensions/add-ons are something that the Chrome team would like to do down the road, but the Chrome team will be a bit busy for a while, what with the feedback from the launch plus working on Mac and Linux support. I’d suggest that you give Google Chrome a try for a few days to see if enjoy browsing even without extension X. A lot of really cool extension-like behaviors such as resize-able textareas and drag-and-drop file upload are already built into Google Chrome.
[ "browser", "plugins", "google-chrome" ]
20
9
6,612
6
0
2008-09-02T21:13:11.860000
2008-09-03T12:38:11.963000
40,692
40,728
Possible to create REST web service with ASP.NET 2.0
Is it possible to create a REST web service using ASP.NET 2.0? The articles and blog entries I am finding all seem to indicate that ASP.NET 3.5 with WCF is required to create REST web services with ASP.NET. If it is possible to create REST web services in ASP.NET 2.0 can you provide an example. Thanks!
I have actually created a REST web service with asp.net 2.0. Its really no different than creating a web page. When I did it, I really didn't have much time to research how to do it with an asmx file so I did it in a standard aspx file. I know thier is extra overhead by doing it this way but as a first revision it was fine. protected void PageLoad(object sender, EventArgs e) { using (XmlWriter xm = XmlWriter.Create(Response.OutputStream, GetXmlSettings())) { //do your stuff xm.Flush(); } } /// /// Create Xml Settings object to properly format the output of the xml doc. /// private static XmlWriterSettings GetXmlSettings() { XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.Indent = true; xmlSettings.IndentChars = " "; return xmlSettings; } That should be enough to get you started, I will try and post more later. Also if you need basic authentication for your web service it can be done, but it needs to be done manually if you aren't using active directory.
Possible to create REST web service with ASP.NET 2.0 Is it possible to create a REST web service using ASP.NET 2.0? The articles and blog entries I am finding all seem to indicate that ASP.NET 3.5 with WCF is required to create REST web services with ASP.NET. If it is possible to create REST web services in ASP.NET 2.0 can you provide an example. Thanks!
TITLE: Possible to create REST web service with ASP.NET 2.0 QUESTION: Is it possible to create a REST web service using ASP.NET 2.0? The articles and blog entries I am finding all seem to indicate that ASP.NET 3.5 with WCF is required to create REST web services with ASP.NET. If it is possible to create REST web services in ASP.NET 2.0 can you provide an example. Thanks! ANSWER: I have actually created a REST web service with asp.net 2.0. Its really no different than creating a web page. When I did it, I really didn't have much time to research how to do it with an asmx file so I did it in a standard aspx file. I know thier is extra overhead by doing it this way but as a first revision it was fine. protected void PageLoad(object sender, EventArgs e) { using (XmlWriter xm = XmlWriter.Create(Response.OutputStream, GetXmlSettings())) { //do your stuff xm.Flush(); } } /// /// Create Xml Settings object to properly format the output of the xml doc. /// private static XmlWriterSettings GetXmlSettings() { XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.Indent = true; xmlSettings.IndentChars = " "; return xmlSettings; } That should be enough to get you started, I will try and post more later. Also if you need basic authentication for your web service it can be done, but it needs to be done manually if you aren't using active directory.
[ "web-services", "rest" ]
9
5
13,762
8
0
2008-09-02T21:15:42.210000
2008-09-02T21:28:51.853000
40,703
40,714
Where can I find and submit bug reports on Google's Chrome browser?
It will be important for developers wanting to develop for the chrome browser to be able to review existing bugs (to avoid too much pulling-out of hair), and to add new ones (to improve the thing). Yet I can't seem to find the bug tracking for this project. It is open source, right?
Google is calling it Chromium on Google Code The Chromium Bug Reporting Page is there and has the link to submit bugs listed. (Google Account Required) Here's a direct link to the bug report form.
Where can I find and submit bug reports on Google's Chrome browser? It will be important for developers wanting to develop for the chrome browser to be able to review existing bugs (to avoid too much pulling-out of hair), and to add new ones (to improve the thing). Yet I can't seem to find the bug tracking for this project. It is open source, right?
TITLE: Where can I find and submit bug reports on Google's Chrome browser? QUESTION: It will be important for developers wanting to develop for the chrome browser to be able to review existing bugs (to avoid too much pulling-out of hair), and to add new ones (to improve the thing). Yet I can't seem to find the bug tracking for this project. It is open source, right? ANSWER: Google is calling it Chromium on Google Code The Chromium Bug Reporting Page is there and has the link to submit bugs listed. (Google Account Required) Here's a direct link to the bug report form.
[ "google-chrome", "bug-tracking" ]
167
149
73,734
8
0
2008-09-02T21:19:39.627000
2008-09-02T21:23:45.937000
40,705
40,715
Python deployment and /usr/bin/env portability
At the beginning of all my executable Python scripts I put the shebang line: #!/usr/bin/env python I'm running these scripts on a system where env python yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version: if sys.version_info < (2, 4): raise ImportError("Cannot run with Python version < 2.4") I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of env python and I don't want to force a particular version, as in: #!/usr/bin/env python2.4 I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4. What's the elegant solution? [Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in ~/bin and ensuring your PATH has ~/bin before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?
"env" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory for that python's executable to the path before invoking your script.
Python deployment and /usr/bin/env portability At the beginning of all my executable Python scripts I put the shebang line: #!/usr/bin/env python I'm running these scripts on a system where env python yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version: if sys.version_info < (2, 4): raise ImportError("Cannot run with Python version < 2.4") I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of env python and I don't want to force a particular version, as in: #!/usr/bin/env python2.4 I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4. What's the elegant solution? [Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in ~/bin and ensuring your PATH has ~/bin before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?
TITLE: Python deployment and /usr/bin/env portability QUESTION: At the beginning of all my executable Python scripts I put the shebang line: #!/usr/bin/env python I'm running these scripts on a system where env python yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version: if sys.version_info < (2, 4): raise ImportError("Cannot run with Python version < 2.4") I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of env python and I don't want to force a particular version, as in: #!/usr/bin/env python2.4 I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4. What's the elegant solution? [Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in ~/bin and ensuring your PATH has ~/bin before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks? ANSWER: "env" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory for that python's executable to the path before invoking your script.
[ "python", "executable", "environment", "shebang" ]
13
8
4,764
5
0
2008-09-02T21:21:14.383000
2008-09-02T21:25:40.520000
40,723
40,739
Server centered vs. client centered architecture
For a typical business application, should the focus be on client processing via AJAX i.e. pull the data from the server and process it on the client or would you suggest a more classic ASP.Net approach with the server being responsible for handling most of the UI events? I find it hard to come up with a good 'default architecture' from which to start. Maybe someone has an open source example application which they could recommend.
It really depends on the application and the situation, but just keep in mind that every hit to the server is costly, both in adding load (perhaps minimally), but also in terms of UI responsiveness. I am of the mind that doing things in JavaScript when possible is a good idea, if it can make your UI feel snappier. Of course, it all depends on what you are trying to do, and whether it matters if the UI is snappy (an internal web app probably doesn't NEED extra development to make the UI more attractive and quicker/easier to use, whereas something that is used by the general public by a mass audience probably needs to be as polished and tuned as possible).
Server centered vs. client centered architecture For a typical business application, should the focus be on client processing via AJAX i.e. pull the data from the server and process it on the client or would you suggest a more classic ASP.Net approach with the server being responsible for handling most of the UI events? I find it hard to come up with a good 'default architecture' from which to start. Maybe someone has an open source example application which they could recommend.
TITLE: Server centered vs. client centered architecture QUESTION: For a typical business application, should the focus be on client processing via AJAX i.e. pull the data from the server and process it on the client or would you suggest a more classic ASP.Net approach with the server being responsible for handling most of the UI events? I find it hard to come up with a good 'default architecture' from which to start. Maybe someone has an open source example application which they could recommend. ANSWER: It really depends on the application and the situation, but just keep in mind that every hit to the server is costly, both in adding load (perhaps minimally), but also in terms of UI responsiveness. I am of the mind that doing things in JavaScript when possible is a good idea, if it can make your UI feel snappier. Of course, it all depends on what you are trying to do, and whether it matters if the UI is snappy (an internal web app probably doesn't NEED extra development to make the UI more attractive and quicker/easier to use, whereas something that is used by the general public by a mass audience probably needs to be as polished and tuned as possible).
[ ".net", "architecture" ]
2
1
248
3
0
2008-09-02T21:28:22.820000
2008-09-02T21:34:34.443000
40,730
40,754
What is the best way to give a C# auto-property an initial value?
How do you give a C# auto-property an initial value? I either use the constructor, or revert to the old syntax. Using the Constructor: class Person { public Person() { Name = "Initial Name"; } public string Name { get; set; } } Using normal property syntax (with an initial value) private string name = "Initial Name"; public string Name { get { return name; } set { name = value; } } Is there a better way?
In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor. Since C# 6.0, you can specify initial value in-line. The syntax is: public int X { get; set; } = x; // C# 6 or higher DefaultValueAttribute is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value). At compile time DefaultValueAttribute will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property ). Example of attributes that impact the IL are ThreadStaticAttribute, CallerMemberNameAttribute,...
What is the best way to give a C# auto-property an initial value? How do you give a C# auto-property an initial value? I either use the constructor, or revert to the old syntax. Using the Constructor: class Person { public Person() { Name = "Initial Name"; } public string Name { get; set; } } Using normal property syntax (with an initial value) private string name = "Initial Name"; public string Name { get { return name; } set { name = value; } } Is there a better way?
TITLE: What is the best way to give a C# auto-property an initial value? QUESTION: How do you give a C# auto-property an initial value? I either use the constructor, or revert to the old syntax. Using the Constructor: class Person { public Person() { Name = "Initial Name"; } public string Name { get; set; } } Using normal property syntax (with an initial value) private string name = "Initial Name"; public string Name { get { return name; } set { name = value; } } Is there a better way? ANSWER: In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor. Since C# 6.0, you can specify initial value in-line. The syntax is: public int X { get; set; } = x; // C# 6 or higher DefaultValueAttribute is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value). At compile time DefaultValueAttribute will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property ). Example of attributes that impact the IL are ThreadStaticAttribute, CallerMemberNameAttribute,...
[ "c#", "constructor", "getter", "setter", "automatic-properties" ]
2,323
2,948
1,253,745
23
0
2008-09-02T21:29:41.227000
2008-09-02T21:46:23.683000
40,733
3,211,015
Disable WPF label accelerator key (text underscore is missing)
I am setting the.Content value of a Label to a string that contains underscores; the first underscore is being interpreted as an accelerator key. Without changing the underlying string (by replacing all _ with __ ), is there a way to disable the accelerator for Labels?
If you use a TextBlock as the Content of the Label, its Text will not absorb underscores.
Disable WPF label accelerator key (text underscore is missing) I am setting the.Content value of a Label to a string that contains underscores; the first underscore is being interpreted as an accelerator key. Without changing the underlying string (by replacing all _ with __ ), is there a way to disable the accelerator for Labels?
TITLE: Disable WPF label accelerator key (text underscore is missing) QUESTION: I am setting the.Content value of a Label to a string that contains underscores; the first underscore is being interpreted as an accelerator key. Without changing the underlying string (by replacing all _ with __ ), is there a way to disable the accelerator for Labels? ANSWER: If you use a TextBlock as the Content of the Label, its Text will not absorb underscores.
[ "wpf", "user-interface" ]
65
95
31,875
5
0
2008-09-02T21:32:37.320000
2010-07-09T08:24:02.263000
40,737
43,733
Generate disk usage graphs/charts with CLI only tools in Linux
In this question someone asked for ways to display disk usage in Linux. I'd like to take this one step further down the cli-path... how about a shell script that takes the output from something like a reasonable answer to the previous question and generates a graph/chart from it (output in a png file or something)? This may be a bit too much code to ask for in a regular question, but my guess is that someone already has a oneliner laying around somewhere...
I would recommend munin. It is designed for exactly this sort of thing - graphing CPU usage, memory usage, disc-usage and such. sort of like MRTG (but MRTG is primarily aimed at graphing router's traffic, graphing anything but bandwidth with it is very hackish) Writing Munin plugins is very easy (it was one of the projects goals). They can be written in almost anything (shell script, perl/python/ruby/etc, C, anything that can be execute and produce an output). The plugin output format is basically disc1usage.value 1234. And debugging the plugins is very easy (compared to MRTG) I've set it up on my laptop to monitor disc-usage, bandwidth usage (by pulling data from my ISP's control panel, it graphs my two download "bins", uploads and newsgroup usage), load average and number of processes. Once I got it installed (currently slightly difficult on OS X, but it's trivial on Linux/FreeBSD), I had written a plugin in a few minutes, and it worked, first time! I would describe how it's setup, but the munin site will do that far better than I could! There's an example installation here Some alternatives are nagios and cacti. You could also write something similar using rrdtool. Munin, MRTG and Cacti are basically all far-nicer-to-use systems based around this graphing tool. If you want something really, really simple, you could do.. import os import time while True: disc_usage = os.system("df -h / | awk '{print $3}'") log = open("mylog.txt") log.write(disc_usage + "\n") log.close() time.sleep(60*5) Then.. f = open("mylog.txt") lines = f.readlines() # Convert each line to a float number lines = [float(cur_line) for cur_line in lines] # Get the biggest and smallest biggest = max(lines) smallest = min(lines) for cur_line in lines: base = (cur_line - smallest) + 1 # make lowest value 1 normalised = base / (biggest - smallest) # normalise value between 0 and 1 line_length = int(round(normalised * 28)) # make a graph between 0 and 28 characters wide print "#" * line_length That'll make a simple ascii graph of the disc usage. I really really don't recommend you use something like this. Why? The log file will get bigger, and bigger, and bigger. The graph will get progressively slower to graph. RRDTool uses a rolling-database system to store it's data, so the file will never get bigger than about 50-100KB, and it's consistently quick to graph as the file is a fixed length. In short. If you want something to easily graph almost anything, use munin. If you want something smaller and self-contained, write something with RRDTool.
Generate disk usage graphs/charts with CLI only tools in Linux In this question someone asked for ways to display disk usage in Linux. I'd like to take this one step further down the cli-path... how about a shell script that takes the output from something like a reasonable answer to the previous question and generates a graph/chart from it (output in a png file or something)? This may be a bit too much code to ask for in a regular question, but my guess is that someone already has a oneliner laying around somewhere...
TITLE: Generate disk usage graphs/charts with CLI only tools in Linux QUESTION: In this question someone asked for ways to display disk usage in Linux. I'd like to take this one step further down the cli-path... how about a shell script that takes the output from something like a reasonable answer to the previous question and generates a graph/chart from it (output in a png file or something)? This may be a bit too much code to ask for in a regular question, but my guess is that someone already has a oneliner laying around somewhere... ANSWER: I would recommend munin. It is designed for exactly this sort of thing - graphing CPU usage, memory usage, disc-usage and such. sort of like MRTG (but MRTG is primarily aimed at graphing router's traffic, graphing anything but bandwidth with it is very hackish) Writing Munin plugins is very easy (it was one of the projects goals). They can be written in almost anything (shell script, perl/python/ruby/etc, C, anything that can be execute and produce an output). The plugin output format is basically disc1usage.value 1234. And debugging the plugins is very easy (compared to MRTG) I've set it up on my laptop to monitor disc-usage, bandwidth usage (by pulling data from my ISP's control panel, it graphs my two download "bins", uploads and newsgroup usage), load average and number of processes. Once I got it installed (currently slightly difficult on OS X, but it's trivial on Linux/FreeBSD), I had written a plugin in a few minutes, and it worked, first time! I would describe how it's setup, but the munin site will do that far better than I could! There's an example installation here Some alternatives are nagios and cacti. You could also write something similar using rrdtool. Munin, MRTG and Cacti are basically all far-nicer-to-use systems based around this graphing tool. If you want something really, really simple, you could do.. import os import time while True: disc_usage = os.system("df -h / | awk '{print $3}'") log = open("mylog.txt") log.write(disc_usage + "\n") log.close() time.sleep(60*5) Then.. f = open("mylog.txt") lines = f.readlines() # Convert each line to a float number lines = [float(cur_line) for cur_line in lines] # Get the biggest and smallest biggest = max(lines) smallest = min(lines) for cur_line in lines: base = (cur_line - smallest) + 1 # make lowest value 1 normalised = base / (biggest - smallest) # normalise value between 0 and 1 line_length = int(round(normalised * 28)) # make a graph between 0 and 28 characters wide print "#" * line_length That'll make a simple ascii graph of the disc usage. I really really don't recommend you use something like this. Why? The log file will get bigger, and bigger, and bigger. The graph will get progressively slower to graph. RRDTool uses a rolling-database system to store it's data, so the file will never get bigger than about 50-100KB, and it's consistently quick to graph as the file is a fixed length. In short. If you want something to easily graph almost anything, use munin. If you want something smaller and self-contained, write something with RRDTool.
[ "linux", "shell", "storage", "diskspace", "disk" ]
11
6
14,909
4
0
2008-09-02T21:33:39.970000
2008-09-04T13:16:00.850000
40,764
40,782
How should I cast in VB.NET?
Are all of these equal? Under what circumstances should I choose each over the others? var.ToString() CStr(var) CType(var, String) DirectCast(var, String) EDIT: Suggestion from NotMyself … TryCast(var, String)
Those are all slightly different, and generally have an acceptable usage. var. ToString () is going to give you the string representation of an object, regardless of what type it is. Use this if var is not a string already. CStr (var) is the VB string cast operator. I'm not a VB guy, so I would suggest avoiding it, but it's not really going to hurt anything. I think it is basically the same as CType. CType (var, String) will convert the given type into a string, using any provided conversion operators. DirectCast (var, String) is used to up-cast an object into a string. If you know that an object variable is, in fact, a string, use this. This is the same as (string)var in C#. TryCast (as mentioned by @ NotMyself ) is like DirectCast, but it will return Nothing if the variable can't be converted into a string, rather than throwing an exception. This is the same as var as string in C#. The TryCast page on MSDN has a good comparison, too.
How should I cast in VB.NET? Are all of these equal? Under what circumstances should I choose each over the others? var.ToString() CStr(var) CType(var, String) DirectCast(var, String) EDIT: Suggestion from NotMyself … TryCast(var, String)
TITLE: How should I cast in VB.NET? QUESTION: Are all of these equal? Under what circumstances should I choose each over the others? var.ToString() CStr(var) CType(var, String) DirectCast(var, String) EDIT: Suggestion from NotMyself … TryCast(var, String) ANSWER: Those are all slightly different, and generally have an acceptable usage. var. ToString () is going to give you the string representation of an object, regardless of what type it is. Use this if var is not a string already. CStr (var) is the VB string cast operator. I'm not a VB guy, so I would suggest avoiding it, but it's not really going to hurt anything. I think it is basically the same as CType. CType (var, String) will convert the given type into a string, using any provided conversion operators. DirectCast (var, String) is used to up-cast an object into a string. If you know that an object variable is, in fact, a string, use this. This is the same as (string)var in C#. TryCast (as mentioned by @ NotMyself ) is like DirectCast, but it will return Nothing if the variable can't be converted into a string, rather than throwing an exception. This is the same as var as string in C#. The TryCast page on MSDN has a good comparison, too.
[ ".net", "vb.net", "casting" ]
163
175
191,876
7
0
2008-09-02T21:49:32.910000
2008-09-02T22:03:59.413000
40,769
40,871
Path to Program-Files on remote computer
How do I determine the (local-) path for the "Program Files" directory on a remote computer? There does not appear to any version of SHGetFolderPath (or related function) that takes the name of a remote computer as a parameter. I guess I could try to query HKLM\Software\Microsoft\Windows\CurrentVersion\ProgramFilesDir using remote-registry, but I was hoping there would be "documented" way of doing it.
Many of the standard paths require a user to be logged in, especially the SH* functions as those are provided by the "shell", that is, Explorer. I suspect the only way you're going to get the right path is through the registry like you already mentioned.
Path to Program-Files on remote computer How do I determine the (local-) path for the "Program Files" directory on a remote computer? There does not appear to any version of SHGetFolderPath (or related function) that takes the name of a remote computer as a parameter. I guess I could try to query HKLM\Software\Microsoft\Windows\CurrentVersion\ProgramFilesDir using remote-registry, but I was hoping there would be "documented" way of doing it.
TITLE: Path to Program-Files on remote computer QUESTION: How do I determine the (local-) path for the "Program Files" directory on a remote computer? There does not appear to any version of SHGetFolderPath (or related function) that takes the name of a remote computer as a parameter. I guess I could try to query HKLM\Software\Microsoft\Windows\CurrentVersion\ProgramFilesDir using remote-registry, but I was hoping there would be "documented" way of doing it. ANSWER: Many of the standard paths require a user to be logged in, especially the SH* functions as those are provided by the "shell", that is, Explorer. I suspect the only way you're going to get the right path is through the registry like you already mentioned.
[ "winapi" ]
1
1
601
2
0
2008-09-02T21:53:21.700000
2008-09-02T23:00:49.120000
40,779
40,793
How to change Build Numbering format in Visual Studio
I've inherited a.NET application that automatically updates it's version number with each release. The problem, as I see it, is the length and number of digits in the version number. An example of the current version number format is 3.5.3167.26981 which is a mouthful for the users to say when they are reporting bugs. What I would like is something more like this: 3.5 (build 3198). I would prefer to manually update the major and minor versions, but have the build number update automatically. Even better, I don't want the build number to increment unless I am compiling in RELEASE mode. Anyone know if there is a way to do this -- and how?
In one of the project files, probably AssemblyInfo.cs, the assembly version attribute is set to [assembly: AssemblyVersion("3.5.*")] or something similar. The * basically means it lets Visual Studio automatically set the build and revision number. You can change this to a hard coded value in the format... You are allowed to use any or all of the precision. For instance 3.5 or 3.5.3167 or 3.5.3167.10000. You can also use compiler conditions to change the versioning based on whether you're doing a debug build or release build.
How to change Build Numbering format in Visual Studio I've inherited a.NET application that automatically updates it's version number with each release. The problem, as I see it, is the length and number of digits in the version number. An example of the current version number format is 3.5.3167.26981 which is a mouthful for the users to say when they are reporting bugs. What I would like is something more like this: 3.5 (build 3198). I would prefer to manually update the major and minor versions, but have the build number update automatically. Even better, I don't want the build number to increment unless I am compiling in RELEASE mode. Anyone know if there is a way to do this -- and how?
TITLE: How to change Build Numbering format in Visual Studio QUESTION: I've inherited a.NET application that automatically updates it's version number with each release. The problem, as I see it, is the length and number of digits in the version number. An example of the current version number format is 3.5.3167.26981 which is a mouthful for the users to say when they are reporting bugs. What I would like is something more like this: 3.5 (build 3198). I would prefer to manually update the major and minor versions, but have the build number update automatically. Even better, I don't want the build number to increment unless I am compiling in RELEASE mode. Anyone know if there is a way to do this -- and how? ANSWER: In one of the project files, probably AssemblyInfo.cs, the assembly version attribute is set to [assembly: AssemblyVersion("3.5.*")] or something similar. The * basically means it lets Visual Studio automatically set the build and revision number. You can change this to a hard coded value in the format... You are allowed to use any or all of the precision. For instance 3.5 or 3.5.3167 or 3.5.3167.10000. You can also use compiler conditions to change the versioning based on whether you're doing a debug build or release build.
[ "visual-studio" ]
7
3
1,519
3
0
2008-09-02T22:02:14.393000
2008-09-02T22:09:40.350000
40,787
40,869
How do I increment a value in a textfile using the regular Windows command-line?
I'd like to keep a "compile-counter" for one of my projects. I figured a quick and dirty way to do this would be to keep a text file with a plain number in it, and then simply call upon a small script to increment this each time I compile. How would I go about doing this using the regular Windows command line? I don't really feel like installing some extra shell to do this but if you have any other super simple suggestions that would accomplish just this, they're naturally appreciated as well.
You can try a plain old batchfile. @echo off for /f " delims==" %%i in (counter.txt) do set /A temp_counter= %%i+1 echo %temp_counter% > counter.txt assuming the count.bat and counter.txt are located in the same directory.
How do I increment a value in a textfile using the regular Windows command-line? I'd like to keep a "compile-counter" for one of my projects. I figured a quick and dirty way to do this would be to keep a text file with a plain number in it, and then simply call upon a small script to increment this each time I compile. How would I go about doing this using the regular Windows command line? I don't really feel like installing some extra shell to do this but if you have any other super simple suggestions that would accomplish just this, they're naturally appreciated as well.
TITLE: How do I increment a value in a textfile using the regular Windows command-line? QUESTION: I'd like to keep a "compile-counter" for one of my projects. I figured a quick and dirty way to do this would be to keep a text file with a plain number in it, and then simply call upon a small script to increment this each time I compile. How would I go about doing this using the regular Windows command line? I don't really feel like installing some extra shell to do this but if you have any other super simple suggestions that would accomplish just this, they're naturally appreciated as well. ANSWER: You can try a plain old batchfile. @echo off for /f " delims==" %%i in (counter.txt) do set /A temp_counter= %%i+1 echo %temp_counter% > counter.txt assuming the count.bat and counter.txt are located in the same directory.
[ "windows", "command-line", "text-files" ]
6
13
5,507
4
0
2008-09-02T22:06:36.613000
2008-09-02T22:59:38.920000
40,814
40,830
Execute a large SQL script (with GO commands)
I need to execute a large set of SQL statements (creating a bunch of tables, views and stored procedures) from within a C# program. These statements need to be separated by GO statements, but SqlCommand.ExecuteNonQuery() does not like GO statements. My solution, which I suppose I'll post for reference, was to split the SQL string on GO lines, and execute each batch separately. Is there an easier/better way?
Use SQL Server Management Objects (SMO) which understands GO separators. See my blog post here: http://weblogs.asp.net/jongalloway/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts- 2D00 -the-easy-way Sample code: public static void Main() { string scriptDirectory = "c:\\temp\\sqltest\\"; string sqlConnectionString = "Integrated Security=SSPI;" + "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)"; DirectoryInfo di = new DirectoryInfo(scriptDirectory); FileInfo[] rgFiles = di.GetFiles("*.sql"); foreach (FileInfo fi in rgFiles) { FileInfo fileInfo = new FileInfo(fi.FullName); string script = fileInfo.OpenText().ReadToEnd(); using (SqlConnection connection = new SqlConnection(sqlConnectionString)) { Server server = new Server(new ServerConnection(connection)); server.ConnectionContext.ExecuteNonQuery(script); } } } If that won't work for you, see Phil Haack's library which handles that: http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators-and.aspx
Execute a large SQL script (with GO commands) I need to execute a large set of SQL statements (creating a bunch of tables, views and stored procedures) from within a C# program. These statements need to be separated by GO statements, but SqlCommand.ExecuteNonQuery() does not like GO statements. My solution, which I suppose I'll post for reference, was to split the SQL string on GO lines, and execute each batch separately. Is there an easier/better way?
TITLE: Execute a large SQL script (with GO commands) QUESTION: I need to execute a large set of SQL statements (creating a bunch of tables, views and stored procedures) from within a C# program. These statements need to be separated by GO statements, but SqlCommand.ExecuteNonQuery() does not like GO statements. My solution, which I suppose I'll post for reference, was to split the SQL string on GO lines, and execute each batch separately. Is there an easier/better way? ANSWER: Use SQL Server Management Objects (SMO) which understands GO separators. See my blog post here: http://weblogs.asp.net/jongalloway/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts- 2D00 -the-easy-way Sample code: public static void Main() { string scriptDirectory = "c:\\temp\\sqltest\\"; string sqlConnectionString = "Integrated Security=SSPI;" + "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)"; DirectoryInfo di = new DirectoryInfo(scriptDirectory); FileInfo[] rgFiles = di.GetFiles("*.sql"); foreach (FileInfo fi in rgFiles) { FileInfo fileInfo = new FileInfo(fi.FullName); string script = fileInfo.OpenText().ReadToEnd(); using (SqlConnection connection = new SqlConnection(sqlConnectionString)) { Server server = new Server(new ServerConnection(connection)); server.ConnectionContext.ExecuteNonQuery(script); } } } If that won't work for you, see Phil Haack's library which handles that: http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators-and.aspx
[ "c#", "sql-server" ]
106
125
130,633
20
0
2008-09-02T22:20:02.353000
2008-09-02T22:29:04.110000
40,816
40,846
Styling HTML helpers ASP.NET MVC
If I have an HTML helper like so: Name: <%=Html.TextBox("txtName",20) %> How do I apply a CSS class to it? Do I have to wrap it in a span? Or do I need to somehow utilize the HtmlAttributes property of the helper?
You can pass it into the TextBox call as a parameter. Name: <%= Html.TextBox("txtName", "20", new { @class = "hello" }) %> This line will create a text box with the value 20 and assign the class attribute with the value hello. I put the @ character in front of the class, because class is a reserved keyword. If you want to add other attributes, just separate the key/value pairs with commas.
Styling HTML helpers ASP.NET MVC If I have an HTML helper like so: Name: <%=Html.TextBox("txtName",20) %> How do I apply a CSS class to it? Do I have to wrap it in a span? Or do I need to somehow utilize the HtmlAttributes property of the helper?
TITLE: Styling HTML helpers ASP.NET MVC QUESTION: If I have an HTML helper like so: Name: <%=Html.TextBox("txtName",20) %> How do I apply a CSS class to it? Do I have to wrap it in a span? Or do I need to somehow utilize the HtmlAttributes property of the helper? ANSWER: You can pass it into the TextBox call as a parameter. Name: <%= Html.TextBox("txtName", "20", new { @class = "hello" }) %> This line will create a text box with the value 20 and assign the class attribute with the value hello. I put the @ character in front of the class, because class is a reserved keyword. If you want to add other attributes, just separate the key/value pairs with commas.
[ "css", "asp.net-mvc", "html-helper" ]
24
38
61,441
7
0
2008-09-02T22:21:17.827000
2008-09-02T22:37:58.427000
40,840
40,866
Cannot create an environment variable in the registry
I have a custom installer action that updates the PATH environment, and creates an additional environment variable. Appending a directory to the existing path variable is working fine, but for some reason my attempts to create a new environment variable have been unsuccessful. The code I am using is: using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) { reg.SetValue("MYVAR", "SomeVal", RegistryValueKind.ExpandString); } Edit: The OS is 32-bit XP, and as far as I can tell it is failing silently.
Is there any reason that you have to do it through the registry? If not, you can use Environment.SetEnvironmentVariable() since.NET 2.0. It allows you to set on a machine, process or user basis.
Cannot create an environment variable in the registry I have a custom installer action that updates the PATH environment, and creates an additional environment variable. Appending a directory to the existing path variable is working fine, but for some reason my attempts to create a new environment variable have been unsuccessful. The code I am using is: using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) { reg.SetValue("MYVAR", "SomeVal", RegistryValueKind.ExpandString); } Edit: The OS is 32-bit XP, and as far as I can tell it is failing silently.
TITLE: Cannot create an environment variable in the registry QUESTION: I have a custom installer action that updates the PATH environment, and creates an additional environment variable. Appending a directory to the existing path variable is working fine, but for some reason my attempts to create a new environment variable have been unsuccessful. The code I am using is: using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) { reg.SetValue("MYVAR", "SomeVal", RegistryValueKind.ExpandString); } Edit: The OS is 32-bit XP, and as far as I can tell it is failing silently. ANSWER: Is there any reason that you have to do it through the registry? If not, you can use Environment.SetEnvironmentVariable() since.NET 2.0. It allows you to set on a machine, process or user basis.
[ "c#", "registry", "environment" ]
0
1
1,148
4
0
2008-09-02T22:34:03.630000
2008-09-02T22:58:11.437000
40,845
40,891
How do F# units of measure work?
Has anyone had a chance to dig into how F# Units of Measure work? Is it just type-based chicanery, or are there CLR types hiding underneath that could (potentially) be used from other.net languages? Will it work for any numerical unit, or is it limited to floating point values (which is what all the examples use)?
According to a response on the next related blog post, they are a purely static mechanism in the F# compiler. So there is no CLR representation of the units data. Its not entirely clear whether it currently works with non-float types, but from the perspective of the type system it is theoretically possible.
How do F# units of measure work? Has anyone had a chance to dig into how F# Units of Measure work? Is it just type-based chicanery, or are there CLR types hiding underneath that could (potentially) be used from other.net languages? Will it work for any numerical unit, or is it limited to floating point values (which is what all the examples use)?
TITLE: How do F# units of measure work? QUESTION: Has anyone had a chance to dig into how F# Units of Measure work? Is it just type-based chicanery, or are there CLR types hiding underneath that could (potentially) be used from other.net languages? Will it work for any numerical unit, or is it limited to floating point values (which is what all the examples use)? ANSWER: According to a response on the next related blog post, they are a purely static mechanism in the F# compiler. So there is no CLR representation of the units data. Its not entirely clear whether it currently works with non-float types, but from the perspective of the type system it is theoretically possible.
[ ".net", "f#", "functional-programming", "units-of-measurement" ]
17
14
5,397
2
0
2008-09-02T22:37:37.163000
2008-09-02T23:12:40.963000
40,853
40,867
How to store passwords in Winforms application?
I have some code like this in a winforms app I was writing to query a user's mail box Storage Quota. DirectoryEntry mbstore = new DirectoryEntry( @"LDAP://" + strhome, m_serviceaccount, [m_pwd], AuthenticationTypes.Secure); No matter what approach I tried (like SecureString ), I am easily able to see the password ( m_pwd ) either using Reflector or using strings tab of Process Explorer for the executable. I know I could put this code on the server or tighten up the security using mechanisms like delegation and giving only the required privileges to the service account. Can somebody suggest a reasonably secure way to store the password in the local application without revealing the password to hackers? Hashing is not possible since I need to know the exact password (not just the hash for matching purpose). Encryption/Decryption mechanisms are not working since they are machine dependent.
The sanctified method is to use CryptoAPI and the Data Protection APIs. To encrypt, use something like this (C++): DATA_BLOB blobIn, blobOut; blobIn.pbData=(BYTE*)data; blobIn.cbData=wcslen(data)*sizeof(WCHAR); CryptProtectData(&blobIn, description, NULL, NULL, NULL, CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN, &blobOut); _encrypted=blobOut.pbData; _length=blobOut.cbData; Decryption is the opposite: DATA_BLOB blobIn, blobOut; blobIn.pbData=const_cast (data); blobIn.cbData=length; CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &blobOut); std::wstring _decrypted; _decrypted.assign((LPCWSTR)blobOut.pbData,(LPCWSTR)blobOut.pbData+blobOut.cbData/sizeof(WCHAR)); If you don't specify CRYPTPROTECT_LOCAL_MACHINE then the encrypted password can be securely stored in the registry or config file and only you can decrypt it. If you specify LOCAL_MACHINE, then anyone with access to the machine can get it.
How to store passwords in Winforms application? I have some code like this in a winforms app I was writing to query a user's mail box Storage Quota. DirectoryEntry mbstore = new DirectoryEntry( @"LDAP://" + strhome, m_serviceaccount, [m_pwd], AuthenticationTypes.Secure); No matter what approach I tried (like SecureString ), I am easily able to see the password ( m_pwd ) either using Reflector or using strings tab of Process Explorer for the executable. I know I could put this code on the server or tighten up the security using mechanisms like delegation and giving only the required privileges to the service account. Can somebody suggest a reasonably secure way to store the password in the local application without revealing the password to hackers? Hashing is not possible since I need to know the exact password (not just the hash for matching purpose). Encryption/Decryption mechanisms are not working since they are machine dependent.
TITLE: How to store passwords in Winforms application? QUESTION: I have some code like this in a winforms app I was writing to query a user's mail box Storage Quota. DirectoryEntry mbstore = new DirectoryEntry( @"LDAP://" + strhome, m_serviceaccount, [m_pwd], AuthenticationTypes.Secure); No matter what approach I tried (like SecureString ), I am easily able to see the password ( m_pwd ) either using Reflector or using strings tab of Process Explorer for the executable. I know I could put this code on the server or tighten up the security using mechanisms like delegation and giving only the required privileges to the service account. Can somebody suggest a reasonably secure way to store the password in the local application without revealing the password to hackers? Hashing is not possible since I need to know the exact password (not just the hash for matching purpose). Encryption/Decryption mechanisms are not working since they are machine dependent. ANSWER: The sanctified method is to use CryptoAPI and the Data Protection APIs. To encrypt, use something like this (C++): DATA_BLOB blobIn, blobOut; blobIn.pbData=(BYTE*)data; blobIn.cbData=wcslen(data)*sizeof(WCHAR); CryptProtectData(&blobIn, description, NULL, NULL, NULL, CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN, &blobOut); _encrypted=blobOut.pbData; _length=blobOut.cbData; Decryption is the opposite: DATA_BLOB blobIn, blobOut; blobIn.pbData=const_cast (data); blobIn.cbData=length; CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &blobOut); std::wstring _decrypted; _decrypted.assign((LPCWSTR)blobOut.pbData,(LPCWSTR)blobOut.pbData+blobOut.cbData/sizeof(WCHAR)); If you don't specify CRYPTPROTECT_LOCAL_MACHINE then the encrypted password can be securely stored in the registry or config file and only you can decrypt it. If you specify LOCAL_MACHINE, then anyone with access to the machine can get it.
[ "winforms", "security", "passwords" ]
32
27
19,035
4
0
2008-09-02T22:43:39.520000
2008-09-02T22:58:13.183000
40,863
41,206
Business Application UI Design
Basically I'm going to go a bit broad here and ask a few questions to get a bit of a picture of how people are handling UI these days. Lately I've found it pretty easy to do some fancy things with UI design and with WPF specifically we're finding new ways to do layouts that are better looking and more functional for the user, but in contrast one of the business focused guys at our local.NET User Group wouldn't even think of using WPF until it had a datagrid that he could use to make Excel like input forms. So basically, have you rethought the design of your business apps as you move to Web/WPF/Silverlight designs, because for us at least - in winforms we kept things fairly functional and uniform, or are you trying to keep that "known" UI? Would a dedicated design guy (for larger teams), or a dev with more design chops rank higher when looking at hiring these days? (Check out what a designer did for Scott Hanselman's BabySmash and Microsoft's Prism demo ) Are there any design hints/tips/guidelines you use for your UI - especially for WPF? What sites would you recommend for design?
I recommend that you read Steve Krug's Don't Make Me Think first. The book has a great checklist of things that you have to take into consideration when designing your UIs. While it's focused on web usability, a lot of the lessons therein are valuable even to desktop application designers. That being said, whether you use Windows forms or WPF or Flash or whatever new and shiny thing that comes around is, it is of utmost importance to hire either a) a real designer, or b) a development guy with a lot of UI design experience, either of which who can provide you a serious URL for their design portfolio. It will help a lot not only in improving the design of your application but also unburdening your developers from thinking about UI design, and allow them to focus on the back-end code. As for "business focused" guys -- it would be really great if you would get the opinion of actual customers and stake holders, and have them do some usability testing for your application. It's their opinion that would matter most. I think it would not be difficult to get a good designer up to speed on Microsoft Expression Blend to whip up some good XAML designs that your team could use to come up with a really good product.
Business Application UI Design Basically I'm going to go a bit broad here and ask a few questions to get a bit of a picture of how people are handling UI these days. Lately I've found it pretty easy to do some fancy things with UI design and with WPF specifically we're finding new ways to do layouts that are better looking and more functional for the user, but in contrast one of the business focused guys at our local.NET User Group wouldn't even think of using WPF until it had a datagrid that he could use to make Excel like input forms. So basically, have you rethought the design of your business apps as you move to Web/WPF/Silverlight designs, because for us at least - in winforms we kept things fairly functional and uniform, or are you trying to keep that "known" UI? Would a dedicated design guy (for larger teams), or a dev with more design chops rank higher when looking at hiring these days? (Check out what a designer did for Scott Hanselman's BabySmash and Microsoft's Prism demo ) Are there any design hints/tips/guidelines you use for your UI - especially for WPF? What sites would you recommend for design?
TITLE: Business Application UI Design QUESTION: Basically I'm going to go a bit broad here and ask a few questions to get a bit of a picture of how people are handling UI these days. Lately I've found it pretty easy to do some fancy things with UI design and with WPF specifically we're finding new ways to do layouts that are better looking and more functional for the user, but in contrast one of the business focused guys at our local.NET User Group wouldn't even think of using WPF until it had a datagrid that he could use to make Excel like input forms. So basically, have you rethought the design of your business apps as you move to Web/WPF/Silverlight designs, because for us at least - in winforms we kept things fairly functional and uniform, or are you trying to keep that "known" UI? Would a dedicated design guy (for larger teams), or a dev with more design chops rank higher when looking at hiring these days? (Check out what a designer did for Scott Hanselman's BabySmash and Microsoft's Prism demo ) Are there any design hints/tips/guidelines you use for your UI - especially for WPF? What sites would you recommend for design? ANSWER: I recommend that you read Steve Krug's Don't Make Me Think first. The book has a great checklist of things that you have to take into consideration when designing your UIs. While it's focused on web usability, a lot of the lessons therein are valuable even to desktop application designers. That being said, whether you use Windows forms or WPF or Flash or whatever new and shiny thing that comes around is, it is of utmost importance to hire either a) a real designer, or b) a development guy with a lot of UI design experience, either of which who can provide you a serious URL for their design portfolio. It will help a lot not only in improving the design of your application but also unburdening your developers from thinking about UI design, and allow them to focus on the back-end code. As for "business focused" guys -- it would be really great if you would get the opinion of actual customers and stake holders, and have them do some usability testing for your application. It's their opinion that would matter most. I think it would not be difficult to get a good designer up to speed on Microsoft Expression Blend to whip up some good XAML designs that your team could use to come up with a really good product.
[ "wpf", "user-interface" ]
20
12
7,345
8
0
2008-09-02T22:56:14.217000
2008-09-03T05:25:38.477000
40,873
41,016
Searching for phone numbers in mysql
I have a table which is full of arbitrarily formatted phone numbers, like this 027 123 5644 021 393-5593 (07) 123 456 042123456 I need to search for a phone number in a similarly arbitrary format ( e.g. 07123456 should find the entry (07) 123 456 The way I'd do this in a normal programming language is to strip all the non-digit characters out of the 'needle', then go through each number in the haystack, strip all non-digit characters out of it, then compare against the needle, eg (in ruby) digits_only = lambda{ |n| n.gsub /[^\d]/, '' } needle = digits_only[input_phone_number] haystack.map(&digits_only).include?(needle) The catch is, I need to do this in MySQL. It has a host of string functions, none of which really seem to do what I want. Currently I can think of 2 'solutions' Hack together a franken-query of CONCAT and SUBSTR Insert a % between every character of the needle ( so it's like this: %0%7%1%2%3%4%5%6% ) However, neither of these seem like particularly elegant solutions. Hopefully someone can help or I might be forced to use the %%%%%% solution Update: This is operating over a relatively fixed set of data, with maybe a few hundred rows. I just didn't want to do something ridiculously bad that future programmers would cry over. If the dataset grows I'll take the 'phoneStripped' approach. Thanks for all the feedback! could you use a "replace" function to strip out any instances of "(", "-" and " ", I'm not concerned about the result being numeric. The main characters I need to consider are +, -, (, ) and space So would that solution look like this? SELECT * FROM people WHERE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phonenumber, '('),')'),'-'),' '),'+') LIKE '123456' Wouldn't that be terribly slow?
This looks like a problem from the start. Any kind of searching you do will require a table scan and we all know that's bad. How about adding a column with a hash of the current phone numbers after stripping out all formatting characters. Then you can at least index the hash values and avoid a full blown table scan. Or is the amount of data small and not expected to grow much? Then maybe just sucking all the numbers into the client and running a search there.
Searching for phone numbers in mysql I have a table which is full of arbitrarily formatted phone numbers, like this 027 123 5644 021 393-5593 (07) 123 456 042123456 I need to search for a phone number in a similarly arbitrary format ( e.g. 07123456 should find the entry (07) 123 456 The way I'd do this in a normal programming language is to strip all the non-digit characters out of the 'needle', then go through each number in the haystack, strip all non-digit characters out of it, then compare against the needle, eg (in ruby) digits_only = lambda{ |n| n.gsub /[^\d]/, '' } needle = digits_only[input_phone_number] haystack.map(&digits_only).include?(needle) The catch is, I need to do this in MySQL. It has a host of string functions, none of which really seem to do what I want. Currently I can think of 2 'solutions' Hack together a franken-query of CONCAT and SUBSTR Insert a % between every character of the needle ( so it's like this: %0%7%1%2%3%4%5%6% ) However, neither of these seem like particularly elegant solutions. Hopefully someone can help or I might be forced to use the %%%%%% solution Update: This is operating over a relatively fixed set of data, with maybe a few hundred rows. I just didn't want to do something ridiculously bad that future programmers would cry over. If the dataset grows I'll take the 'phoneStripped' approach. Thanks for all the feedback! could you use a "replace" function to strip out any instances of "(", "-" and " ", I'm not concerned about the result being numeric. The main characters I need to consider are +, -, (, ) and space So would that solution look like this? SELECT * FROM people WHERE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phonenumber, '('),')'),'-'),' '),'+') LIKE '123456' Wouldn't that be terribly slow?
TITLE: Searching for phone numbers in mysql QUESTION: I have a table which is full of arbitrarily formatted phone numbers, like this 027 123 5644 021 393-5593 (07) 123 456 042123456 I need to search for a phone number in a similarly arbitrary format ( e.g. 07123456 should find the entry (07) 123 456 The way I'd do this in a normal programming language is to strip all the non-digit characters out of the 'needle', then go through each number in the haystack, strip all non-digit characters out of it, then compare against the needle, eg (in ruby) digits_only = lambda{ |n| n.gsub /[^\d]/, '' } needle = digits_only[input_phone_number] haystack.map(&digits_only).include?(needle) The catch is, I need to do this in MySQL. It has a host of string functions, none of which really seem to do what I want. Currently I can think of 2 'solutions' Hack together a franken-query of CONCAT and SUBSTR Insert a % between every character of the needle ( so it's like this: %0%7%1%2%3%4%5%6% ) However, neither of these seem like particularly elegant solutions. Hopefully someone can help or I might be forced to use the %%%%%% solution Update: This is operating over a relatively fixed set of data, with maybe a few hundred rows. I just didn't want to do something ridiculously bad that future programmers would cry over. If the dataset grows I'll take the 'phoneStripped' approach. Thanks for all the feedback! could you use a "replace" function to strip out any instances of "(", "-" and " ", I'm not concerned about the result being numeric. The main characters I need to consider are +, -, (, ) and space So would that solution look like this? SELECT * FROM people WHERE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phonenumber, '('),')'),'-'),' '),'+') LIKE '123456' Wouldn't that be terribly slow? ANSWER: This looks like a problem from the start. Any kind of searching you do will require a table scan and we all know that's bad. How about adding a column with a hash of the current phone numbers after stripping out all formatting characters. Then you can at least index the hash values and avoid a full blown table scan. Or is the amount of data small and not expected to grow much? Then maybe just sucking all the numbers into the client and running a search there.
[ "mysql", "string", "search", "phone-number" ]
18
14
24,105
18
0
2008-09-02T23:01:32.240000
2008-09-03T01:21:31.373000
40,884
40,893
vb.net object persisted in database
How can I go about storing a vb.net user defined object in a sql database. I am not trying to replicate the properties with columns. I mean something along the lines of converting or encoding my object to a byte array and then storing that in a field in the db. Like when you store an instance of an object in session, but I need the info to persist past the current session. @Orion Edwards It's not a matter of stances. It's because one day, you will change your code. Then you will try de-serialize the old object, and YOUR PROGRAM WILL CRASH. My Program will not "CRASH", it will throw an exception. Lucky for me.net has a whole set of classes dedicated for such an occasion. At which time I will refresh my stale data and put it back in the db. That is the point of this one field (or stance, as the case may be).
You can use serialization - it allows you to store your object at least in 3 forms: binary (suitable for BLOBs), XML (take advantage of MSSQL's XML data type) or just plain text (store in varchar or text column)
vb.net object persisted in database How can I go about storing a vb.net user defined object in a sql database. I am not trying to replicate the properties with columns. I mean something along the lines of converting or encoding my object to a byte array and then storing that in a field in the db. Like when you store an instance of an object in session, but I need the info to persist past the current session. @Orion Edwards It's not a matter of stances. It's because one day, you will change your code. Then you will try de-serialize the old object, and YOUR PROGRAM WILL CRASH. My Program will not "CRASH", it will throw an exception. Lucky for me.net has a whole set of classes dedicated for such an occasion. At which time I will refresh my stale data and put it back in the db. That is the point of this one field (or stance, as the case may be).
TITLE: vb.net object persisted in database QUESTION: How can I go about storing a vb.net user defined object in a sql database. I am not trying to replicate the properties with columns. I mean something along the lines of converting or encoding my object to a byte array and then storing that in a field in the db. Like when you store an instance of an object in session, but I need the info to persist past the current session. @Orion Edwards It's not a matter of stances. It's because one day, you will change your code. Then you will try de-serialize the old object, and YOUR PROGRAM WILL CRASH. My Program will not "CRASH", it will throw an exception. Lucky for me.net has a whole set of classes dedicated for such an occasion. At which time I will refresh my stale data and put it back in the db. That is the point of this one field (or stance, as the case may be). ANSWER: You can use serialization - it allows you to store your object at least in 3 forms: binary (suitable for BLOBs), XML (take advantage of MSSQL's XML data type) or just plain text (store in varchar or text column)
[ "sql", "vb.net", "serialization" ]
1
5
5,013
8
0
2008-09-02T23:08:54.547000
2008-09-02T23:13:34.550000
40,912
45,189
How to check if page is postback within reserved function pageLoad on ASP.NET AJAX
I'm looking for a way to check within pageLoad() if this method is raised during load event because of a postback/async postback or because of being loaded and access the first time. This is similar to Page.IsPostback property within code behind page. TIA, Ricky
One way you could do that is to wire up an Application.Load handler in Application.Init, then have that handler unbind itself after running: Sys.Application.add_init(AppInit); function AppInit() { Sys.Application.add_load(RunOnce); } function RunOnce() { // This will only happen once per GET request to the page. Sys.Application.remove_load(RunOnce); } That will execute after Application.Init. It should be the last thing before pageLoad is called.
How to check if page is postback within reserved function pageLoad on ASP.NET AJAX I'm looking for a way to check within pageLoad() if this method is raised during load event because of a postback/async postback or because of being loaded and access the first time. This is similar to Page.IsPostback property within code behind page. TIA, Ricky
TITLE: How to check if page is postback within reserved function pageLoad on ASP.NET AJAX QUESTION: I'm looking for a way to check within pageLoad() if this method is raised during load event because of a postback/async postback or because of being loaded and access the first time. This is similar to Page.IsPostback property within code behind page. TIA, Ricky ANSWER: One way you could do that is to wire up an Application.Load handler in Application.Init, then have that handler unbind itself after running: Sys.Application.add_init(AppInit); function AppInit() { Sys.Application.add_load(RunOnce); } function RunOnce() { // This will only happen once per GET request to the page. Sys.Application.remove_load(RunOnce); } That will execute after Application.Init. It should be the last thing before pageLoad is called.
[ "javascript", "asp.net-ajax", "postback", "lifecycle" ]
10
6
16,110
9
0
2008-09-02T23:27:23.347000
2008-09-05T03:29:49.690000
40,913
41,222
How do I loop through result objects in Flex?
I am having problems manually looping through xml data that is received via an HTTPService call, the xml looks something like this: foo bar When the webservice result event is fired I do something like this: for(var i:int=0;i<event.result.DataTable.Row.length;i++) { if(event.result.DataTable.Row[i].text == "foo") mx.controls.Alert.show('foo found!'); } This code works then there is more than 1 "Row" nodes returned. However, it seems that if there is only one "Row" node then the event.DataTable.Row object is not an error and the code subsequently breaks. What is the proper way to loop through the HTTPService result object? Do I need to convert it to some type of XMLList collection or an ArrayCollection? I have tried setting the resultFormat to e4x and that has yet to fix the problem... Thanks.
The problem lies in this statement event.result.DataTable.Row.length length is not a property of XMLList, but a method: event.result.DataTable.Row.length() it's confusing, but that's the way it is. Addition: actually, the safest thing to do is to always use a for each loop when iterating over XMLList s, that way you never make the mistake, it's less code, and easier to read: for each ( var node: XML in event.result.DataTable.Row )
How do I loop through result objects in Flex? I am having problems manually looping through xml data that is received via an HTTPService call, the xml looks something like this: foo bar When the webservice result event is fired I do something like this: for(var i:int=0;i<event.result.DataTable.Row.length;i++) { if(event.result.DataTable.Row[i].text == "foo") mx.controls.Alert.show('foo found!'); } This code works then there is more than 1 "Row" nodes returned. However, it seems that if there is only one "Row" node then the event.DataTable.Row object is not an error and the code subsequently breaks. What is the proper way to loop through the HTTPService result object? Do I need to convert it to some type of XMLList collection or an ArrayCollection? I have tried setting the resultFormat to e4x and that has yet to fix the problem... Thanks.
TITLE: How do I loop through result objects in Flex? QUESTION: I am having problems manually looping through xml data that is received via an HTTPService call, the xml looks something like this: foo bar When the webservice result event is fired I do something like this: for(var i:int=0;i<event.result.DataTable.Row.length;i++) { if(event.result.DataTable.Row[i].text == "foo") mx.controls.Alert.show('foo found!'); } This code works then there is more than 1 "Row" nodes returned. However, it seems that if there is only one "Row" node then the event.DataTable.Row object is not an error and the code subsequently breaks. What is the proper way to loop through the HTTPService result object? Do I need to convert it to some type of XMLList collection or an ArrayCollection? I have tried setting the resultFormat to e4x and that has yet to fix the problem... Thanks. ANSWER: The problem lies in this statement event.result.DataTable.Row.length length is not a property of XMLList, but a method: event.result.DataTable.Row.length() it's confusing, but that's the way it is. Addition: actually, the safest thing to do is to always use a for each loop when iterating over XMLList s, that way you never make the mistake, it's less code, and easier to read: for each ( var node: XML in event.result.DataTable.Row )
[ "apache-flex", "actionscript-3", "actionscript" ]
3
4
7,669
3
0
2008-09-02T23:28:59.647000
2008-09-03T05:48:34.180000
40,943
40,947
How to Automatically Start a Download in PHP?
What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited? I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?
Send the following headers before outputting the file: header("Content-Disposition: attachment; filename=\"". basename($File). "\""); header("Content-Type: application/octet-stream"); header("Content-Length: ". filesize($File)); header("Connection: close"); @grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download':)
How to Automatically Start a Download in PHP? What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited? I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?
TITLE: How to Automatically Start a Download in PHP? QUESTION: What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited? I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software? ANSWER: Send the following headers before outputting the file: header("Content-Disposition: attachment; filename=\"". basename($File). "\""); header("Content-Type: application/octet-stream"); header("Content-Length: ". filesize($File)); header("Connection: close"); @grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download':)
[ "php", "automation", "download" ]
56
62
119,040
5
0
2008-09-03T00:02:42.293000
2008-09-03T00:07:32.500000
40,957
41,229
Keeping development databases in multiple environments in sync
I'm early in development on a web application built in VS2008. I have both a desktop PC (where most of the work gets done) and a laptop (for occasional portability) on which I use AnkhSVN to keep the project code synced. What's the best way to keep my development database (SQL Server Express) synced up as well? I have a VS database project in SVN containing create scripts which I re-generate when the schema changes. The original idea was to recreate the DB whenever something changed, but it's quickly becoming a pain. Also, I'd lose all the sample rows I entered to make sure data is being displayed properly. I'm considering putting the.MDF and.LDF files under source control, but I doubt SQL Server Express will handle it gracefully if I do an SVN Update and the files get yanked out from under it, replaced with newer copies. Sticking a couple big binary files into source control doesn't seem like an elegant solution either, even if it is just a throwaway development database. Any suggestions?
In addition to your database CREATE script, why don't you maintain a default data or sample data script as well? This is an approach that we've taken for incremental versions of an application we have been maintaining for more than 2 years now, and it works very well. Having a default data script also allows your QA testers to be able to recreate bugs using the data that you also have? You might also want to take a look at a question I posted some time ago: Best tool for auto-generating SQL change scripts
Keeping development databases in multiple environments in sync I'm early in development on a web application built in VS2008. I have both a desktop PC (where most of the work gets done) and a laptop (for occasional portability) on which I use AnkhSVN to keep the project code synced. What's the best way to keep my development database (SQL Server Express) synced up as well? I have a VS database project in SVN containing create scripts which I re-generate when the schema changes. The original idea was to recreate the DB whenever something changed, but it's quickly becoming a pain. Also, I'd lose all the sample rows I entered to make sure data is being displayed properly. I'm considering putting the.MDF and.LDF files under source control, but I doubt SQL Server Express will handle it gracefully if I do an SVN Update and the files get yanked out from under it, replaced with newer copies. Sticking a couple big binary files into source control doesn't seem like an elegant solution either, even if it is just a throwaway development database. Any suggestions?
TITLE: Keeping development databases in multiple environments in sync QUESTION: I'm early in development on a web application built in VS2008. I have both a desktop PC (where most of the work gets done) and a laptop (for occasional portability) on which I use AnkhSVN to keep the project code synced. What's the best way to keep my development database (SQL Server Express) synced up as well? I have a VS database project in SVN containing create scripts which I re-generate when the schema changes. The original idea was to recreate the DB whenever something changed, but it's quickly becoming a pain. Also, I'd lose all the sample rows I entered to make sure data is being displayed properly. I'm considering putting the.MDF and.LDF files under source control, but I doubt SQL Server Express will handle it gracefully if I do an SVN Update and the files get yanked out from under it, replaced with newer copies. Sticking a couple big binary files into source control doesn't seem like an elegant solution either, even if it is just a throwaway development database. Any suggestions? ANSWER: In addition to your database CREATE script, why don't you maintain a default data or sample data script as well? This is an approach that we've taken for incremental versions of an application we have been maintaining for more than 2 years now, and it works very well. Having a default data script also allows your QA testers to be able to recreate bugs using the data that you also have? You might also want to take a look at a question I posted some time ago: Best tool for auto-generating SQL change scripts
[ "database", "visual-studio-2008", "svn", "version-control" ]
5
3
2,590
4
0
2008-09-03T00:19:51.380000
2008-09-03T06:02:35.813000
40,962
40,970
How do I close a parent Form from child form in Windows Forms 2.0?
I have a need to close a parent form from within child form from a Windows application. What would be the best way to do this?
When you close form in WinForms it disposes all of it's children. So it's not a good idea. You need to do it asynchronously, for example you can send a message to parent form.
How do I close a parent Form from child form in Windows Forms 2.0? I have a need to close a parent form from within child form from a Windows application. What would be the best way to do this?
TITLE: How do I close a parent Form from child form in Windows Forms 2.0? QUESTION: I have a need to close a parent form from within child form from a Windows application. What would be the best way to do this? ANSWER: When you close form in WinForms it disposes all of it's children. So it's not a good idea. You need to do it asynchronously, for example you can send a message to parent form.
[ "c#", "winforms" ]
4
3
27,413
7
0
2008-09-03T00:27:29.677000
2008-09-03T00:35:12.467000
40,966
40,972
Should I use window.onload or script block?
I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state). Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better? For example: function updateDOM(id) { // updates the id element based on form state } should I invoke it via: window.onload = function() { updateDOM("myElement"); }; or:... The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it. Any thoughts? Is one version really better than the other?
Definitely use onload. Keep your scripts separate from your page, or you'll go mad trying to disentangle them later.
Should I use window.onload or script block? I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state). Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better? For example: function updateDOM(id) { // updates the id element based on form state } should I invoke it via: window.onload = function() { updateDOM("myElement"); }; or:... The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it. Any thoughts? Is one version really better than the other?
TITLE: Should I use window.onload or script block? QUESTION: I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state). Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better? For example: function updateDOM(id) { // updates the id element based on form state } should I invoke it via: window.onload = function() { updateDOM("myElement"); }; or:... The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it. Any thoughts? Is one version really better than the other? ANSWER: Definitely use onload. Keep your scripts separate from your page, or you'll go mad trying to disentangle them later.
[ "javascript", "dom" ]
14
5
7,860
9
0
2008-09-03T00:32:40.333000
2008-09-03T00:37:36.733000
40,969
41,015
Is it possible to build an application for the LinkedIn platform?
Do you know if it's possible to build an application for the LinkedIn platform?
While LinkedIn has promised a public API for a very long time now, they have yet to deliver. No, there is no public LinkedIn API yet. IMO, their widgets (which there are only two of at the moment, which are very limited) don't count. They say that they are open to being contacted with specific uses for their API and they may give access to parts as needed - but that is if they accept your ideas for integration. They have been very picky with this - and have not accepted my attempts to integrate with LinkedIn yet, they tell me I have to wait with everyone else, apparently my applications are not "high-profile" enough. Sure, you'll find many Google results talking about their "promised" API, but they are empty promises and won't be of much help.
Is it possible to build an application for the LinkedIn platform? Do you know if it's possible to build an application for the LinkedIn platform?
TITLE: Is it possible to build an application for the LinkedIn platform? QUESTION: Do you know if it's possible to build an application for the LinkedIn platform? ANSWER: While LinkedIn has promised a public API for a very long time now, they have yet to deliver. No, there is no public LinkedIn API yet. IMO, their widgets (which there are only two of at the moment, which are very limited) don't count. They say that they are open to being contacted with specific uses for their API and they may give access to parts as needed - but that is if they accept your ideas for integration. They have been very picky with this - and have not accepted my attempts to integrate with LinkedIn yet, they tell me I have to wait with everyone else, apparently my applications are not "high-profile" enough. Sure, you'll find many Google results talking about their "promised" API, but they are empty promises and won't be of much help.
[ "linkedin-api", "social-media" ]
6
4
2,234
3
0
2008-09-03T00:35:11.390000
2008-09-03T01:21:08.627000
40,994
41,932
Is Google Chrome's V8 engine really that good?
Does anyone have time to take a look at it? I've read a bit and it promises a lot, if it's half what they say, it'll change web Development a lot
I have compared Mozilla Firefox 3.0.1 and Google Chrome 0.2.149.27 on SunSpider JavaScript Benchmark with the following results: Firefox - total: 2900.0ms +/- 1.8% Chrome - total: 1549.2ms +/- 1.7% and on V8 Benchmark Suite with the following results (higher score is better): Firefox - score: 212 Chrome - score: 1842 and on Web Browser Javascript Benchmark with the following results: Firefox - total duration: 362 ms Chrome - total duration: 349 ms Machine: Windows XP SP2, Intel Core2 DUO T7500 @ 2.2 Ghz, 2 GB RAM All blog posts and articles that I've read so far also claim that V8 is clearly the fastest JavaScript engine out there. See for example - V8, TraceMonkey, SquirrelFish, IE8 BenchMarks "... Needless to say, Chrome’s V8 blows away all the current builds of the next-generation of JavaScript VMs. Just to be clear, WebKit and FireFox engines haven’t even hit beta, but it looks like the performance bar has just been set to an astronomical height by the V8 Team."
Is Google Chrome's V8 engine really that good? Does anyone have time to take a look at it? I've read a bit and it promises a lot, if it's half what they say, it'll change web Development a lot
TITLE: Is Google Chrome's V8 engine really that good? QUESTION: Does anyone have time to take a look at it? I've read a bit and it promises a lot, if it's half what they say, it'll change web Development a lot ANSWER: I have compared Mozilla Firefox 3.0.1 and Google Chrome 0.2.149.27 on SunSpider JavaScript Benchmark with the following results: Firefox - total: 2900.0ms +/- 1.8% Chrome - total: 1549.2ms +/- 1.7% and on V8 Benchmark Suite with the following results (higher score is better): Firefox - score: 212 Chrome - score: 1842 and on Web Browser Javascript Benchmark with the following results: Firefox - total duration: 362 ms Chrome - total duration: 349 ms Machine: Windows XP SP2, Intel Core2 DUO T7500 @ 2.2 Ghz, 2 GB RAM All blog posts and articles that I've read so far also claim that V8 is clearly the fastest JavaScript engine out there. See for example - V8, TraceMonkey, SquirrelFish, IE8 BenchMarks "... Needless to say, Chrome’s V8 blows away all the current builds of the next-generation of JavaScript VMs. Just to be clear, WebKit and FireFox engines haven’t even hit beta, but it looks like the performance bar has just been set to an astronomical height by the V8 Team."
[ "javascript", "google-chrome", "v8" ]
6
19
9,116
13
0
2008-09-03T01:09:04.147000
2008-09-03T15:26:52.977000
40,999
41,012
How to Convert a StreamReader into an XMLReader object in .Net 2.0/C#
Here's a quick question I've been banging my head against today. I'm trying to convert a.Net dataset into an XML stream, transform it with an xsl file in memory, then output the result to a new XML file. Here's the current solution: string transformXML = @"pathToXslDocument"; XmlDocument originalXml = new XmlDocument(); XmlDocument transformedXml = new XmlDocument(); XslCompiledTransform transformer = new XslCompiledTransform(); DataSet ds = new DataSet(); string filepath; originalXml.LoadXml(ds.GetXml()); //data loaded prior StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb); transformer.Load(transformXML); transformer.Transform(originalXml, writer); //no need to select the node transformedXml.LoadXml(sb.ToString()); transformedXml.Save(filepath); writer.Close(); Here's the original code: BufferedStream stream = new BufferedStream(new MemoryStream()); DataSet ds = new DataSet(); da.Fill(ds); ds.WriteXml(stream); StreamReader sr = new StreamReader(stream, true); stream.Position = 0; //I'm not certain if this is necessary, but for the StreamReader to read the text the position must be reset. XmlReader reader = XmlReader.Create(sr, null); //Problem is created here, the XmlReader is created with none of the data from the StreamReader XslCompiledTransform transformer = new XslCompiledTransform(); transformer.Load(@" "); transformer.Transform(reader, null, writer); //Exception is thrown here, though the problem originates from the XmlReader.Create(sr, null) For some reason in the transformer.Transform method, the reader has no root node, in fact the reader isn't reading anything from the StreamReader. My questions is what is wrong with this code? Secondarily, is there a better way to convert/transform/store a dataset into XML? Edit: Both answers were helpful and technically aku's was closer. However I am leaning towards a solution that more closely resembles Longhorn's after trying both solutions.
I'm not sure but it seems that you didn't reset position in stream before passing it to XmlReader. Try to seek at the beginning of your stream before trying to read from it. Also it may be necessary to close\flush stream after you wrote some data to it. EDIT: Just tried following code and it worked perfectly: BufferedStream stream = new BufferedStream(new MemoryStream()); stream.Write(Encoding.ASCII.GetBytes(" foo "), 0, " foo ".Length); stream.Seek(0, SeekOrigin.Begin); StreamReader sr = new StreamReader(stream); XmlReader reader = XmlReader.Create(sr); while (reader.Read()) { Console.WriteLine(reader.Value); } stream.Close();
How to Convert a StreamReader into an XMLReader object in .Net 2.0/C# Here's a quick question I've been banging my head against today. I'm trying to convert a.Net dataset into an XML stream, transform it with an xsl file in memory, then output the result to a new XML file. Here's the current solution: string transformXML = @"pathToXslDocument"; XmlDocument originalXml = new XmlDocument(); XmlDocument transformedXml = new XmlDocument(); XslCompiledTransform transformer = new XslCompiledTransform(); DataSet ds = new DataSet(); string filepath; originalXml.LoadXml(ds.GetXml()); //data loaded prior StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb); transformer.Load(transformXML); transformer.Transform(originalXml, writer); //no need to select the node transformedXml.LoadXml(sb.ToString()); transformedXml.Save(filepath); writer.Close(); Here's the original code: BufferedStream stream = new BufferedStream(new MemoryStream()); DataSet ds = new DataSet(); da.Fill(ds); ds.WriteXml(stream); StreamReader sr = new StreamReader(stream, true); stream.Position = 0; //I'm not certain if this is necessary, but for the StreamReader to read the text the position must be reset. XmlReader reader = XmlReader.Create(sr, null); //Problem is created here, the XmlReader is created with none of the data from the StreamReader XslCompiledTransform transformer = new XslCompiledTransform(); transformer.Load(@" "); transformer.Transform(reader, null, writer); //Exception is thrown here, though the problem originates from the XmlReader.Create(sr, null) For some reason in the transformer.Transform method, the reader has no root node, in fact the reader isn't reading anything from the StreamReader. My questions is what is wrong with this code? Secondarily, is there a better way to convert/transform/store a dataset into XML? Edit: Both answers were helpful and technically aku's was closer. However I am leaning towards a solution that more closely resembles Longhorn's after trying both solutions.
TITLE: How to Convert a StreamReader into an XMLReader object in .Net 2.0/C# QUESTION: Here's a quick question I've been banging my head against today. I'm trying to convert a.Net dataset into an XML stream, transform it with an xsl file in memory, then output the result to a new XML file. Here's the current solution: string transformXML = @"pathToXslDocument"; XmlDocument originalXml = new XmlDocument(); XmlDocument transformedXml = new XmlDocument(); XslCompiledTransform transformer = new XslCompiledTransform(); DataSet ds = new DataSet(); string filepath; originalXml.LoadXml(ds.GetXml()); //data loaded prior StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb); transformer.Load(transformXML); transformer.Transform(originalXml, writer); //no need to select the node transformedXml.LoadXml(sb.ToString()); transformedXml.Save(filepath); writer.Close(); Here's the original code: BufferedStream stream = new BufferedStream(new MemoryStream()); DataSet ds = new DataSet(); da.Fill(ds); ds.WriteXml(stream); StreamReader sr = new StreamReader(stream, true); stream.Position = 0; //I'm not certain if this is necessary, but for the StreamReader to read the text the position must be reset. XmlReader reader = XmlReader.Create(sr, null); //Problem is created here, the XmlReader is created with none of the data from the StreamReader XslCompiledTransform transformer = new XslCompiledTransform(); transformer.Load(@" "); transformer.Transform(reader, null, writer); //Exception is thrown here, though the problem originates from the XmlReader.Create(sr, null) For some reason in the transformer.Transform method, the reader has no root node, in fact the reader isn't reading anything from the StreamReader. My questions is what is wrong with this code? Secondarily, is there a better way to convert/transform/store a dataset into XML? Edit: Both answers were helpful and technically aku's was closer. However I am leaning towards a solution that more closely resembles Longhorn's after trying both solutions. ANSWER: I'm not sure but it seems that you didn't reset position in stream before passing it to XmlReader. Try to seek at the beginning of your stream before trying to read from it. Also it may be necessary to close\flush stream after you wrote some data to it. EDIT: Just tried following code and it worked perfectly: BufferedStream stream = new BufferedStream(new MemoryStream()); stream.Write(Encoding.ASCII.GetBytes(" foo "), 0, " foo ".Length); stream.Seek(0, SeekOrigin.Begin); StreamReader sr = new StreamReader(stream); XmlReader reader = XmlReader.Create(sr); while (reader.Read()) { Console.WriteLine(reader.Value); } stream.Close();
[ "c#", ".net", "xml", "xslt", "stream" ]
5
7
31,194
3
0
2008-09-03T01:10:45.033000
2008-09-03T01:19:39.800000
41,009
45,101
IRAPIStream COM Interface in .NET
I'm trying to use the OpenNETCF RAPI class to interact with a windows mobile device using the RAPI.Invoke() method. According to the following article: http://blog.opennetcf.com/ncowburn/2007/07/27/HOWTORetrieveTheDeviceIDFromTheDesktop.aspx You can do the communication in either block or stream mode. I have used block mode before, but now I need to do something a bit more complicated with a lot more data and continuous communication and therefore need to use the stream mode. Unfortunately on that article, and basically everywhere else, there is no explaination of how to use IRAPIStream in.NET I have found C/C++ documentation, but my desktop app needs to be written in C# Does anyone know how to properly implement the IRAPIStream COM interface in.NET? And better yet, anyone actually used RAPI.Invoke() with IRAPIStream before? Examples would be much appreciated. Edit: Upon a closer look at the RAPI class documentation, I realized that the Invoke() method doesn't support the stream interface.... so OpenNETCF is likely out, but maybe there is still a way to do it?
I have found that generally the most performant and stable way to push/pull large amounts of data of a device over activesync is to use a socket. Early on we used CeRapiInvoke and a stream to pull data down of the device but ditched this early on in favour of using tcp/ip over a socket.
IRAPIStream COM Interface in .NET I'm trying to use the OpenNETCF RAPI class to interact with a windows mobile device using the RAPI.Invoke() method. According to the following article: http://blog.opennetcf.com/ncowburn/2007/07/27/HOWTORetrieveTheDeviceIDFromTheDesktop.aspx You can do the communication in either block or stream mode. I have used block mode before, but now I need to do something a bit more complicated with a lot more data and continuous communication and therefore need to use the stream mode. Unfortunately on that article, and basically everywhere else, there is no explaination of how to use IRAPIStream in.NET I have found C/C++ documentation, but my desktop app needs to be written in C# Does anyone know how to properly implement the IRAPIStream COM interface in.NET? And better yet, anyone actually used RAPI.Invoke() with IRAPIStream before? Examples would be much appreciated. Edit: Upon a closer look at the RAPI class documentation, I realized that the Invoke() method doesn't support the stream interface.... so OpenNETCF is likely out, but maybe there is still a way to do it?
TITLE: IRAPIStream COM Interface in .NET QUESTION: I'm trying to use the OpenNETCF RAPI class to interact with a windows mobile device using the RAPI.Invoke() method. According to the following article: http://blog.opennetcf.com/ncowburn/2007/07/27/HOWTORetrieveTheDeviceIDFromTheDesktop.aspx You can do the communication in either block or stream mode. I have used block mode before, but now I need to do something a bit more complicated with a lot more data and continuous communication and therefore need to use the stream mode. Unfortunately on that article, and basically everywhere else, there is no explaination of how to use IRAPIStream in.NET I have found C/C++ documentation, but my desktop app needs to be written in C# Does anyone know how to properly implement the IRAPIStream COM interface in.NET? And better yet, anyone actually used RAPI.Invoke() with IRAPIStream before? Examples would be much appreciated. Edit: Upon a closer look at the RAPI class documentation, I realized that the Invoke() method doesn't support the stream interface.... so OpenNETCF is likely out, but maybe there is still a way to do it? ANSWER: I have found that generally the most performant and stable way to push/pull large amounts of data of a device over activesync is to use a socket. Early on we used CeRapiInvoke and a stream to pull data down of the device but ditched this early on in favour of using tcp/ip over a socket.
[ "c#", ".net", "windows-mobile", "compact-framework", "rapi" ]
2
1
582
1
0
2008-09-03T01:16:07.983000
2008-09-05T02:05:50.640000
41,018
50,357
How do you access two databases in Grails
Grails makes it very easy to configure datasources for different environments (development, test, production) in its DataSources.groovy file, but there seems to be no facility for configuring multiple datasources in one environment. What to I do if I need to access several databases from the same Grails application?
There is now Grails plugin that enables the use of multiple datasources directly with Grails' GORM layer: http://burtbeckwith.com/blog/?p=70
How do you access two databases in Grails Grails makes it very easy to configure datasources for different environments (development, test, production) in its DataSources.groovy file, but there seems to be no facility for configuring multiple datasources in one environment. What to I do if I need to access several databases from the same Grails application?
TITLE: How do you access two databases in Grails QUESTION: Grails makes it very easy to configure datasources for different environments (development, test, production) in its DataSources.groovy file, but there seems to be no facility for configuring multiple datasources in one environment. What to I do if I need to access several databases from the same Grails application? ANSWER: There is now Grails plugin that enables the use of multiple datasources directly with Grails' GORM layer: http://burtbeckwith.com/blog/?p=70
[ "grails" ]
22
9
24,039
6
0
2008-09-03T01:23:49.963000
2008-09-08T18:27:50.487000
41,024
41,069
FXRuby FXFileDialog box default directory
In FXRuby; how do I set the FXFileDialog to be at the home directory when it opens?
Here's an exceedingly lazy way to do it: #!/usr/bin/ruby require 'rubygems' require 'fox16' include Fox theApp = FXApp.new theMainWindow = FXMainWindow.new(theApp, "Hello") theButton = FXButton.new(theMainWindow, "Hello, World!") theButton.tipText = "Push Me!" iconFile = File.open("icon.jpg", "rb") theButton.icon = FXJPGIcon.new(theApp, iconFile.read) theButton.iconPosition = ICON_ABOVE_TEXT iconFile.close theButton.connect(SEL_COMMAND) { fileToOpen = FXFileDialog.getOpenFilename(theMainWindow, "window name goes here", `echo $HOME`.chomp + "/") } FXToolTip.new(theApp) theApp.create theMainWindow.show theApp.run This relies on you being on a *nix box (or having the $HOME environment variable set). The lines that specifically answer your question are: theButton.connect(SEL_COMMAND) { fileToOpen = FXFileDialog.getOpenFilename(theMainWindow, "window name goes here", `echo $HOME`.chomp + "/") } Here, the first argument is the window that owns the dialog box, the second is the title of the window, and the third is the default path to start at (you need the "/" at the end otherwise it'll start a directory higher with the user's home folder selected). Check out this link for more info on FXFileDialog.
FXRuby FXFileDialog box default directory In FXRuby; how do I set the FXFileDialog to be at the home directory when it opens?
TITLE: FXRuby FXFileDialog box default directory QUESTION: In FXRuby; how do I set the FXFileDialog to be at the home directory when it opens? ANSWER: Here's an exceedingly lazy way to do it: #!/usr/bin/ruby require 'rubygems' require 'fox16' include Fox theApp = FXApp.new theMainWindow = FXMainWindow.new(theApp, "Hello") theButton = FXButton.new(theMainWindow, "Hello, World!") theButton.tipText = "Push Me!" iconFile = File.open("icon.jpg", "rb") theButton.icon = FXJPGIcon.new(theApp, iconFile.read) theButton.iconPosition = ICON_ABOVE_TEXT iconFile.close theButton.connect(SEL_COMMAND) { fileToOpen = FXFileDialog.getOpenFilename(theMainWindow, "window name goes here", `echo $HOME`.chomp + "/") } FXToolTip.new(theApp) theApp.create theMainWindow.show theApp.run This relies on you being on a *nix box (or having the $HOME environment variable set). The lines that specifically answer your question are: theButton.connect(SEL_COMMAND) { fileToOpen = FXFileDialog.getOpenFilename(theMainWindow, "window name goes here", `echo $HOME`.chomp + "/") } Here, the first argument is the window that owns the dialog box, the second is the title of the window, and the third is the default path to start at (you need the "/" at the end otherwise it'll start a directory higher with the user's home folder selected). Check out this link for more info on FXFileDialog.
[ "fxruby" ]
1
1
417
1
0
2008-09-03T01:29:50.727000
2008-09-03T02:26:42.323000
41,027
865,198
What's a good bit of JS or JQuery for horizontally scrolling news ticker
I am looking for a little bit of JQuery or JS that allows me to produce a horizontally scrolling "news ticker" list. The produced HTML needs to be standards compliant as well. I have tried liScroll but this has a habit of breaking (some content ends up on a second line at the start of the scroll), especially with longer lists. I have also tried this News Ticker but when a DOCTYPE is included the scrolling will jolt rather than cycle smoothly at the end of each cycle. Any suggestions are appreciated. Edit So thanks to Matt Hinze's suggestion I realised I could do what I wanted to do with JQuery animate (I require continuous scrolling not discrete scrolling like the example). However, I quickly ran into similar problems to those I was having with liScroll and after all that realised a CSS issue (as always) was responsible. Solution: liScroll - change the default 'var stripWidth = 0' to something like 100, to give a little space and avoid new line wrapping.
Smooth Div Scroll can also be used as a news ticker/stock ticker. It can pause on mouse over or mouse down and it can loop endlessly if you want it to. Here's the example with a running ticker.
What's a good bit of JS or JQuery for horizontally scrolling news ticker I am looking for a little bit of JQuery or JS that allows me to produce a horizontally scrolling "news ticker" list. The produced HTML needs to be standards compliant as well. I have tried liScroll but this has a habit of breaking (some content ends up on a second line at the start of the scroll), especially with longer lists. I have also tried this News Ticker but when a DOCTYPE is included the scrolling will jolt rather than cycle smoothly at the end of each cycle. Any suggestions are appreciated. Edit So thanks to Matt Hinze's suggestion I realised I could do what I wanted to do with JQuery animate (I require continuous scrolling not discrete scrolling like the example). However, I quickly ran into similar problems to those I was having with liScroll and after all that realised a CSS issue (as always) was responsible. Solution: liScroll - change the default 'var stripWidth = 0' to something like 100, to give a little space and avoid new line wrapping.
TITLE: What's a good bit of JS or JQuery for horizontally scrolling news ticker QUESTION: I am looking for a little bit of JQuery or JS that allows me to produce a horizontally scrolling "news ticker" list. The produced HTML needs to be standards compliant as well. I have tried liScroll but this has a habit of breaking (some content ends up on a second line at the start of the scroll), especially with longer lists. I have also tried this News Ticker but when a DOCTYPE is included the scrolling will jolt rather than cycle smoothly at the end of each cycle. Any suggestions are appreciated. Edit So thanks to Matt Hinze's suggestion I realised I could do what I wanted to do with JQuery animate (I require continuous scrolling not discrete scrolling like the example). However, I quickly ran into similar problems to those I was having with liScroll and after all that realised a CSS issue (as always) was responsible. Solution: liScroll - change the default 'var stripWidth = 0' to something like 100, to give a little space and avoid new line wrapping. ANSWER: Smooth Div Scroll can also be used as a news ticker/stock ticker. It can pause on mouse over or mouse down and it can loop endlessly if you want it to. Here's the example with a running ticker.
[ "javascript", "jquery", "scroll", "client-side" ]
8
5
22,314
5
0
2008-09-03T01:33:57.100000
2009-05-14T19:24:33.047000
41,039
78,966
Find in Files: Search all code in Team Foundation Server
Is there a way to search the latest version of every file in TFS for a specific string or regex? This is probably the only thing I miss from Visual Source Safe... Currently I perform a Get Latest on the entire codebase and use Windows Search, but this gets quite painful with over 1GB of code in 75,000 files. EDIT: Tried the powertools mentioned, but the "Wildcard Search" option appears to only search filenames and not contents. UPDATE: We have implemented a customised search option in an existing MOSS (Search Server) installation.
Team Foundation Server 2015 (on-premises) and Visual Studio Team Services (cloud version) include built-in support for searching across all your code and work items. You can do simple string searches like foo, boolean operations like foo OR bar or more complex language-specific things like class:WebRequest You can read more about it here: https://www.visualstudio.com/en-us/docs/search/overview
Find in Files: Search all code in Team Foundation Server Is there a way to search the latest version of every file in TFS for a specific string or regex? This is probably the only thing I miss from Visual Source Safe... Currently I perform a Get Latest on the entire codebase and use Windows Search, but this gets quite painful with over 1GB of code in 75,000 files. EDIT: Tried the powertools mentioned, but the "Wildcard Search" option appears to only search filenames and not contents. UPDATE: We have implemented a customised search option in an existing MOSS (Search Server) installation.
TITLE: Find in Files: Search all code in Team Foundation Server QUESTION: Is there a way to search the latest version of every file in TFS for a specific string or regex? This is probably the only thing I miss from Visual Source Safe... Currently I perform a Get Latest on the entire codebase and use Windows Search, but this gets quite painful with over 1GB of code in 75,000 files. EDIT: Tried the powertools mentioned, but the "Wildcard Search" option appears to only search filenames and not contents. UPDATE: We have implemented a customised search option in an existing MOSS (Search Server) installation. ANSWER: Team Foundation Server 2015 (on-premises) and Visual Studio Team Services (cloud version) include built-in support for searching across all your code and work items. You can do simple string searches like foo, boolean operations like foo OR bar or more complex language-specific things like class:WebRequest You can read more about it here: https://www.visualstudio.com/en-us/docs/search/overview
[ "visual-studio-2008", "search", "tfs", "code-search-engine" ]
104
62
121,182
12
0
2008-09-03T01:49:04.270000
2008-09-17T01:34:39.647000
41,042
42,144
XML dataset in Crystal Reports
I am trying to print a report from within an InfoPath template. So my dataset is an XML DOM that I will load into the Crystal Report at runtime. But how do I define the dataset off which the Crystal Report is developed? Crystal Reports has a great tool to build a dataset from an SQL database. Is there something similar for XML schema that I am missing?
right now i don't have crystal reports installed on my machine but if i remember correctly you can select as the source of your report an xml file. i believe that you can also select the xsd with the data definition for your xml file. in my case, since i was working with a dataset i would run my application and save the xml representation of the dataset with dataset.writexml(true) so that i would end up with an xml file that include the data definition
XML dataset in Crystal Reports I am trying to print a report from within an InfoPath template. So my dataset is an XML DOM that I will load into the Crystal Report at runtime. But how do I define the dataset off which the Crystal Report is developed? Crystal Reports has a great tool to build a dataset from an SQL database. Is there something similar for XML schema that I am missing?
TITLE: XML dataset in Crystal Reports QUESTION: I am trying to print a report from within an InfoPath template. So my dataset is an XML DOM that I will load into the Crystal Report at runtime. But how do I define the dataset off which the Crystal Report is developed? Crystal Reports has a great tool to build a dataset from an SQL database. Is there something similar for XML schema that I am missing? ANSWER: right now i don't have crystal reports installed on my machine but if i remember correctly you can select as the source of your report an xml file. i believe that you can also select the xsd with the data definition for your xml file. in my case, since i was working with a dataset i would run my application and save the xml representation of the dataset with dataset.writexml(true) so that i would end up with an xml file that include the data definition
[ "xml", "crystal-reports", "infopath" ]
3
1
1,802
2
0
2008-09-03T02:01:45.097000
2008-09-03T17:24:19.810000
41,045
41,059
Can I have polymorphic containers with value semantics in C++?
As a general rule, I prefer using value rather than pointer semantics in C++ (ie using vector instead of vector ). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects. Unfortunately, value collections don't work when you want to store a variety of object types that all derive from a common base. See the example below. #include using namespace std; class Parent { public: Parent(): parent_mem(1) {} virtual void write() { cout << "Parent: " << parent_mem << endl; } int parent_mem; }; class Child: public Parent { public: Child(): child_mem(2) { parent_mem = 2; } void write() { cout << "Child: " << parent_mem << ", " << child_mem << endl; } int child_mem; }; int main(int, char**) { // I can have a polymorphic container with pointer semantics vector pointerVec; pointerVec.push_back(new Parent()); pointerVec.push_back(new Child()); pointerVec[0]->write(); pointerVec[1]->write(); // Output: // // Parent: 1 // Child: 2, 2 // But I can't do it with value semantics vector valueVec; valueVec.push_back(Parent()); valueVec.push_back(Child()); // gets turned into a Parent object:( valueVec[0].write(); valueVec[1].write(); // Output: // // Parent: 1 // Parent: 2 } My question is: Can I have have my cake (value semantics) and eat it too (polymorphic containers)? Or do I have to use pointers?
Since the objects of different classes will have different sizes, you would end up running into the slicing problem if you store them as values. One reasonable solution is to store container safe smart pointers. I normally use boost::shared_ptr which is safe to store in a container. Note that std::auto_ptr is not. vector > vec; vec.push_back(shared_ptr (new Child())); shared_ptr uses reference counting so it will not delete the underlying instance until all references are removed.
Can I have polymorphic containers with value semantics in C++? As a general rule, I prefer using value rather than pointer semantics in C++ (ie using vector instead of vector ). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects. Unfortunately, value collections don't work when you want to store a variety of object types that all derive from a common base. See the example below. #include using namespace std; class Parent { public: Parent(): parent_mem(1) {} virtual void write() { cout << "Parent: " << parent_mem << endl; } int parent_mem; }; class Child: public Parent { public: Child(): child_mem(2) { parent_mem = 2; } void write() { cout << "Child: " << parent_mem << ", " << child_mem << endl; } int child_mem; }; int main(int, char**) { // I can have a polymorphic container with pointer semantics vector pointerVec; pointerVec.push_back(new Parent()); pointerVec.push_back(new Child()); pointerVec[0]->write(); pointerVec[1]->write(); // Output: // // Parent: 1 // Child: 2, 2 // But I can't do it with value semantics vector valueVec; valueVec.push_back(Parent()); valueVec.push_back(Child()); // gets turned into a Parent object:( valueVec[0].write(); valueVec[1].write(); // Output: // // Parent: 1 // Parent: 2 } My question is: Can I have have my cake (value semantics) and eat it too (polymorphic containers)? Or do I have to use pointers?
TITLE: Can I have polymorphic containers with value semantics in C++? QUESTION: As a general rule, I prefer using value rather than pointer semantics in C++ (ie using vector instead of vector ). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects. Unfortunately, value collections don't work when you want to store a variety of object types that all derive from a common base. See the example below. #include using namespace std; class Parent { public: Parent(): parent_mem(1) {} virtual void write() { cout << "Parent: " << parent_mem << endl; } int parent_mem; }; class Child: public Parent { public: Child(): child_mem(2) { parent_mem = 2; } void write() { cout << "Child: " << parent_mem << ", " << child_mem << endl; } int child_mem; }; int main(int, char**) { // I can have a polymorphic container with pointer semantics vector pointerVec; pointerVec.push_back(new Parent()); pointerVec.push_back(new Child()); pointerVec[0]->write(); pointerVec[1]->write(); // Output: // // Parent: 1 // Child: 2, 2 // But I can't do it with value semantics vector valueVec; valueVec.push_back(Parent()); valueVec.push_back(Child()); // gets turned into a Parent object:( valueVec[0].write(); valueVec[1].write(); // Output: // // Parent: 1 // Parent: 2 } My question is: Can I have have my cake (value semantics) and eat it too (polymorphic containers)? Or do I have to use pointers? ANSWER: Since the objects of different classes will have different sizes, you would end up running into the slicing problem if you store them as values. One reasonable solution is to store container safe smart pointers. I normally use boost::shared_ptr which is safe to store in a container. Note that std::auto_ptr is not. vector > vec; vec.push_back(shared_ptr (new Child())); shared_ptr uses reference counting so it will not delete the underlying instance until all references are removed.
[ "c++", "stl" ]
38
29
12,916
9
0
2008-09-03T02:09:29.027000
2008-09-03T02:19:53.260000
41,050
41,055
Where do you store your database connectionstring?
I usually store my connectionstring in web.config or in the application settings of my Visual Studio project. The application I'm currently working on makes a lot of trips to the database which means it will look up the connectionstring every time. Should I be putting the connectionstring in the cache or should I be looking at storing the whole SqlConnection object in the cache to eliminate the need to open and close them all the time? Update: Seems like the consensus is to store the connection string in a configuration file and leave the caching in the trusting hand of ADO.NET
I wouldn't cache the connection object, that will defeat the built-in connection pooling -- ADO.NET will handle connections (assuming you instantiate and close them) efficiently by itself. As far as the connection string itself, you shouldn't need to cache it if you load it from connection -- the connection manager object in the.NET 2.0 framework loads the config into memory when you first access it, so there are no repeat trips to the file system.
Where do you store your database connectionstring? I usually store my connectionstring in web.config or in the application settings of my Visual Studio project. The application I'm currently working on makes a lot of trips to the database which means it will look up the connectionstring every time. Should I be putting the connectionstring in the cache or should I be looking at storing the whole SqlConnection object in the cache to eliminate the need to open and close them all the time? Update: Seems like the consensus is to store the connection string in a configuration file and leave the caching in the trusting hand of ADO.NET
TITLE: Where do you store your database connectionstring? QUESTION: I usually store my connectionstring in web.config or in the application settings of my Visual Studio project. The application I'm currently working on makes a lot of trips to the database which means it will look up the connectionstring every time. Should I be putting the connectionstring in the cache or should I be looking at storing the whole SqlConnection object in the cache to eliminate the need to open and close them all the time? Update: Seems like the consensus is to store the connection string in a configuration file and leave the caching in the trusting hand of ADO.NET ANSWER: I wouldn't cache the connection object, that will defeat the built-in connection pooling -- ADO.NET will handle connections (assuming you instantiate and close them) efficiently by itself. As far as the connection string itself, you shouldn't need to cache it if you load it from connection -- the connection manager object in the.NET 2.0 framework loads the config into memory when you first access it, so there are no repeat trips to the file system.
[ "asp.net" ]
7
4
2,437
6
0
2008-09-03T02:12:34.527000
2008-09-03T02:18:12.173000
41,056
41,063
Best java tools for emacs
I'm a long-time emacs user, and I'm now working about 1/2 time in Java. What are the best emacs libraries for Debugging Java Code Completion/Intellisense Javadoc browsing?
I've used JDEE on several projects. It handles Code Completion. I've never used it for debugging or browsing docs, but it's a big step up from a basic text editor.
Best java tools for emacs I'm a long-time emacs user, and I'm now working about 1/2 time in Java. What are the best emacs libraries for Debugging Java Code Completion/Intellisense Javadoc browsing?
TITLE: Best java tools for emacs QUESTION: I'm a long-time emacs user, and I'm now working about 1/2 time in Java. What are the best emacs libraries for Debugging Java Code Completion/Intellisense Javadoc browsing? ANSWER: I've used JDEE on several projects. It handles Code Completion. I've never used it for debugging or browsing docs, but it's a big step up from a basic text editor.
[ "java", "debugging", "emacs", "ide", "javadoc" ]
17
12
11,220
3
0
2008-09-03T02:18:15.650000
2008-09-03T02:22:04.237000
41,073
41,158
.NET Mass Downloader with VS.NET 2005?
After downloading all.NET framework symbols and sources using NetMassDownloader, is it possible to setup the VS.NET 2005 for debugging into.NET 2.0 source files?
It looks like you can download the symbols, though they're not available for browsing.
.NET Mass Downloader with VS.NET 2005? After downloading all.NET framework symbols and sources using NetMassDownloader, is it possible to setup the VS.NET 2005 for debugging into.NET 2.0 source files?
TITLE: .NET Mass Downloader with VS.NET 2005? QUESTION: After downloading all.NET framework symbols and sources using NetMassDownloader, is it possible to setup the VS.NET 2005 for debugging into.NET 2.0 source files? ANSWER: It looks like you can download the symbols, though they're not available for browsing.
[ ".net", "visual-studio", "debugging" ]
1
3
210
1
0
2008-09-03T02:29:03.673000
2008-09-03T04:09:08.177000
41,089
41,521
How do I click a button on a vb6 form?
I have a vb6 form with an ocx control on it. The ocx control has a button on it that I want to press from code. How do I do this? I have: Dim b As CommandButton Set b = ocx.GetButton("btnPrint") SendMessage ocx.hwnd, WM_COMMAND, GetWindowLong(b.hwnd, GWL_ID), b.hwnd but it doesn't seem to work.
I believe the following will work: Dim b As CommandButton Set b = ocx.GetButton("btnPrint") b = True CommandButton s actually have two functions. One is the usual click button and the other is a toggle button that acts similar to a CheckBox. The default property of the CommandButton is actually the Value property that indicates whether a button is toggled. By setting the property, the Click event is generated. This is done even if the button is not styled as a ToggleButton and therefore doesn't change its state.
How do I click a button on a vb6 form? I have a vb6 form with an ocx control on it. The ocx control has a button on it that I want to press from code. How do I do this? I have: Dim b As CommandButton Set b = ocx.GetButton("btnPrint") SendMessage ocx.hwnd, WM_COMMAND, GetWindowLong(b.hwnd, GWL_ID), b.hwnd but it doesn't seem to work.
TITLE: How do I click a button on a vb6 form? QUESTION: I have a vb6 form with an ocx control on it. The ocx control has a button on it that I want to press from code. How do I do this? I have: Dim b As CommandButton Set b = ocx.GetButton("btnPrint") SendMessage ocx.hwnd, WM_COMMAND, GetWindowLong(b.hwnd, GWL_ID), b.hwnd but it doesn't seem to work. ANSWER: I believe the following will work: Dim b As CommandButton Set b = ocx.GetButton("btnPrint") b = True CommandButton s actually have two functions. One is the usual click button and the other is a toggle button that acts similar to a CheckBox. The default property of the CommandButton is actually the Value property that indicates whether a button is toggled. By setting the property, the Click event is generated. This is done even if the button is not styled as a ToggleButton and therefore doesn't change its state.
[ "vb6" ]
2
2
4,225
5
0
2008-09-03T02:39:52.197000
2008-09-03T12:08:30.553000
41,097
41,931
What are some compact algorithms for generating interesting time series data?
The question sort of says it all. Whether it's for code testing purposes, or you're modeling a real-world process, or you're trying to impress a loved one, what are some algorithms that folks use to generate interesting time series data? Are there any good resources out there with a consolidated list? No constraints on values (except plus or minus infinity) or dimensions, but I'm looking for examples that people have found useful or exciting in practice. Bonus points for parsimonious and readable code samples.
There are a ton of PRN generators out there, and you can always get free random bits, or even buy them on CD or DVD. I've used simple sine wave generators mixed together with some phase and amplitude noise thrown in to get signals that sound and look interesting to humans when put through speakers or lights, but I don't know what you mean by interesting. There are ways to generate data that looks interesting in a chart form, but that would be different than data used on a stock chart, and neither would make a nice "static" image such as produced by an analog television tuned to a null channel. You can use Conway's game of life as a PRN, and "listen" to cells (or run all the cells through a logic circuit) to get some interesting time based signals. It would be interesting to look at the graph of DB updates/inserts for Stackoverflow over time, and you could mine that data. There really are infinite ways to generate an "interesting" time series data. Can you narrow the scope of your question?
What are some compact algorithms for generating interesting time series data? The question sort of says it all. Whether it's for code testing purposes, or you're modeling a real-world process, or you're trying to impress a loved one, what are some algorithms that folks use to generate interesting time series data? Are there any good resources out there with a consolidated list? No constraints on values (except plus or minus infinity) or dimensions, but I'm looking for examples that people have found useful or exciting in practice. Bonus points for parsimonious and readable code samples.
TITLE: What are some compact algorithms for generating interesting time series data? QUESTION: The question sort of says it all. Whether it's for code testing purposes, or you're modeling a real-world process, or you're trying to impress a loved one, what are some algorithms that folks use to generate interesting time series data? Are there any good resources out there with a consolidated list? No constraints on values (except plus or minus infinity) or dimensions, but I'm looking for examples that people have found useful or exciting in practice. Bonus points for parsimonious and readable code samples. ANSWER: There are a ton of PRN generators out there, and you can always get free random bits, or even buy them on CD or DVD. I've used simple sine wave generators mixed together with some phase and amplitude noise thrown in to get signals that sound and look interesting to humans when put through speakers or lights, but I don't know what you mean by interesting. There are ways to generate data that looks interesting in a chart form, but that would be different than data used on a stock chart, and neither would make a nice "static" image such as produced by an analog television tuned to a null channel. You can use Conway's game of life as a PRN, and "listen" to cells (or run all the cells through a logic circuit) to get some interesting time based signals. It would be interesting to look at the graph of DB updates/inserts for Stackoverflow over time, and you could mine that data. There really are infinite ways to generate an "interesting" time series data. Can you narrow the scope of your question?
[ "algorithm", "language-agnostic", "time-series" ]
1
2
440
3
0
2008-09-03T02:45:08.863000
2008-09-03T15:26:15.490000
41,107
41,156
How to generate a random alpha-numeric string
I've been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over 500K+ generation (my needs don't really require anything much more sophisticated). Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like "AEYGF7K0DM1X".
Algorithm To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length. Implementation Here's some fairly simple and very flexible code for generating random identifiers. Read the information that follows for important application notes. public class RandomString { /** * Generate a random string. */ public String nextString() { for (int idx = 0; idx < buf.length; ++idx) buf[idx] = symbols[random.nextInt(symbols.length)]; return new String(buf); } public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String lower = upper.toLowerCase(Locale.ROOT); public static final String digits = "0123456789"; public static final String alphanum = upper + lower + digits; private final Random random; private final char[] symbols; private final char[] buf; public RandomString(int length, Random random, String symbols) { if (length < 1) throw new IllegalArgumentException(); if (symbols.length() < 2) throw new IllegalArgumentException(); this.random = Objects.requireNonNull(random); this.symbols = symbols.toCharArray(); this.buf = new char[length]; } /** * Create an alphanumeric string generator. */ public RandomString(int length, Random random) { this(length, random, alphanum); } /** * Create an alphanumeric strings from a secure generator. */ public RandomString(int length) { this(length, new SecureRandom()); } /** * Create session identifiers. */ public RandomString() { this(21); } } Usage examples Create an insecure generator for 8-character identifiers: RandomString gen = new RandomString(8, ThreadLocalRandom.current()); Create a secure generator for session identifiers: RandomString session = new RandomString(); Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols: String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx"; RandomString tickets = new RandomString(23, new SecureRandom(), easy); Use as session identifiers Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used. There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand. The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible. Use as object identifiers Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big. Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission. Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." The probability of a collision, p, is approximately n 2 /(2q x ), where n is the number of identifiers actually generated, q is the number of distinct symbols in the alphabet, and x is the length of the identifiers. This should be a very small number, like 2 ‑50 or less. Working this out shows that the chance of collision among 500k 15-character identifiers is about 2 ‑52, which is probably less likely than undetected errors from cosmic rays, etc. Comparison with UUIDs According to their specification, UUIDs are not designed to be unpredictable, and should not be used as session identifiers. UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters. UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.
How to generate a random alpha-numeric string I've been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over 500K+ generation (my needs don't really require anything much more sophisticated). Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like "AEYGF7K0DM1X".
TITLE: How to generate a random alpha-numeric string QUESTION: I've been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over 500K+ generation (my needs don't really require anything much more sophisticated). Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like "AEYGF7K0DM1X". ANSWER: Algorithm To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length. Implementation Here's some fairly simple and very flexible code for generating random identifiers. Read the information that follows for important application notes. public class RandomString { /** * Generate a random string. */ public String nextString() { for (int idx = 0; idx < buf.length; ++idx) buf[idx] = symbols[random.nextInt(symbols.length)]; return new String(buf); } public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String lower = upper.toLowerCase(Locale.ROOT); public static final String digits = "0123456789"; public static final String alphanum = upper + lower + digits; private final Random random; private final char[] symbols; private final char[] buf; public RandomString(int length, Random random, String symbols) { if (length < 1) throw new IllegalArgumentException(); if (symbols.length() < 2) throw new IllegalArgumentException(); this.random = Objects.requireNonNull(random); this.symbols = symbols.toCharArray(); this.buf = new char[length]; } /** * Create an alphanumeric string generator. */ public RandomString(int length, Random random) { this(length, random, alphanum); } /** * Create an alphanumeric strings from a secure generator. */ public RandomString(int length) { this(length, new SecureRandom()); } /** * Create session identifiers. */ public RandomString() { this(21); } } Usage examples Create an insecure generator for 8-character identifiers: RandomString gen = new RandomString(8, ThreadLocalRandom.current()); Create a secure generator for session identifiers: RandomString session = new RandomString(); Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols: String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx"; RandomString tickets = new RandomString(23, new SecureRandom(), easy); Use as session identifiers Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used. There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand. The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible. Use as object identifiers Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big. Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission. Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." The probability of a collision, p, is approximately n 2 /(2q x ), where n is the number of identifiers actually generated, q is the number of distinct symbols in the alphabet, and x is the length of the identifiers. This should be a very small number, like 2 ‑50 or less. Working this out shows that the chance of collision among 500k 15-character identifiers is about 2 ‑52, which is probably less likely than undetected errors from cosmic rays, etc. Comparison with UUIDs According to their specification, UUIDs are not designed to be unpredictable, and should not be used as session identifiers. UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters. UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.
[ "java", "string", "random", "alphanumeric" ]
1,974
1,634
1,662,183
46
0
2008-09-03T02:58:43.073000
2008-09-03T04:04:24.647000
41,155
545,754
WCF Service Returning "Method Not Allowed"
In the process of developing my first WCF service and when I try to use it I get "Method not Allowed" with no other explanation. I've got my interface set up with the ServiceContract and OperationContract: [OperationContract] void FileUpload(UploadedFile file); Along with the actual method: public void FileUpload(UploadedFile file) {}; To access the Service I enter http://localhost/project/myService.svc/FileUpload but I get the "Method not Allowed" error Am I missing something?
Your browser is sending an HTTP GET request: Make sure you have the WebGet attribute on the operation in the contract: [ServiceContract] public interface IUploadService { [WebGet()] [OperationContract] string TestGetMethod(); // This method takes no arguments, returns a string. Perfect for testing quickly with a browser. [OperationContract] void UploadFile(UploadedFile file); // This probably involves an HTTP POST request. Not so easy for a quick browser test. }
WCF Service Returning "Method Not Allowed" In the process of developing my first WCF service and when I try to use it I get "Method not Allowed" with no other explanation. I've got my interface set up with the ServiceContract and OperationContract: [OperationContract] void FileUpload(UploadedFile file); Along with the actual method: public void FileUpload(UploadedFile file) {}; To access the Service I enter http://localhost/project/myService.svc/FileUpload but I get the "Method not Allowed" error Am I missing something?
TITLE: WCF Service Returning "Method Not Allowed" QUESTION: In the process of developing my first WCF service and when I try to use it I get "Method not Allowed" with no other explanation. I've got my interface set up with the ServiceContract and OperationContract: [OperationContract] void FileUpload(UploadedFile file); Along with the actual method: public void FileUpload(UploadedFile file) {}; To access the Service I enter http://localhost/project/myService.svc/FileUpload but I get the "Method not Allowed" error Am I missing something? ANSWER: Your browser is sending an HTTP GET request: Make sure you have the WebGet attribute on the operation in the contract: [ServiceContract] public interface IUploadService { [WebGet()] [OperationContract] string TestGetMethod(); // This method takes no arguments, returns a string. Perfect for testing quickly with a browser. [OperationContract] void UploadFile(UploadedFile file); // This probably involves an HTTP POST request. Not so easy for a quick browser test. }
[ ".net", "wcf", "web-services" ]
45
66
113,371
9
0
2008-09-03T04:03:49.313000
2009-02-13T12:34:26.253000
41,159
41,175
Fastest way to find common items across multiple lists in C#
Given the following: List > optionLists; what would be a quick way to determine the subset of Option objects that appear in all N lists? Equality is determined through some string property such as option1.Value == option2.Value. So we should end up with List where each item appears only once.
Ok, this will find the list of Option objects that have a Value appearing in every list. var x = from list in optionLists from option in list where optionLists.All(l => l.Any(o => o.Value == option.Value)) orderby option.Value select option; It doesn't do a "distinct" select so it'll return multiple Option objects, some of them with the same Value.
Fastest way to find common items across multiple lists in C# Given the following: List > optionLists; what would be a quick way to determine the subset of Option objects that appear in all N lists? Equality is determined through some string property such as option1.Value == option2.Value. So we should end up with List where each item appears only once.
TITLE: Fastest way to find common items across multiple lists in C# QUESTION: Given the following: List > optionLists; what would be a quick way to determine the subset of Option objects that appear in all N lists? Equality is determined through some string property such as option1.Value == option2.Value. So we should end up with List where each item appears only once. ANSWER: Ok, this will find the list of Option objects that have a Value appearing in every list. var x = from list in optionLists from option in list where optionLists.All(l => l.Any(o => o.Value == option.Value)) orderby option.Value select option; It doesn't do a "distinct" select so it'll return multiple Option objects, some of them with the same Value.
[ "c#" ]
6
9
15,485
11
0
2008-09-03T04:13:46.607000
2008-09-03T04:32:09.010000
41,162
41,173
Javascript spinning wait hourglass-type thing
I'd like to indicate to the user of a web app that a long-running task is being performed. Once upon a time, this concept would have been communicated to the user by displaying an hourglass. Nowadays, it seems to be an animated spinning circle. (e.g., when you are loading a new tab in Firefox, or booting in Mac OS X. Coincidentally, the overflowing stack in the stackoverflow logo looks like one quarter of the circle). Is there a simple way to create this effect using Javascript (in particular, JQuery)? Ideally, I'd like to have one of these little spinners as elements in a table, to indicate to the user that the system is still active in processing a pending task (i.e., it hasn't forgotten or crashed). (Of course, I realize it's possible that the back-end has crashed and the front-end still show as an animating spinning thing, it's more for the psychological purpose of the user seeing activity). And what do you call that spinning thing, anyways?
Google Ajax activity indicator to find lots of images and image generators (the "spinning" image itself is an animated GIF). Here is one link to get you started. With the image in hand, use JQuery to toggle the visibility of the image (or perhaps its parent DIV tag). See this link for some more info. rp
Javascript spinning wait hourglass-type thing I'd like to indicate to the user of a web app that a long-running task is being performed. Once upon a time, this concept would have been communicated to the user by displaying an hourglass. Nowadays, it seems to be an animated spinning circle. (e.g., when you are loading a new tab in Firefox, or booting in Mac OS X. Coincidentally, the overflowing stack in the stackoverflow logo looks like one quarter of the circle). Is there a simple way to create this effect using Javascript (in particular, JQuery)? Ideally, I'd like to have one of these little spinners as elements in a table, to indicate to the user that the system is still active in processing a pending task (i.e., it hasn't forgotten or crashed). (Of course, I realize it's possible that the back-end has crashed and the front-end still show as an animating spinning thing, it's more for the psychological purpose of the user seeing activity). And what do you call that spinning thing, anyways?
TITLE: Javascript spinning wait hourglass-type thing QUESTION: I'd like to indicate to the user of a web app that a long-running task is being performed. Once upon a time, this concept would have been communicated to the user by displaying an hourglass. Nowadays, it seems to be an animated spinning circle. (e.g., when you are loading a new tab in Firefox, or booting in Mac OS X. Coincidentally, the overflowing stack in the stackoverflow logo looks like one quarter of the circle). Is there a simple way to create this effect using Javascript (in particular, JQuery)? Ideally, I'd like to have one of these little spinners as elements in a table, to indicate to the user that the system is still active in processing a pending task (i.e., it hasn't forgotten or crashed). (Of course, I realize it's possible that the back-end has crashed and the front-end still show as an animating spinning thing, it's more for the psychological purpose of the user seeing activity). And what do you call that spinning thing, anyways? ANSWER: Google Ajax activity indicator to find lots of images and image generators (the "spinning" image itself is an animated GIF). Here is one link to get you started. With the image in hand, use JQuery to toggle the visibility of the image (or perhaps its parent DIV tag). See this link for some more info. rp
[ "javascript", "jquery" ]
12
21
31,907
4
0
2008-09-03T04:18:18.840000
2008-09-03T04:32:03.270000
41,185
41,202
Vista Console App?
I'm doing a fair bit of work in Ruby recently, and using ruby script/console Is absolutely critical. However, I'm really disappointed with the default Windows console in Vista, especially in that there's a really annoying bug where moving the cursor back when at the bottom of the screen irregularly causes it to jump back. Anyone have a decent console app they use in Windows?
I use Console2. I like the tabbed interface and that copy works properly if text breaks at the end of a line.
Vista Console App? I'm doing a fair bit of work in Ruby recently, and using ruby script/console Is absolutely critical. However, I'm really disappointed with the default Windows console in Vista, especially in that there's a really annoying bug where moving the cursor back when at the bottom of the screen irregularly causes it to jump back. Anyone have a decent console app they use in Windows?
TITLE: Vista Console App? QUESTION: I'm doing a fair bit of work in Ruby recently, and using ruby script/console Is absolutely critical. However, I'm really disappointed with the default Windows console in Vista, especially in that there's a really annoying bug where moving the cursor back when at the bottom of the screen irregularly causes it to jump back. Anyone have a decent console app they use in Windows? ANSWER: I use Console2. I like the tabbed interface and that copy works properly if text breaks at the end of a line.
[ "windows", "ruby", "windows-vista", "console" ]
1
7
892
4
0
2008-09-03T04:42:04.573000
2008-09-03T05:11:52.037000
41,188
41,209
Waveform Visualization in Ruby
I'm about to start a project that will record and edit audio files, and I'm looking for a good library (preferably Ruby, but will consider anything other than Java or.NET) for on-the-fly visualization of waveforms. Does anybody know where I should start my search?
That's a lot of data to be streaming into a browser. Flash or Flex charts is probably the only solution that will be memory efficient. Javascript charting tends to break-down for large data sets.
Waveform Visualization in Ruby I'm about to start a project that will record and edit audio files, and I'm looking for a good library (preferably Ruby, but will consider anything other than Java or.NET) for on-the-fly visualization of waveforms. Does anybody know where I should start my search?
TITLE: Waveform Visualization in Ruby QUESTION: I'm about to start a project that will record and edit audio files, and I'm looking for a good library (preferably Ruby, but will consider anything other than Java or.NET) for on-the-fly visualization of waveforms. Does anybody know where I should start my search? ANSWER: That's a lot of data to be streaming into a browser. Flash or Flex charts is probably the only solution that will be memory efficient. Javascript charting tends to break-down for large data sets.
[ "ruby", "audio", "mp3", "visualization", "waveform" ]
5
3
5,109
5
0
2008-09-03T04:54:21.453000
2008-09-03T05:29:16.877000
41,207
747,082
JavaScript interactive shell with completion
For debugging and testing I'm searching for a JavaScript shell with auto completion and if possible object introspection (like ipython). The online JavaScript Shell is really nice, but I'm looking for something local, without the need for an browser. So far I have tested the standalone JavaScript interpreter rhino, spidermonkey and google V8. But neither of them has completion. At least Rhino with jline and spidermonkey have some kind of command history via key up/down, but nothing more. Any suggestions? This question was asked again here. It might contain an answer that you are looking for.
Rhino Shell since 1.7R2 has support for completion as well. You can find more information here.
JavaScript interactive shell with completion For debugging and testing I'm searching for a JavaScript shell with auto completion and if possible object introspection (like ipython). The online JavaScript Shell is really nice, but I'm looking for something local, without the need for an browser. So far I have tested the standalone JavaScript interpreter rhino, spidermonkey and google V8. But neither of them has completion. At least Rhino with jline and spidermonkey have some kind of command history via key up/down, but nothing more. Any suggestions? This question was asked again here. It might contain an answer that you are looking for.
TITLE: JavaScript interactive shell with completion QUESTION: For debugging and testing I'm searching for a JavaScript shell with auto completion and if possible object introspection (like ipython). The online JavaScript Shell is really nice, but I'm looking for something local, without the need for an browser. So far I have tested the standalone JavaScript interpreter rhino, spidermonkey and google V8. But neither of them has completion. At least Rhino with jline and spidermonkey have some kind of command history via key up/down, but nothing more. Any suggestions? This question was asked again here. It might contain an answer that you are looking for. ANSWER: Rhino Shell since 1.7R2 has support for completion as well. You can find more information here.
[ "javascript" ]
31
19
21,993
6
0
2008-09-03T05:27:19.487000
2009-04-14T11:03:50.347000
41,218
43,384
Testing HTTPS files with MAMP
I am running MAMP locally on my laptop, and I like to test as much as I can locally. Unfortunately, since I work on e-commerce stuff (PHP), I normally force ssl in most of the checkout forms and it just fails on my laptop. Is there any easy configuration that I might be missing to allow "https" to run under MAMP? Please note, I know that I could configure Apache by hand, re-compile PHP, etc. but I'm just wondering if there's an easier way for a lazy programmer. Thanks
NOTE: startssl is no longer supported after version 2+ of MAMP. You have to update the config files (httpd.conf) to enable ssl. You can modify the free version of MAMP to enable ssl by default very easily. Once you have setup all the SSL parts of apache and have it working so that calling apachectl startssl works, just edit the file /Applications/MAMP/startApache.sh in your favorite text editor and change the start argument to startssl and you will have the MAMP launcher starting apache in ssl mode for you.
Testing HTTPS files with MAMP I am running MAMP locally on my laptop, and I like to test as much as I can locally. Unfortunately, since I work on e-commerce stuff (PHP), I normally force ssl in most of the checkout forms and it just fails on my laptop. Is there any easy configuration that I might be missing to allow "https" to run under MAMP? Please note, I know that I could configure Apache by hand, re-compile PHP, etc. but I'm just wondering if there's an easier way for a lazy programmer. Thanks
TITLE: Testing HTTPS files with MAMP QUESTION: I am running MAMP locally on my laptop, and I like to test as much as I can locally. Unfortunately, since I work on e-commerce stuff (PHP), I normally force ssl in most of the checkout forms and it just fails on my laptop. Is there any easy configuration that I might be missing to allow "https" to run under MAMP? Please note, I know that I could configure Apache by hand, re-compile PHP, etc. but I'm just wondering if there's an easier way for a lazy programmer. Thanks ANSWER: NOTE: startssl is no longer supported after version 2+ of MAMP. You have to update the config files (httpd.conf) to enable ssl. You can modify the free version of MAMP to enable ssl by default very easily. Once you have setup all the SSL parts of apache and have it working so that calling apachectl startssl works, just edit the file /Applications/MAMP/startApache.sh in your favorite text editor and change the start argument to startssl and you will have the MAMP launcher starting apache in ssl mode for you.
[ "apache", "macos", "ssl", "https", "mamp" ]
16
10
15,427
3
0
2008-09-03T05:44:06.747000
2008-09-04T09:11:08.083000
41,220
41,228
Is there a best .NET algorithm for credit card encryption?
The.NET System.Security.Cryptography namespace has a rather bewildering collection of algorithms that I could use for encryption of credit card details. Which is the best? It clearly needs to be secure for a relatively short string. EDIT: I'm in the UK, where I understand we're OK storing encrypted credit card details so long as the three-digit CVV number is never stored. And thanks all for the great responses.
No offense, but the question is a little "misguided". There is no "silver bullet" solution. I would recommend to read up on cryptography in general and then do some threat modeling. Some questions (by no means a comprehensive list) you should ask yourself: Is the module doing the encryption the one which needs to decrypt it (in this case use symmetric crypto) or will it send data to an other module (on an other machine) which will use it (in which case you should consider public-key crypto) What do you want to protect against? Someone accessing the database but not having the sourcecode (in which case you can hardcode the encryption key directly into the source)? Someone sniffing your local network (you should consider transparent solutions like IPSec)? Someone stealing your server (it can happen even in data centers - in which case full disk encryption should be considered)? Do you really need to keep the data? Can't you directly pass it to the credit card processor and erase it after you get the confirmation? Can't you store it locally at the client in a cookie or Flash LSO? If you store it at the client, make sure that you encrypt it at the server side before putting it in a cookie. Also, if you are using cookies, make sure that you make them http only. Is it enough to compare the equality of the data (ie the data that the client has given me is the same data that I have)? If so, consider storing a hash of it. Because credit card numbers are relatively short and use a reduced set of symbols, a unique salt should be generated for each before hashing. Later edit: note that standard encryption algorithms from the same category (for example 3DES and AES - both being symmetric block cyphers) are of comparable strength. Most (commercial) systems are not broken because somebody bruteforced their encryption, but because their threat modelling was not detailed enough (or flat out they didn't have any). For example you can encrypt all the data, but if you happen to have a public facing web interface which is vulnerable to SQL injection, it won't help you much.
Is there a best .NET algorithm for credit card encryption? The.NET System.Security.Cryptography namespace has a rather bewildering collection of algorithms that I could use for encryption of credit card details. Which is the best? It clearly needs to be secure for a relatively short string. EDIT: I'm in the UK, where I understand we're OK storing encrypted credit card details so long as the three-digit CVV number is never stored. And thanks all for the great responses.
TITLE: Is there a best .NET algorithm for credit card encryption? QUESTION: The.NET System.Security.Cryptography namespace has a rather bewildering collection of algorithms that I could use for encryption of credit card details. Which is the best? It clearly needs to be secure for a relatively short string. EDIT: I'm in the UK, where I understand we're OK storing encrypted credit card details so long as the three-digit CVV number is never stored. And thanks all for the great responses. ANSWER: No offense, but the question is a little "misguided". There is no "silver bullet" solution. I would recommend to read up on cryptography in general and then do some threat modeling. Some questions (by no means a comprehensive list) you should ask yourself: Is the module doing the encryption the one which needs to decrypt it (in this case use symmetric crypto) or will it send data to an other module (on an other machine) which will use it (in which case you should consider public-key crypto) What do you want to protect against? Someone accessing the database but not having the sourcecode (in which case you can hardcode the encryption key directly into the source)? Someone sniffing your local network (you should consider transparent solutions like IPSec)? Someone stealing your server (it can happen even in data centers - in which case full disk encryption should be considered)? Do you really need to keep the data? Can't you directly pass it to the credit card processor and erase it after you get the confirmation? Can't you store it locally at the client in a cookie or Flash LSO? If you store it at the client, make sure that you encrypt it at the server side before putting it in a cookie. Also, if you are using cookies, make sure that you make them http only. Is it enough to compare the equality of the data (ie the data that the client has given me is the same data that I have)? If so, consider storing a hash of it. Because credit card numbers are relatively short and use a reduced set of symbols, a unique salt should be generated for each before hashing. Later edit: note that standard encryption algorithms from the same category (for example 3DES and AES - both being symmetric block cyphers) are of comparable strength. Most (commercial) systems are not broken because somebody bruteforced their encryption, but because their threat modelling was not detailed enough (or flat out they didn't have any). For example you can encrypt all the data, but if you happen to have a public facing web interface which is vulnerable to SQL injection, it won't help you much.
[ ".net", "security", "encryption", "cryptography" ]
8
24
8,098
10
0
2008-09-03T05:46:20.563000
2008-09-03T06:02:00.323000
41,233
41,241
Java and SQLite
I'm attracted to the neatness that a single file database provides. What driver/connector library is out there to connect and use SQLite with Java. I've discovered a wrapper library, http://www.ch-werner.de/javasqlite, but are there other more prominent projects available?
The wiki lists some more wrappers: Java wrapper (around a SWIG interface): http://tk-software.home.comcast.net/ A good tutorial to use JDBC driver for SQLite. (it works at least!) http://www.ci.uchicago.edu/wiki/bin/view/VDS/VDSDevelopment/UsingSQLite Cross-platform JDBC driver which uses embedded native SQLite libraries on Windows, Linux, OS X, and falls back to pure Java implementation on other OSes: https://github.com/xerial/sqlite-jdbc (formerly zentus ) Another Java - SWIG wrapper. It only works on Win32. http://rodolfo_3.tripod.com/index.html sqlite-java-shell: 100% pure Java port of the sqlite3 commandline shell built with NestedVM. (This is not a JDBC driver). SQLite JDBC Driver for Mysaifu JVM: SQLite JDBC Driver for Mysaifu JVM and SQLite JNI Library for Windows (x86) and Linux (i386/PowerPC).
Java and SQLite I'm attracted to the neatness that a single file database provides. What driver/connector library is out there to connect and use SQLite with Java. I've discovered a wrapper library, http://www.ch-werner.de/javasqlite, but are there other more prominent projects available?
TITLE: Java and SQLite QUESTION: I'm attracted to the neatness that a single file database provides. What driver/connector library is out there to connect and use SQLite with Java. I've discovered a wrapper library, http://www.ch-werner.de/javasqlite, but are there other more prominent projects available? ANSWER: The wiki lists some more wrappers: Java wrapper (around a SWIG interface): http://tk-software.home.comcast.net/ A good tutorial to use JDBC driver for SQLite. (it works at least!) http://www.ci.uchicago.edu/wiki/bin/view/VDS/VDSDevelopment/UsingSQLite Cross-platform JDBC driver which uses embedded native SQLite libraries on Windows, Linux, OS X, and falls back to pure Java implementation on other OSes: https://github.com/xerial/sqlite-jdbc (formerly zentus ) Another Java - SWIG wrapper. It only works on Win32. http://rodolfo_3.tripod.com/index.html sqlite-java-shell: 100% pure Java port of the sqlite3 commandline shell built with NestedVM. (This is not a JDBC driver). SQLite JDBC Driver for Mysaifu JVM: SQLite JDBC Driver for Mysaifu JVM and SQLite JNI Library for Windows (x86) and Linux (i386/PowerPC).
[ "java", "sqlite" ]
336
196
315,838
9
0
2008-09-03T06:10:15.297000
2008-09-03T06:17:50.007000
41,234
41,250
Apache serving files that should not be served
Today I discovered that my fresh installation of Apache HTTP Server is able to serve files from my C:\uploads\ directory. I have two folders in C:\uploads: C:\uploads\templates C:\uploads\sites Both folders contain testimage.jpg. I found that Apache will serve the files from the templates folder if I request: http://localhost/templates/testimage.jpg However, http://localhost/sites/testimage.jpg 404 's! OMG - firstly, why does Apache serve the templates folder in the first place? Is it special? Secondly, by what arbitrary set of rules does apache disallow access to other folders such the sites? I'm so confused. Perhaps I've taken a wrong turn somewhere during the installation.
Did you look through your httpd.conf file to see what rules are in place for what is being served? Alternatively, are there.htaccess files that may be changing what is being served? You might have templates exposed in one or the other, but not sites... that's the first thing that comes to mind. I would suggest going through these configuration files with a fine toothed comb to see what may cause the behavior you see.
Apache serving files that should not be served Today I discovered that my fresh installation of Apache HTTP Server is able to serve files from my C:\uploads\ directory. I have two folders in C:\uploads: C:\uploads\templates C:\uploads\sites Both folders contain testimage.jpg. I found that Apache will serve the files from the templates folder if I request: http://localhost/templates/testimage.jpg However, http://localhost/sites/testimage.jpg 404 's! OMG - firstly, why does Apache serve the templates folder in the first place? Is it special? Secondly, by what arbitrary set of rules does apache disallow access to other folders such the sites? I'm so confused. Perhaps I've taken a wrong turn somewhere during the installation.
TITLE: Apache serving files that should not be served QUESTION: Today I discovered that my fresh installation of Apache HTTP Server is able to serve files from my C:\uploads\ directory. I have two folders in C:\uploads: C:\uploads\templates C:\uploads\sites Both folders contain testimage.jpg. I found that Apache will serve the files from the templates folder if I request: http://localhost/templates/testimage.jpg However, http://localhost/sites/testimage.jpg 404 's! OMG - firstly, why does Apache serve the templates folder in the first place? Is it special? Secondly, by what arbitrary set of rules does apache disallow access to other folders such the sites? I'm so confused. Perhaps I've taken a wrong turn somewhere during the installation. ANSWER: Did you look through your httpd.conf file to see what rules are in place for what is being served? Alternatively, are there.htaccess files that may be changing what is being served? You might have templates exposed in one or the other, but not sites... that's the first thing that comes to mind. I would suggest going through these configuration files with a fine toothed comb to see what may cause the behavior you see.
[ "apache", "webserver", "hosting", "web-hosting", "self-hosting" ]
0
1
460
1
0
2008-09-03T06:11:09.007000
2008-09-03T06:42:02.723000
41,244
233,505
Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>
I found an example in the VS2008 Examples for Dynamic LINQ that allows you to use a SQL-like string (e.g. OrderBy("Name, Age DESC")) for ordering. Unfortunately, the method included only works on IQueryable. Is there any way to get this functionality on IEnumerable?
Just stumbled into this oldie... To do this without the dynamic LINQ library, you just need the code as below. This covers most common scenarios including nested properties. To get it working with IEnumerable you could add some wrapper methods that go via AsQueryable - but the code below is the core Expression logic needed. public static IOrderedQueryable OrderBy ( this IQueryable source, string property) { return ApplyOrder (source, property, "OrderBy"); } public static IOrderedQueryable OrderByDescending ( this IQueryable source, string property) { return ApplyOrder (source, property, "OrderByDescending"); } public static IOrderedQueryable ThenBy ( this IOrderedQueryable source, string property) { return ApplyOrder (source, property, "ThenBy"); } public static IOrderedQueryable ThenByDescending ( this IOrderedQueryable source, string property) { return ApplyOrder (source, property, "ThenByDescending"); } static IOrderedQueryable ApplyOrder ( IQueryable source, string property, string methodName) { string[] props = property.Split('.'); Type type = typeof(T); ParameterExpression arg = Expression.Parameter(type, "x"); Expression expr = arg; foreach(string prop in props) { // use reflection (not ComponentModel) to mirror LINQ PropertyInfo pi = type.GetProperty(prop); expr = Expression.Property(expr, pi); type = pi.PropertyType; } Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg); object result = typeof(Queryable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 2 && method.GetParameters().Length == 2).MakeGenericMethod(typeof(T), type).Invoke(null, new object[] {source, lambda}); return (IOrderedQueryable )result; } Edit: it gets more fun if you want to mix that with dynamic - although note that dynamic only applies to LINQ-to-Objects (expression-trees for ORMs etc can't really represent dynamic queries - MemberExpression doesn't support it). But here's a way to do it with LINQ-to-Objects. Note that the choice of Hashtable is due to favorable locking semantics: using Microsoft.CSharp.RuntimeBinder; using System; using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Runtime.CompilerServices; static class Program { private static class AccessorCache { private static readonly Hashtable accessors = new Hashtable(); private static readonly Hashtable callSites = new Hashtable(); private static CallSite > GetCallSiteLocked( string name) { var callSite = (CallSite >)callSites[name]; if(callSite == null) { callSites[name] = callSite = CallSite >.Create(Binder.GetMember( CSharpBinderFlags.None, name, typeof(AccessorCache), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create( CSharpArgumentInfoFlags.None, null) })); } return callSite; } internal static Func GetAccessor(string name) { Func accessor = (Func )accessors[name]; if (accessor == null) { lock (accessors ) { accessor = (Func )accessors[name]; if (accessor == null) { if(name.IndexOf('.') >= 0) { string[] props = name.Split('.'); CallSite >[] arr = Array.ConvertAll(props, GetCallSiteLocked); accessor = target => { object val = (object)target; for (int i = 0; i < arr.Length; i++) { var cs = arr[i]; val = cs.Target(cs, val); } return val; }; } else { var callSite = GetCallSiteLocked(name); accessor = target => { return callSite.Target(callSite, (object)target); }; } accessors[name] = accessor; } } } return accessor; } } public static IOrderedEnumerable OrderBy( this IEnumerable source, string property) { return Enumerable.OrderBy ( source, AccessorCache.GetAccessor(property), Comparer.Default); } public static IOrderedEnumerable OrderByDescending( this IEnumerable source, string property) { return Enumerable.OrderByDescending ( source, AccessorCache.GetAccessor(property), Comparer.Default); } public static IOrderedEnumerable ThenBy( this IOrderedEnumerable source, string property) { return Enumerable.ThenBy ( source, AccessorCache.GetAccessor(property), Comparer.Default); } public static IOrderedEnumerable ThenByDescending( this IOrderedEnumerable source, string property) { return Enumerable.ThenByDescending ( source, AccessorCache.GetAccessor(property), Comparer.Default); } static void Main() { dynamic a = new ExpandoObject(), b = new ExpandoObject(), c = new ExpandoObject(); a.X = "abc"; b.X = "ghi"; c.X = "def"; dynamic[] data = new[] { new { Y = a }, new { Y = b }, new { Y = c } }; var ordered = data.OrderByDescending("Y.X").ToArray(); foreach (var obj in ordered) { Console.WriteLine(obj.Y.X); } } }
Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T> I found an example in the VS2008 Examples for Dynamic LINQ that allows you to use a SQL-like string (e.g. OrderBy("Name, Age DESC")) for ordering. Unfortunately, the method included only works on IQueryable. Is there any way to get this functionality on IEnumerable?
TITLE: Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T> QUESTION: I found an example in the VS2008 Examples for Dynamic LINQ that allows you to use a SQL-like string (e.g. OrderBy("Name, Age DESC")) for ordering. Unfortunately, the method included only works on IQueryable. Is there any way to get this functionality on IEnumerable? ANSWER: Just stumbled into this oldie... To do this without the dynamic LINQ library, you just need the code as below. This covers most common scenarios including nested properties. To get it working with IEnumerable you could add some wrapper methods that go via AsQueryable - but the code below is the core Expression logic needed. public static IOrderedQueryable OrderBy ( this IQueryable source, string property) { return ApplyOrder (source, property, "OrderBy"); } public static IOrderedQueryable OrderByDescending ( this IQueryable source, string property) { return ApplyOrder (source, property, "OrderByDescending"); } public static IOrderedQueryable ThenBy ( this IOrderedQueryable source, string property) { return ApplyOrder (source, property, "ThenBy"); } public static IOrderedQueryable ThenByDescending ( this IOrderedQueryable source, string property) { return ApplyOrder (source, property, "ThenByDescending"); } static IOrderedQueryable ApplyOrder ( IQueryable source, string property, string methodName) { string[] props = property.Split('.'); Type type = typeof(T); ParameterExpression arg = Expression.Parameter(type, "x"); Expression expr = arg; foreach(string prop in props) { // use reflection (not ComponentModel) to mirror LINQ PropertyInfo pi = type.GetProperty(prop); expr = Expression.Property(expr, pi); type = pi.PropertyType; } Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg); object result = typeof(Queryable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 2 && method.GetParameters().Length == 2).MakeGenericMethod(typeof(T), type).Invoke(null, new object[] {source, lambda}); return (IOrderedQueryable )result; } Edit: it gets more fun if you want to mix that with dynamic - although note that dynamic only applies to LINQ-to-Objects (expression-trees for ORMs etc can't really represent dynamic queries - MemberExpression doesn't support it). But here's a way to do it with LINQ-to-Objects. Note that the choice of Hashtable is due to favorable locking semantics: using Microsoft.CSharp.RuntimeBinder; using System; using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Runtime.CompilerServices; static class Program { private static class AccessorCache { private static readonly Hashtable accessors = new Hashtable(); private static readonly Hashtable callSites = new Hashtable(); private static CallSite > GetCallSiteLocked( string name) { var callSite = (CallSite >)callSites[name]; if(callSite == null) { callSites[name] = callSite = CallSite >.Create(Binder.GetMember( CSharpBinderFlags.None, name, typeof(AccessorCache), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create( CSharpArgumentInfoFlags.None, null) })); } return callSite; } internal static Func GetAccessor(string name) { Func accessor = (Func )accessors[name]; if (accessor == null) { lock (accessors ) { accessor = (Func )accessors[name]; if (accessor == null) { if(name.IndexOf('.') >= 0) { string[] props = name.Split('.'); CallSite >[] arr = Array.ConvertAll(props, GetCallSiteLocked); accessor = target => { object val = (object)target; for (int i = 0; i < arr.Length; i++) { var cs = arr[i]; val = cs.Target(cs, val); } return val; }; } else { var callSite = GetCallSiteLocked(name); accessor = target => { return callSite.Target(callSite, (object)target); }; } accessors[name] = accessor; } } } return accessor; } } public static IOrderedEnumerable OrderBy( this IEnumerable source, string property) { return Enumerable.OrderBy ( source, AccessorCache.GetAccessor(property), Comparer.Default); } public static IOrderedEnumerable OrderByDescending( this IEnumerable source, string property) { return Enumerable.OrderByDescending ( source, AccessorCache.GetAccessor(property), Comparer.Default); } public static IOrderedEnumerable ThenBy( this IOrderedEnumerable source, string property) { return Enumerable.ThenBy ( source, AccessorCache.GetAccessor(property), Comparer.Default); } public static IOrderedEnumerable ThenByDescending( this IOrderedEnumerable source, string property) { return Enumerable.ThenByDescending ( source, AccessorCache.GetAccessor(property), Comparer.Default); } static void Main() { dynamic a = new ExpandoObject(), b = new ExpandoObject(), c = new ExpandoObject(); a.X = "abc"; b.X = "ghi"; c.X = "def"; dynamic[] data = new[] { new { Y = a }, new { Y = b }, new { Y = c } }; var ordered = data.OrderByDescending("Y.X").ToArray(); foreach (var obj in ordered) { Console.WriteLine(obj.Y.X); } } }
[ "c#", "linq", "ienumerable", "iqueryable", "linq-to-objects" ]
753
978
330,813
24
0
2008-09-03T06:30:31.927000
2008-10-24T13:21:09.627000
41,256
41,267
New Added Types in .NET Framework 2.0 Service Pack 1
I assumed there were only bug fixes/(no new types) in.NET 2.0 SP1 until I came across few posts which were mentioning DateTimeOffset structure, that was added in.NET 2.0 SP1. Is there a full listing of the newly added types in.NET 2.0 SP1?
Here's what you're looking for: Full Article: http://www.hanselman.com/blog/CatchingRedBitsDifferencesInNET20AndNET20SP1.aspx This may also be helpful: Full Article: http://www.hanselman.com/blog/ChangesInTheNETBCLBetween20And35.aspx
New Added Types in .NET Framework 2.0 Service Pack 1 I assumed there were only bug fixes/(no new types) in.NET 2.0 SP1 until I came across few posts which were mentioning DateTimeOffset structure, that was added in.NET 2.0 SP1. Is there a full listing of the newly added types in.NET 2.0 SP1?
TITLE: New Added Types in .NET Framework 2.0 Service Pack 1 QUESTION: I assumed there were only bug fixes/(no new types) in.NET 2.0 SP1 until I came across few posts which were mentioning DateTimeOffset structure, that was added in.NET 2.0 SP1. Is there a full listing of the newly added types in.NET 2.0 SP1? ANSWER: Here's what you're looking for: Full Article: http://www.hanselman.com/blog/CatchingRedBitsDifferencesInNET20AndNET20SP1.aspx This may also be helpful: Full Article: http://www.hanselman.com/blog/ChangesInTheNETBCLBetween20And35.aspx
[ ".net", ".net-2.0" ]
4
6
698
4
0
2008-09-03T06:49:23.440000
2008-09-03T07:13:18.313000
41,273
81,440
SQL Server Merge Replication Schedule
We're replicating a database between London and Hong Kong using SQL Server 2005 Merge replication. The replication is set to synchronise every one minute and it works just fine. There is however the option to set the synchronisation to be "Continuous". Is there any real difference between replication every one minute and continuously? The only reason for us doing every one minute rather than continuous in the first place was that it recovered better if the line went down for a few minutes, but this experience was all from SQL Server 2000 so it might not be applicable any more...
We have been trying the continuous replication solution on SQL SERVER 2005 and it appeared to be less efficient than a scheduled solution: as your process is continuous, you will not get all the info related to your passed replications (how many replications failed, how long did the process take, why was the process stopped, how many records were updated, how many database structure modifications were replicated to suscribers, and so on), making the replication follow-up a lot more difficult. We have also been experiencing troubles while modifying database structure (ALTER TABLE instructions) and/or making bulk updates on one of the databases with continuous replication going on. Keep you "every minute" synchro as it is and just forget about this "continuous" option.
SQL Server Merge Replication Schedule We're replicating a database between London and Hong Kong using SQL Server 2005 Merge replication. The replication is set to synchronise every one minute and it works just fine. There is however the option to set the synchronisation to be "Continuous". Is there any real difference between replication every one minute and continuously? The only reason for us doing every one minute rather than continuous in the first place was that it recovered better if the line went down for a few minutes, but this experience was all from SQL Server 2000 so it might not be applicable any more...
TITLE: SQL Server Merge Replication Schedule QUESTION: We're replicating a database between London and Hong Kong using SQL Server 2005 Merge replication. The replication is set to synchronise every one minute and it works just fine. There is however the option to set the synchronisation to be "Continuous". Is there any real difference between replication every one minute and continuously? The only reason for us doing every one minute rather than continuous in the first place was that it recovered better if the line went down for a few minutes, but this experience was all from SQL Server 2000 so it might not be applicable any more... ANSWER: We have been trying the continuous replication solution on SQL SERVER 2005 and it appeared to be less efficient than a scheduled solution: as your process is continuous, you will not get all the info related to your passed replications (how many replications failed, how long did the process take, why was the process stopped, how many records were updated, how many database structure modifications were replicated to suscribers, and so on), making the replication follow-up a lot more difficult. We have also been experiencing troubles while modifying database structure (ALTER TABLE instructions) and/or making bulk updates on one of the databases with continuous replication going on. Keep you "every minute" synchro as it is and just forget about this "continuous" option.
[ "sql-server", "merge", "replication" ]
9
9
3,172
1
0
2008-09-03T07:19:29.513000
2008-09-17T09:25:28.563000
41,279
41,342
Can Mac OS X's Spotlight be configured to ignore certain file types?
I've got bunches of auxiliary files that are generated by code and LaTeX documents that I dearly wish would not be suggested by SpotLight as potential search candidates. I'm not looking for example.log, I'm looking for example.tex! So can Spotlight be configured to ignore, say, all.log files? (I know, I know; I should just use QuickSilver instead…) @ diciu That's an interesting answer. The problem in my case is this: Figure out which importer handles your type of file I'm not sure if my type of file is handled by any single importer? Since they've all got weird extensions (.aux,.glo,.out, whatever) I think it's improbable that there's an importer that's trying to index them. But because they're plain text they're being picked up as generic files. (Admittedly, I don't know much about Spotlight's indexing, so I might be completely wrong on this.) @ diciu again: TextImporterDontImportList sounds very promising; I'll head off and see if anything comes of it. Like you say, it does seem like the whole UTI system doesn't really allow not searching for something. @ Raynet Making the files invisible is a good idea actually, albeit relatively tedious for me to set up in the general sense. If worst comes to worst, I might give that a shot (but probably after exhausting other options such as QuickSilver). (Oh, and SetFile requires the Developer Tools, but I'm guessing everyone here has them installed anyway:) )
@Will - these things that define types are called uniform type identifiers. The problem is they are a combination of extensions (like.txt) and generic types (i.e. public.plain-text matches a txt file without the txt extension based purely on content) so it's not as simple as looking for an extension. RichText.mdimporter is probably the importer that imports your text file. This should be easily verified by running mdimport in debug mode on one of the files you don't want indexed: cristi:~ diciu$ echo "All work and no play makes Jack a dull boy" > ~/input.txt cristi:~ diciu$ mdimport -d 4 -n ~/input.txt 2>&1 | grep Imported kMD2008-09-03 12:05:06.342 mdimport[1230:10b] Imported '/Users/diciu/input.txt' of type 'public.plain-text' with plugIn /System/Library/Spotlight/RichText.mdimporter. The type that matches in my example is public.plain-text. I've no idea how you actually write an extension-based exception for an UTI (like public.plain-text except anything ending in.log). Later edit: I've also looked though the RichText mdimporter binary and found a promising string but I can't figure out if it's actually being used (as a preference name or whatever): cristi:FoodBrowser diciu$ strings /System/Library/Spotlight/RichText.mdimporter/Contents/MacOS/RichText |grep Text TextImporterDontImportList
Can Mac OS X's Spotlight be configured to ignore certain file types? I've got bunches of auxiliary files that are generated by code and LaTeX documents that I dearly wish would not be suggested by SpotLight as potential search candidates. I'm not looking for example.log, I'm looking for example.tex! So can Spotlight be configured to ignore, say, all.log files? (I know, I know; I should just use QuickSilver instead…) @ diciu That's an interesting answer. The problem in my case is this: Figure out which importer handles your type of file I'm not sure if my type of file is handled by any single importer? Since they've all got weird extensions (.aux,.glo,.out, whatever) I think it's improbable that there's an importer that's trying to index them. But because they're plain text they're being picked up as generic files. (Admittedly, I don't know much about Spotlight's indexing, so I might be completely wrong on this.) @ diciu again: TextImporterDontImportList sounds very promising; I'll head off and see if anything comes of it. Like you say, it does seem like the whole UTI system doesn't really allow not searching for something. @ Raynet Making the files invisible is a good idea actually, albeit relatively tedious for me to set up in the general sense. If worst comes to worst, I might give that a shot (but probably after exhausting other options such as QuickSilver). (Oh, and SetFile requires the Developer Tools, but I'm guessing everyone here has them installed anyway:) )
TITLE: Can Mac OS X's Spotlight be configured to ignore certain file types? QUESTION: I've got bunches of auxiliary files that are generated by code and LaTeX documents that I dearly wish would not be suggested by SpotLight as potential search candidates. I'm not looking for example.log, I'm looking for example.tex! So can Spotlight be configured to ignore, say, all.log files? (I know, I know; I should just use QuickSilver instead…) @ diciu That's an interesting answer. The problem in my case is this: Figure out which importer handles your type of file I'm not sure if my type of file is handled by any single importer? Since they've all got weird extensions (.aux,.glo,.out, whatever) I think it's improbable that there's an importer that's trying to index them. But because they're plain text they're being picked up as generic files. (Admittedly, I don't know much about Spotlight's indexing, so I might be completely wrong on this.) @ diciu again: TextImporterDontImportList sounds very promising; I'll head off and see if anything comes of it. Like you say, it does seem like the whole UTI system doesn't really allow not searching for something. @ Raynet Making the files invisible is a good idea actually, albeit relatively tedious for me to set up in the general sense. If worst comes to worst, I might give that a shot (but probably after exhausting other options such as QuickSilver). (Oh, and SetFile requires the Developer Tools, but I'm guessing everyone here has them installed anyway:) ) ANSWER: @Will - these things that define types are called uniform type identifiers. The problem is they are a combination of extensions (like.txt) and generic types (i.e. public.plain-text matches a txt file without the txt extension based purely on content) so it's not as simple as looking for an extension. RichText.mdimporter is probably the importer that imports your text file. This should be easily verified by running mdimport in debug mode on one of the files you don't want indexed: cristi:~ diciu$ echo "All work and no play makes Jack a dull boy" > ~/input.txt cristi:~ diciu$ mdimport -d 4 -n ~/input.txt 2>&1 | grep Imported kMD2008-09-03 12:05:06.342 mdimport[1230:10b] Imported '/Users/diciu/input.txt' of type 'public.plain-text' with plugIn /System/Library/Spotlight/RichText.mdimporter. The type that matches in my example is public.plain-text. I've no idea how you actually write an extension-based exception for an UTI (like public.plain-text except anything ending in.log). Later edit: I've also looked though the RichText mdimporter binary and found a promising string but I can't figure out if it's actually being used (as a preference name or whatever): cristi:FoodBrowser diciu$ strings /System/Library/Spotlight/RichText.mdimporter/Contents/MacOS/RichText |grep Text TextImporterDontImportList
[ "macos", "spotlight" ]
6
3
4,339
4
0
2008-09-03T07:27:16.843000
2008-09-03T09:06:45.310000
41,290
41,559
File Access Strategy in a Multi-Threaded Environment (Web App)
I have a file which is an XML representation of some data that is taken from a Web service and cached locally within a Web Application. The idea being is that this data is very static, but just might change. So I have set it up to cache to a file, and stuck a monitor against it to check if it has been deleted. Once deleted, the file will be refreshed from its source and rebuilt. I am now running in to problems though, because obviously in a multi-threaded environment it falls over as it is trying to access the data when it is still reading/writing the file. This is confusing me, because I added a object to lock against, and this is always locked during read/write. It was my understanding that attempted access from other threads would be told to "wait" until the lock was released? Just to let you know, I am real new to multi-threaded development, so I am totally willing to accept this is a screw up on my part:) Am I missing something? What is the best file access strategy in a multi-threaded environment? Edit Sorry - I should have said this is using ASP.NET 2.0:)
Here is the code that I use to make sure a file is not locked by another process. It's not 100% foolproof, but it gets the job done most of the time: /// /// Blocks until the file is not locked any more. /// /// bool WaitForFile(string fullPath) { int numTries = 0; while (true) { ++numTries; try { // Attempt to open the file exclusively. using (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 100)) { fs.ReadByte(); // If we got this far the file is ready break; } } catch (Exception ex) { Log.LogWarning( "WaitForFile {0} failed to get an exclusive lock: {1}", fullPath, ex.ToString()); if (numTries > 10) { Log.LogWarning( "WaitForFile {0} giving up after 10 tries", fullPath); return false; } // Wait for the lock to be released System.Threading.Thread.Sleep(500); } } Log.LogTrace("WaitForFile {0} returning true after {1} tries", fullPath, numTries); return true; } Obviously you can tweak the timeouts and retries to suit your application. I use this to process huge FTP files that take a while to be written.
File Access Strategy in a Multi-Threaded Environment (Web App) I have a file which is an XML representation of some data that is taken from a Web service and cached locally within a Web Application. The idea being is that this data is very static, but just might change. So I have set it up to cache to a file, and stuck a monitor against it to check if it has been deleted. Once deleted, the file will be refreshed from its source and rebuilt. I am now running in to problems though, because obviously in a multi-threaded environment it falls over as it is trying to access the data when it is still reading/writing the file. This is confusing me, because I added a object to lock against, and this is always locked during read/write. It was my understanding that attempted access from other threads would be told to "wait" until the lock was released? Just to let you know, I am real new to multi-threaded development, so I am totally willing to accept this is a screw up on my part:) Am I missing something? What is the best file access strategy in a multi-threaded environment? Edit Sorry - I should have said this is using ASP.NET 2.0:)
TITLE: File Access Strategy in a Multi-Threaded Environment (Web App) QUESTION: I have a file which is an XML representation of some data that is taken from a Web service and cached locally within a Web Application. The idea being is that this data is very static, but just might change. So I have set it up to cache to a file, and stuck a monitor against it to check if it has been deleted. Once deleted, the file will be refreshed from its source and rebuilt. I am now running in to problems though, because obviously in a multi-threaded environment it falls over as it is trying to access the data when it is still reading/writing the file. This is confusing me, because I added a object to lock against, and this is always locked during read/write. It was my understanding that attempted access from other threads would be told to "wait" until the lock was released? Just to let you know, I am real new to multi-threaded development, so I am totally willing to accept this is a screw up on my part:) Am I missing something? What is the best file access strategy in a multi-threaded environment? Edit Sorry - I should have said this is using ASP.NET 2.0:) ANSWER: Here is the code that I use to make sure a file is not locked by another process. It's not 100% foolproof, but it gets the job done most of the time: /// /// Blocks until the file is not locked any more. /// /// bool WaitForFile(string fullPath) { int numTries = 0; while (true) { ++numTries; try { // Attempt to open the file exclusively. using (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 100)) { fs.ReadByte(); // If we got this far the file is ready break; } } catch (Exception ex) { Log.LogWarning( "WaitForFile {0} failed to get an exclusive lock: {1}", fullPath, ex.ToString()); if (numTries > 10) { Log.LogWarning( "WaitForFile {0} giving up after 10 tries", fullPath); return false; } // Wait for the lock to be released System.Threading.Thread.Sleep(500); } } Log.LogTrace("WaitForFile {0} returning true after {1} tries", fullPath, numTries); return true; } Obviously you can tweak the timeouts and retries to suit your application. I use this to process huge FTP files that take a while to be written.
[ "asp.net", "multithreading", "web-applications", "caching", "file-io" ]
6
7
5,373
5
0
2008-09-03T07:44:40.763000
2008-09-03T12:33:29.370000
41,300
41,370
Emacs in Windows
How do you run Emacs in Windows? What is the best flavor of Emacs to use in Windows, and where can I download it? And where is the.emacs file located?
I use EmacsW32, it works great. EDIT: I now use regular GNU Emacs 24, see below. See its EmacsWiki page for details. To me, the biggest advantage is that: it has a version of emacsclient that starts the Emacs server if no server is running (open all your files in the same Emacs window) it includes several useful packages such as Nxml it has a Windows installer or you can build it from sources And concerning XEmacs, according to this post by Steve Yegge: To summarize, I've argued that XEmacs has a much lower market share, poorer performance, more bugs, much lower stability, and at this point probably fewer features than GNU Emacs. When you add it all up, it's the weaker candidate by a large margin. EDIT: I now use regular GNU Emacs 24. It also contains Nxml, can be installed or built from sources, and with this wrapper, the Emacs server starts if no server is running. Cheers!
Emacs in Windows How do you run Emacs in Windows? What is the best flavor of Emacs to use in Windows, and where can I download it? And where is the.emacs file located?
TITLE: Emacs in Windows QUESTION: How do you run Emacs in Windows? What is the best flavor of Emacs to use in Windows, and where can I download it? And where is the.emacs file located? ANSWER: I use EmacsW32, it works great. EDIT: I now use regular GNU Emacs 24, see below. See its EmacsWiki page for details. To me, the biggest advantage is that: it has a version of emacsclient that starts the Emacs server if no server is running (open all your files in the same Emacs window) it includes several useful packages such as Nxml it has a Windows installer or you can build it from sources And concerning XEmacs, according to this post by Steve Yegge: To summarize, I've argued that XEmacs has a much lower market share, poorer performance, more bugs, much lower stability, and at this point probably fewer features than GNU Emacs. When you add it all up, it's the weaker candidate by a large margin. EDIT: I now use regular GNU Emacs 24. It also contains Nxml, can be installed or built from sources, and with this wrapper, the Emacs server starts if no server is running. Cheers!
[ "windows", "emacs" ]
96
58
65,666
20
0
2008-09-03T08:04:11.700000
2008-09-03T09:34:10.237000
41,304
662,946
Find item in WPF ComboBox
I know in ASP.NET I can get an item from a DropDownList by using DropDownList1.Items.FindByText Is there a similar method I can use in WPF for a ComboBox? Here's the scenario. I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values. In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record. Here's the scenario. I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values. In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record. Does this make sense?
Can you use ItemContainerGenerator? ItemContainerGenerator contains a ContainerFromItem method that takes an object parameter. If you have a reference to the full object that your comboBox contains (or a way to reconstruct it), you can use the following: ComboBoxItem item = (ComboBoxItem)myComboBox.ItemContainerGenerator.ContainerFromItem(myObject);
Find item in WPF ComboBox I know in ASP.NET I can get an item from a DropDownList by using DropDownList1.Items.FindByText Is there a similar method I can use in WPF for a ComboBox? Here's the scenario. I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values. In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record. Here's the scenario. I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values. In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record. Does this make sense?
TITLE: Find item in WPF ComboBox QUESTION: I know in ASP.NET I can get an item from a DropDownList by using DropDownList1.Items.FindByText Is there a similar method I can use in WPF for a ComboBox? Here's the scenario. I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values. In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record. Here's the scenario. I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values. In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record. Does this make sense? ANSWER: Can you use ItemContainerGenerator? ItemContainerGenerator contains a ContainerFromItem method that takes an object parameter. If you have a reference to the full object that your comboBox contains (or a way to reconstruct it), you can use the following: ComboBoxItem item = (ComboBoxItem)myComboBox.ItemContainerGenerator.ContainerFromItem(myObject);
[ ".net", "wpf", "search", "user-controls" ]
6
11
33,634
5
0
2008-09-03T08:06:08.497000
2009-03-19T16:28:33.633000
41,319
41,324
Checking if a list is empty with LINQ
What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type IEnumerable and doesn't have a Count property. Right now I'm tossing up between this: if (myList.Count() == 0) {... } and this: if (!myList.Any()) {... } My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count. That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list? Edit @lassevk's response seems to be the most logical, coupled with a bit of runtime checking to use a cached count if possible, like this: public static bool IsEmpty (this IEnumerable list) { if (list is ICollection ) return ((ICollection )list).Count == 0; return!list.Any(); }
You could do this: public static Boolean IsEmpty (this IEnumerable source) { if (source == null) return true; // or throw an exception return!source.Any(); } Edit: Note that simply using the.Count method will be fast if the underlying source actually has a fast Count property. A valid optimization above would be to detect a few base types and simply use the.Count property of those, instead of the.Any() approach, but then fall back to.Any() if no guarantee can be made.
Checking if a list is empty with LINQ What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type IEnumerable and doesn't have a Count property. Right now I'm tossing up between this: if (myList.Count() == 0) {... } and this: if (!myList.Any()) {... } My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count. That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list? Edit @lassevk's response seems to be the most logical, coupled with a bit of runtime checking to use a cached count if possible, like this: public static bool IsEmpty (this IEnumerable list) { if (list is ICollection ) return ((ICollection )list).Count == 0; return!list.Any(); }
TITLE: Checking if a list is empty with LINQ QUESTION: What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type IEnumerable and doesn't have a Count property. Right now I'm tossing up between this: if (myList.Count() == 0) {... } and this: if (!myList.Any()) {... } My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count. That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list? Edit @lassevk's response seems to be the most logical, coupled with a bit of runtime checking to use a cached count if possible, like this: public static bool IsEmpty (this IEnumerable list) { if (list is ICollection ) return ((ICollection )list).Count == 0; return!list.Any(); } ANSWER: You could do this: public static Boolean IsEmpty (this IEnumerable source) { if (source == null) return true; // or throw an exception return!source.Any(); } Edit: Note that simply using the.Count method will be fast if the underlying source actually has a fast Count property. A valid optimization above would be to detect a few base types and simply use the.Count property of those, instead of the.Any() approach, but then fall back to.Any() if no guarantee can be made.
[ "c#", ".net", "linq", "list" ]
130
111
162,973
16
0
2008-09-03T08:35:24.980000
2008-09-03T08:38:51.650000
41,320
41,326
Working on a Visual Studio Project with multiple users?
I just wonder what the best approach is to have multiple users work on a Project in Visual Studio 2005 Professional. We got a Solution with multiple Class Libraries, but when everyone opens the solution, we keep getting the "X was modified, Reload/Discard?" prompt all the time. Just opening one project is an obvious alternative, but I find it harder to use as you can't just see some of the other classes in other projects that way. Are there any Guidelines for Team Development with VS2005 Pro? Edit: Thanks. The current environment is a bit limited in the sense there is only 1 PC with RDP Connection, but that will change in the future. Marking the first answer as Accepted, but they are all good:)
Use source control to keep a central repository of all your code. Then each user checks out their own copy of the source code and works locally. Then submits only the code that changed. https://en.wikipedia.org/wiki/Version_control
Working on a Visual Studio Project with multiple users? I just wonder what the best approach is to have multiple users work on a Project in Visual Studio 2005 Professional. We got a Solution with multiple Class Libraries, but when everyone opens the solution, we keep getting the "X was modified, Reload/Discard?" prompt all the time. Just opening one project is an obvious alternative, but I find it harder to use as you can't just see some of the other classes in other projects that way. Are there any Guidelines for Team Development with VS2005 Pro? Edit: Thanks. The current environment is a bit limited in the sense there is only 1 PC with RDP Connection, but that will change in the future. Marking the first answer as Accepted, but they are all good:)
TITLE: Working on a Visual Studio Project with multiple users? QUESTION: I just wonder what the best approach is to have multiple users work on a Project in Visual Studio 2005 Professional. We got a Solution with multiple Class Libraries, but when everyone opens the solution, we keep getting the "X was modified, Reload/Discard?" prompt all the time. Just opening one project is an obvious alternative, but I find it harder to use as you can't just see some of the other classes in other projects that way. Are there any Guidelines for Team Development with VS2005 Pro? Edit: Thanks. The current environment is a bit limited in the sense there is only 1 PC with RDP Connection, but that will change in the future. Marking the first answer as Accepted, but they are all good:) ANSWER: Use source control to keep a central repository of all your code. Then each user checks out their own copy of the source code and works locally. Then submits only the code that changed. https://en.wikipedia.org/wiki/Version_control
[ "visual-studio" ]
4
6
14,527
5
0
2008-09-03T08:35:49.877000
2008-09-03T08:39:31.990000
41,330
41,385
How to detect the presence of a default recording device in the system?
How do I detect if the system has a default recording device installed? I bet this can be done through some calls to the Win32 API, anyone has any experience with this? I'm talking about doing this through code, not by opening the control panel and taking a look under sound options.
Using the DirectX SDK, you can call DirectSoundCaptureEnumerate, which will call your DSEnumCallback function for each DirectSoundCapture device on the system. The first parameter passed to your DSEnumCallback is an LPGUID, which is the "Address of the GUID that identifies the device being enumerated, or NULL for the primary device". If all you need to do is find out if a recording device is present (I don't think this is good enough if you really need to know the default device), you can use waveInGetNumDevs: #include #include #include "mmsystem.h" int _tmain( int argc, wchar_t *argv[] ) { UINT deviceCount = waveInGetNumDevs(); if ( deviceCount > 0 ) { for ( int i = 0; i < deviceCount; i++ ) { WAVEINCAPSW waveInCaps; waveInGetDevCapsW( i, &waveInCaps, sizeof( WAVEINCAPS ) ); // do some stuff with waveInCaps... } } return 0; }
How to detect the presence of a default recording device in the system? How do I detect if the system has a default recording device installed? I bet this can be done through some calls to the Win32 API, anyone has any experience with this? I'm talking about doing this through code, not by opening the control panel and taking a look under sound options.
TITLE: How to detect the presence of a default recording device in the system? QUESTION: How do I detect if the system has a default recording device installed? I bet this can be done through some calls to the Win32 API, anyone has any experience with this? I'm talking about doing this through code, not by opening the control panel and taking a look under sound options. ANSWER: Using the DirectX SDK, you can call DirectSoundCaptureEnumerate, which will call your DSEnumCallback function for each DirectSoundCapture device on the system. The first parameter passed to your DSEnumCallback is an LPGUID, which is the "Address of the GUID that identifies the device being enumerated, or NULL for the primary device". If all you need to do is find out if a recording device is present (I don't think this is good enough if you really need to know the default device), you can use waveInGetNumDevs: #include #include #include "mmsystem.h" int _tmain( int argc, wchar_t *argv[] ) { UINT deviceCount = waveInGetNumDevs(); if ( deviceCount > 0 ) { for ( int i = 0; i < deviceCount; i++ ) { WAVEINCAPSW waveInCaps; waveInGetDevCapsW( i, &waveInCaps, sizeof( WAVEINCAPS ) ); // do some stuff with waveInCaps... } } return 0; }
[ "winapi", "audio", "device" ]
2
1
1,013
3
0
2008-09-03T08:46:48.323000
2008-09-03T09:55:52.790000
41,355
169,485
Dynamic programming with WCF
Has anybody got any kind of experience with dynamic programming using WCF. By dynamic programming I mean runtime consumption of WSDL's. I have found one blog entry/tool: http://blogs.msdn.com/vipulmodi/archive/2006/11/16/dynamic-programming-with-wcf.aspx Has anybody here found good tools for this?
This is one of the weirder aspects of WCF. You can dynamically create a channelfactory, but only with a known type. I came up with a solution that is not perfect, but does work: Create an interface, "IFoo" which contains a single method, say Execute(). In your ESB, dynamically create a ChannelFactory for the endpoint that you want to connect to. Set the connection properties (URI, etc.). Now, you can attach services dynamically to your ESB, provided that they always implement the "IFoo" interface.
Dynamic programming with WCF Has anybody got any kind of experience with dynamic programming using WCF. By dynamic programming I mean runtime consumption of WSDL's. I have found one blog entry/tool: http://blogs.msdn.com/vipulmodi/archive/2006/11/16/dynamic-programming-with-wcf.aspx Has anybody here found good tools for this?
TITLE: Dynamic programming with WCF QUESTION: Has anybody got any kind of experience with dynamic programming using WCF. By dynamic programming I mean runtime consumption of WSDL's. I have found one blog entry/tool: http://blogs.msdn.com/vipulmodi/archive/2006/11/16/dynamic-programming-with-wcf.aspx Has anybody here found good tools for this? ANSWER: This is one of the weirder aspects of WCF. You can dynamically create a channelfactory, but only with a known type. I came up with a solution that is not perfect, but does work: Create an interface, "IFoo" which contains a single method, say Execute(). In your ESB, dynamically create a ChannelFactory for the endpoint that you want to connect to. Set the connection properties (URI, etc.). Now, you can attach services dynamically to your ESB, provided that they always implement the "IFoo" interface.
[ ".net", "wcf" ]
4
2
1,169
3
0
2008-09-03T09:24:35.500000
2008-10-04T01:13:49.130000
41,367
41,373
How can I make my applications scale well?
In general, what kinds of design decisions help an application scale well? (Note: Having just learned about Big O Notation, I'm looking to gather more principles of programming here. I've attempted to explain Big O Notation by answering my own question below, but I want the community to improve both this question and the answers.) Responses so far 1) Define scaling. Do you need to scale for lots of users, traffic, objects in a virtual environment? 2) Look at your algorithms. Will the amount of work they do scale linearly with the actual amount of work - i.e. number of items to loop through, number of users, etc? 3) Look at your hardware. Is your application designed such that you can run it on multiple machines if one can't keep up? Secondary thoughts 1) Don't optimize too much too soon - test first. Maybe bottlenecks will happen in unforseen places. 2) Maybe the need to scale will not outpace Moore's Law, and maybe upgrading hardware will be cheaper than refactoring.
The only thing I would say is write your application so that it can be deployed on a cluster from the very start. Anything above that is a premature optimisation. Your first job should be getting enough users to have a scaling problem. Build the code as simple as you can first, then profile the system second and optimise only when there is an obvious performance problem. Often the figures from profiling your code are counter-intuitive; the bottle-necks tend to reside in modules you didn't think would be slow. Data is king when it comes to optimisation. If you optimise the parts you think will be slow, you will often optimise the wrong things.
How can I make my applications scale well? In general, what kinds of design decisions help an application scale well? (Note: Having just learned about Big O Notation, I'm looking to gather more principles of programming here. I've attempted to explain Big O Notation by answering my own question below, but I want the community to improve both this question and the answers.) Responses so far 1) Define scaling. Do you need to scale for lots of users, traffic, objects in a virtual environment? 2) Look at your algorithms. Will the amount of work they do scale linearly with the actual amount of work - i.e. number of items to loop through, number of users, etc? 3) Look at your hardware. Is your application designed such that you can run it on multiple machines if one can't keep up? Secondary thoughts 1) Don't optimize too much too soon - test first. Maybe bottlenecks will happen in unforseen places. 2) Maybe the need to scale will not outpace Moore's Law, and maybe upgrading hardware will be cheaper than refactoring.
TITLE: How can I make my applications scale well? QUESTION: In general, what kinds of design decisions help an application scale well? (Note: Having just learned about Big O Notation, I'm looking to gather more principles of programming here. I've attempted to explain Big O Notation by answering my own question below, but I want the community to improve both this question and the answers.) Responses so far 1) Define scaling. Do you need to scale for lots of users, traffic, objects in a virtual environment? 2) Look at your algorithms. Will the amount of work they do scale linearly with the actual amount of work - i.e. number of items to loop through, number of users, etc? 3) Look at your hardware. Is your application designed such that you can run it on multiple machines if one can't keep up? Secondary thoughts 1) Don't optimize too much too soon - test first. Maybe bottlenecks will happen in unforseen places. 2) Maybe the need to scale will not outpace Moore's Law, and maybe upgrading hardware will be cheaper than refactoring. ANSWER: The only thing I would say is write your application so that it can be deployed on a cluster from the very start. Anything above that is a premature optimisation. Your first job should be getting enough users to have a scaling problem. Build the code as simple as you can first, then profile the system second and optimise only when there is an obvious performance problem. Often the figures from profiling your code are counter-intuitive; the bottle-necks tend to reside in modules you didn't think would be slow. Data is king when it comes to optimisation. If you optimise the parts you think will be slow, you will often optimise the wrong things.
[ "algorithm", "language-agnostic", "scalability" ]
8
11
1,170
7
0
2008-09-03T09:30:40.243000
2008-09-03T09:41:49.140000
41,397
41,408
Asking a Generic Method to Throw Specific Exception Type on FAIL
Right, I know I am totally going to look an idiot with this one, but my brain is just not kicking in to gear this morning. I want to have a method where I can say "if it goes bad, come back with this type of Exception", right? For example, something like ( and this doesn't work ): static ExType TestException (string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = new Exception(message); return ex; } Now whats confusing me is that we KNOW that the generic type is going to be of an Exception type due to the where clause. However, the code fails because we cannot implicitly cast Exception to ExType. We cannot explicitly convert it either, such as: static ExType TestException (string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = (ExType)(new Exception(message)); return ex; } As that fails too.. So is this kind of thing possible? I have a strong feeling its going to be real simple, but I am having a tough day with the old noggin, so cut me some slack:P Update Thanks for the responses guys, looks like it wasn't me being a complete idiot!;) OK, so Vegard and Sam got me on to the point where I could instantiate the correct type, but then obviously got stuck because the message param is read-only following instantiation. Matt hit the nail right on the head with his response, I have tested this and all works fine. Here is the example code: static ExType TestException (string message) where ExType:Exception, new () { ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message); return ex; } Sweet!:) Thanks guys!
You can almost do it like this: static void TestException (string message) where E: Exception, new() { var e = new E(); e.Message = message; throw e; } However, that doesn't compile because Exception.Message is read only. It can only be assigned by passing it to the constructor, and there's no way to constrain a generic type with something other than a default constructor. I think you'd have to use reflection (Activator.CreateInstance) to "new up" the custom exception type with the message parameter, like this: static void TestException (string message) where E: Exception { throw Activator.CreateInstance(typeof(E), message) as E; } Edit Oops just realised you're wanting to return the exception, not throw it. The same principle applies, so I'll leave my answer as-is with the throw statements.
Asking a Generic Method to Throw Specific Exception Type on FAIL Right, I know I am totally going to look an idiot with this one, but my brain is just not kicking in to gear this morning. I want to have a method where I can say "if it goes bad, come back with this type of Exception", right? For example, something like ( and this doesn't work ): static ExType TestException (string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = new Exception(message); return ex; } Now whats confusing me is that we KNOW that the generic type is going to be of an Exception type due to the where clause. However, the code fails because we cannot implicitly cast Exception to ExType. We cannot explicitly convert it either, such as: static ExType TestException (string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = (ExType)(new Exception(message)); return ex; } As that fails too.. So is this kind of thing possible? I have a strong feeling its going to be real simple, but I am having a tough day with the old noggin, so cut me some slack:P Update Thanks for the responses guys, looks like it wasn't me being a complete idiot!;) OK, so Vegard and Sam got me on to the point where I could instantiate the correct type, but then obviously got stuck because the message param is read-only following instantiation. Matt hit the nail right on the head with his response, I have tested this and all works fine. Here is the example code: static ExType TestException (string message) where ExType:Exception, new () { ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message); return ex; } Sweet!:) Thanks guys!
TITLE: Asking a Generic Method to Throw Specific Exception Type on FAIL QUESTION: Right, I know I am totally going to look an idiot with this one, but my brain is just not kicking in to gear this morning. I want to have a method where I can say "if it goes bad, come back with this type of Exception", right? For example, something like ( and this doesn't work ): static ExType TestException (string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = new Exception(message); return ex; } Now whats confusing me is that we KNOW that the generic type is going to be of an Exception type due to the where clause. However, the code fails because we cannot implicitly cast Exception to ExType. We cannot explicitly convert it either, such as: static ExType TestException (string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = (ExType)(new Exception(message)); return ex; } As that fails too.. So is this kind of thing possible? I have a strong feeling its going to be real simple, but I am having a tough day with the old noggin, so cut me some slack:P Update Thanks for the responses guys, looks like it wasn't me being a complete idiot!;) OK, so Vegard and Sam got me on to the point where I could instantiate the correct type, but then obviously got stuck because the message param is read-only following instantiation. Matt hit the nail right on the head with his response, I have tested this and all works fine. Here is the example code: static ExType TestException (string message) where ExType:Exception, new () { ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message); return ex; } Sweet!:) Thanks guys! ANSWER: You can almost do it like this: static void TestException (string message) where E: Exception, new() { var e = new E(); e.Message = message; throw e; } However, that doesn't compile because Exception.Message is read only. It can only be assigned by passing it to the constructor, and there's no way to constrain a generic type with something other than a default constructor. I think you'd have to use reflection (Activator.CreateInstance) to "new up" the custom exception type with the message parameter, like this: static void TestException (string message) where E: Exception { throw Activator.CreateInstance(typeof(E), message) as E; } Edit Oops just realised you're wanting to return the exception, not throw it. The same principle applies, so I'll leave my answer as-is with the throw statements.
[ "c#", "generics", "exception" ]
12
25
8,116
5
0
2008-09-03T10:08:11.527000
2008-09-03T10:15:34.863000
41,400
41,794
How can I wrap a function with variable length arguments?
I am looking to do this in C/C++. I came across Variable Length Arguments, but this suggests a solution with Python and C using libffi. Now, if I want to wrap the printf function with myprintf. I do it like below: void myprintf(char* fmt,...) { va_list args; va_start(args, fmt); printf(fmt, args); va_end(args); } int _tmain(int argc, _TCHAR* argv[]) { int a = 9; int b = 10; char v = 'C'; myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b); return 0; } But the results are not as expected! This is a number: 1244780 and this is a character: h and another number: 29953463 What did I miss?
The problem is that you cannot use 'printf' with va_args. You must use vprintf if you are using variable argument lists. vprint, vsprintf, vfprintf, etc. (there are also 'safe' versions in Microsoft's C runtime that will prevent buffer overruns, etc.) You sample works as follows: void myprintf(char* fmt,...) { va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); } int _tmain(int argc, _TCHAR* argv[]) { int a = 9; int b = 10; char v = 'C'; myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b); return 0; }
How can I wrap a function with variable length arguments? I am looking to do this in C/C++. I came across Variable Length Arguments, but this suggests a solution with Python and C using libffi. Now, if I want to wrap the printf function with myprintf. I do it like below: void myprintf(char* fmt,...) { va_list args; va_start(args, fmt); printf(fmt, args); va_end(args); } int _tmain(int argc, _TCHAR* argv[]) { int a = 9; int b = 10; char v = 'C'; myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b); return 0; } But the results are not as expected! This is a number: 1244780 and this is a character: h and another number: 29953463 What did I miss?
TITLE: How can I wrap a function with variable length arguments? QUESTION: I am looking to do this in C/C++. I came across Variable Length Arguments, but this suggests a solution with Python and C using libffi. Now, if I want to wrap the printf function with myprintf. I do it like below: void myprintf(char* fmt,...) { va_list args; va_start(args, fmt); printf(fmt, args); va_end(args); } int _tmain(int argc, _TCHAR* argv[]) { int a = 9; int b = 10; char v = 'C'; myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b); return 0; } But the results are not as expected! This is a number: 1244780 and this is a character: h and another number: 29953463 What did I miss? ANSWER: The problem is that you cannot use 'printf' with va_args. You must use vprintf if you are using variable argument lists. vprint, vsprintf, vfprintf, etc. (there are also 'safe' versions in Microsoft's C runtime that will prevent buffer overruns, etc.) You sample works as follows: void myprintf(char* fmt,...) { va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); } int _tmain(int argc, _TCHAR* argv[]) { int a = 9; int b = 10; char v = 'C'; myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b); return 0; }
[ "c++", "c", "variadic-functions" ]
52
69
33,134
8
0
2008-09-03T10:12:27.743000
2008-09-03T14:30:29.167000
41,405
41,418
Working with Common/Utility Libraries
At the company I work for we have a "Utility" project that is referenced by pretty much ever application we build. It's got lots of things like NullHelpers, ConfigSettingHelpers, Common ExtensionMethods etc. The way we work is that when we want to make a new project, we get the latest version of the project from source control add it to the solution and then reference the project from any new projects that get added to the solution. This has worked ok, however there have been a couple of instances where people have made "breaking changes" to the common project, which works for them, but doesn't work for others. I've been thinking that rather than adding the common library as a project reference perhaps we should start developing the common library as a standalone dll and publish different versions and target a particular version for a particular project so that changes can be made without any risk to other projects using the common library. Having said all that I'm interested to see how others reference or use their common libraries.
That's exactly what we're doing. We have a Utility project which has some non project specific useful functions. We increase the version manually (minor), build the project in Release version, sign it and put it to a shared location. People then use the specific version of the library. If some useful methods are implemented in some specific projects which could find their way into main Utility project, we put the to a special helper class in the project, and mark them as a possible Utility candidate (simple //TODO). At the end of the project, we review the candidates and if they stick, we move them to the main library. Breaking changes are a no-no and we mark methods and classes as [Obsolete] if needed. But, it doesn't really matter because we increase the version on every publish. Hope this helps.
Working with Common/Utility Libraries At the company I work for we have a "Utility" project that is referenced by pretty much ever application we build. It's got lots of things like NullHelpers, ConfigSettingHelpers, Common ExtensionMethods etc. The way we work is that when we want to make a new project, we get the latest version of the project from source control add it to the solution and then reference the project from any new projects that get added to the solution. This has worked ok, however there have been a couple of instances where people have made "breaking changes" to the common project, which works for them, but doesn't work for others. I've been thinking that rather than adding the common library as a project reference perhaps we should start developing the common library as a standalone dll and publish different versions and target a particular version for a particular project so that changes can be made without any risk to other projects using the common library. Having said all that I'm interested to see how others reference or use their common libraries.
TITLE: Working with Common/Utility Libraries QUESTION: At the company I work for we have a "Utility" project that is referenced by pretty much ever application we build. It's got lots of things like NullHelpers, ConfigSettingHelpers, Common ExtensionMethods etc. The way we work is that when we want to make a new project, we get the latest version of the project from source control add it to the solution and then reference the project from any new projects that get added to the solution. This has worked ok, however there have been a couple of instances where people have made "breaking changes" to the common project, which works for them, but doesn't work for others. I've been thinking that rather than adding the common library as a project reference perhaps we should start developing the common library as a standalone dll and publish different versions and target a particular version for a particular project so that changes can be made without any risk to other projects using the common library. Having said all that I'm interested to see how others reference or use their common libraries. ANSWER: That's exactly what we're doing. We have a Utility project which has some non project specific useful functions. We increase the version manually (minor), build the project in Release version, sign it and put it to a shared location. People then use the specific version of the library. If some useful methods are implemented in some specific projects which could find their way into main Utility project, we put the to a special helper class in the project, and mark them as a possible Utility candidate (simple //TODO). At the end of the project, we review the candidates and if they stick, we move them to the main library. Breaking changes are a no-no and we mark methods and classes as [Obsolete] if needed. But, it doesn't really matter because we increase the version on every publish. Hope this helps.
[ "c#", "visual-studio", "api" ]
3
5
4,122
3
0
2008-09-03T10:13:30.203000
2008-09-03T10:23:51.660000
41,406
41,411
How do I execute PHP that is stored in a MySQL database?
I'm trying to write a page that calls PHP that's stored in a MySQL database. The page that is stored in the MySQL database contains PHP (and HTML) code which I want to run on page load. How could I go about doing this?
You can use the eval command for this. I would recommend against this though, because there's a lot of pitfalls using this approach. Debugging is hard(er), it implies some security risks (bad content in the DB gets executed, uh oh). See When is eval evil in php? for instance. Google for Eval is Evil, and you'll find a lot of examples why you should find another solution. Addition: Another good article with some references to exploits is this blogpost. Refers to past vBulletin and phpMyAdmin exploits which were caused by improper Eval usage.
How do I execute PHP that is stored in a MySQL database? I'm trying to write a page that calls PHP that's stored in a MySQL database. The page that is stored in the MySQL database contains PHP (and HTML) code which I want to run on page load. How could I go about doing this?
TITLE: How do I execute PHP that is stored in a MySQL database? QUESTION: I'm trying to write a page that calls PHP that's stored in a MySQL database. The page that is stored in the MySQL database contains PHP (and HTML) code which I want to run on page load. How could I go about doing this? ANSWER: You can use the eval command for this. I would recommend against this though, because there's a lot of pitfalls using this approach. Debugging is hard(er), it implies some security risks (bad content in the DB gets executed, uh oh). See When is eval evil in php? for instance. Google for Eval is Evil, and you'll find a lot of examples why you should find another solution. Addition: Another good article with some references to exploits is this blogpost. Refers to past vBulletin and phpMyAdmin exploits which were caused by improper Eval usage.
[ "php", "mysql" ]
34
33
41,518
7
0
2008-09-03T10:14:26.067000
2008-09-03T10:18:01.660000
41,407
41,428
Parsing a log file with regular expressions
I'm currently working on a parser for our internal log files (generated by log4php, log4net and log4j). So far I have a nice regular expression to parse the logs, except for one annoying bit: Some log messages span multiple lines, which I can't get to match properly. The regex I have now is this: (? \d{2}/\d{2}/\d{2})\s(? \d{2}):\d{2}:\d{2}),\d{3})\s(?.+) The log format (which I use for testing the parser) is this: 07/23/08 14:17:31,321 log message spanning multiple lines 07/23/08 14:17:31,321 log message on one line When I run the parser right now, I get only the line the log starts on. If I change it to span multiple lines, I get only one result (the whole log file). @samjudson: You need to pass the RegexOptions.Singleline flag in to the regular expression, so that "." matches all characters, not just all characters except new lines (which is the default). I tried that, but then it matches the whole file. I also tried to set the message-group to.+? (non-greedy), but then it matches a single character (which isn't what I'm looking for either). The problem is that the pattern for the message matches on the date-group as well, so when it doesn't break on a new-line it just goes on and on and on. I use this regex for the message group now. It works, unless there's a pattern IN the log message which is the same as the start of the log message. (? (.(?!\d{2}/\d{2}/\d{2}\s\d{2}:\d{2}:\d{2},\d{3}\s\[\d{4}\]))+)
This will only work if the log message doesn't contain a date at the beginning of the line, but you could try adding a negative look-ahead assertion for a date in the "message" group: (? \d{2}/\d{2}/\d{2})\s(? \d{2}:\d{2}:\d{2},\d{3})\s(? (.(?!^\d{2}/\d{2}/ \d{2}))+) Note that this requires the use of the RegexOptions.MultiLine flag.
Parsing a log file with regular expressions I'm currently working on a parser for our internal log files (generated by log4php, log4net and log4j). So far I have a nice regular expression to parse the logs, except for one annoying bit: Some log messages span multiple lines, which I can't get to match properly. The regex I have now is this: (? \d{2}/\d{2}/\d{2})\s(? \d{2}):\d{2}:\d{2}),\d{3})\s(?.+) The log format (which I use for testing the parser) is this: 07/23/08 14:17:31,321 log message spanning multiple lines 07/23/08 14:17:31,321 log message on one line When I run the parser right now, I get only the line the log starts on. If I change it to span multiple lines, I get only one result (the whole log file). @samjudson: You need to pass the RegexOptions.Singleline flag in to the regular expression, so that "." matches all characters, not just all characters except new lines (which is the default). I tried that, but then it matches the whole file. I also tried to set the message-group to.+? (non-greedy), but then it matches a single character (which isn't what I'm looking for either). The problem is that the pattern for the message matches on the date-group as well, so when it doesn't break on a new-line it just goes on and on and on. I use this regex for the message group now. It works, unless there's a pattern IN the log message which is the same as the start of the log message. (? (.(?!\d{2}/\d{2}/\d{2}\s\d{2}:\d{2}:\d{2},\d{3}\s\[\d{4}\]))+)
TITLE: Parsing a log file with regular expressions QUESTION: I'm currently working on a parser for our internal log files (generated by log4php, log4net and log4j). So far I have a nice regular expression to parse the logs, except for one annoying bit: Some log messages span multiple lines, which I can't get to match properly. The regex I have now is this: (? \d{2}/\d{2}/\d{2})\s(? \d{2}):\d{2}:\d{2}),\d{3})\s(?.+) The log format (which I use for testing the parser) is this: 07/23/08 14:17:31,321 log message spanning multiple lines 07/23/08 14:17:31,321 log message on one line When I run the parser right now, I get only the line the log starts on. If I change it to span multiple lines, I get only one result (the whole log file). @samjudson: You need to pass the RegexOptions.Singleline flag in to the regular expression, so that "." matches all characters, not just all characters except new lines (which is the default). I tried that, but then it matches the whole file. I also tried to set the message-group to.+? (non-greedy), but then it matches a single character (which isn't what I'm looking for either). The problem is that the pattern for the message matches on the date-group as well, so when it doesn't break on a new-line it just goes on and on and on. I use this regex for the message group now. It works, unless there's a pattern IN the log message which is the same as the start of the log message. (? (.(?!\d{2}/\d{2}/\d{2}\s\d{2}:\d{2}:\d{2},\d{3}\s\[\d{4}\]))+) ANSWER: This will only work if the log message doesn't contain a date at the beginning of the line, but you could try adding a negative look-ahead assertion for a date in the "message" group: (? \d{2}/\d{2}/\d{2})\s(? \d{2}:\d{2}:\d{2},\d{3})\s(? (.(?!^\d{2}/\d{2}/ \d{2}))+) Note that this requires the use of the RegexOptions.MultiLine flag.
[ "c#", "regex" ]
2
3
5,731
5
0
2008-09-03T10:15:11.247000
2008-09-03T10:37:36.340000
41,419
41,462
Where do search engines start crawling?
What do search engine bots use as a starting point? Is it DNS look-up or do they start with some fixed list of well-know sites? Any guesses or suggestions?
Your question can be interpreted in two ways: Are you asking where search engines start their crawl from in general, or where they start to crawl a particular site? I don't know how the big players work; but if you were to make your own search engine you'd probably seed it with popular portal sites. DMOZ.org seems to be a popular starting point. Since the big players have so much more data than we do they probably start their crawls from a variety of places. If you're asking where a SE starts to crawl your particular site, it probably has a lot to do with which of your pages are the most popular. I imagine that if you have one super popular page that lots of other sites link to, then that would be the page that SEs starts will enter from because there are so many more entry points from other sites. Note that I am not in SEO or anything; I just studied bot and SE traffic for a while for a project I was working on.
Where do search engines start crawling? What do search engine bots use as a starting point? Is it DNS look-up or do they start with some fixed list of well-know sites? Any guesses or suggestions?
TITLE: Where do search engines start crawling? QUESTION: What do search engine bots use as a starting point? Is it DNS look-up or do they start with some fixed list of well-know sites? Any guesses or suggestions? ANSWER: Your question can be interpreted in two ways: Are you asking where search engines start their crawl from in general, or where they start to crawl a particular site? I don't know how the big players work; but if you were to make your own search engine you'd probably seed it with popular portal sites. DMOZ.org seems to be a popular starting point. Since the big players have so much more data than we do they probably start their crawls from a variety of places. If you're asking where a SE starts to crawl your particular site, it probably has a lot to do with which of your pages are the most popular. I imagine that if you have one super popular page that lots of other sites link to, then that would be the page that SEs starts will enter from because there are so many more entry points from other sites. Note that I am not in SEO or anything; I just studied bot and SE traffic for a while for a project I was working on.
[ "search-engine" ]
12
8
2,872
3
0
2008-09-03T10:30:52.753000
2008-09-03T11:07:26.487000
41,424
41,448
How do you implement a "Did you mean"?
Possible Duplicate: How does the Google “Did you mean?” Algorithm work? Suppose you have a search system already in your website. How can you implement the "Did you mean: " like Google does in some search queries?
Actually what Google does is very much non-trivial and also at first counter-intuitive. They don't do anything like check against a dictionary, but rather they make use of statistics to identify "similar" queries that returned more results than your query, the exact algorithm is of course not known. There are different sub-problems to solve here, as a fundamental basis for all Natural Language Processing statistics related there is one must have book: Foundation of Statistical Natural Language Processing. Concretely to solve the problem of word/query similarity I have had good results with using Edit Distance, a mathematical measure of string similarity that works surprisingly well. I used to use Levenshtein but the others may be worth looking into. Soundex - in my experience - is crap. Actually efficiently storing and searching a large dictionary of misspelled words and having sub second retrieval is again non-trivial, your best bet is to make use of existing full text indexing and retrieval engines (i.e. not your database's one), of which Lucene is currently one of the best and coincidentally ported to many many platforms.
How do you implement a "Did you mean"? Possible Duplicate: How does the Google “Did you mean?” Algorithm work? Suppose you have a search system already in your website. How can you implement the "Did you mean: " like Google does in some search queries?
TITLE: How do you implement a "Did you mean"? QUESTION: Possible Duplicate: How does the Google “Did you mean?” Algorithm work? Suppose you have a search system already in your website. How can you implement the "Did you mean: " like Google does in some search queries? ANSWER: Actually what Google does is very much non-trivial and also at first counter-intuitive. They don't do anything like check against a dictionary, but rather they make use of statistics to identify "similar" queries that returned more results than your query, the exact algorithm is of course not known. There are different sub-problems to solve here, as a fundamental basis for all Natural Language Processing statistics related there is one must have book: Foundation of Statistical Natural Language Processing. Concretely to solve the problem of word/query similarity I have had good results with using Edit Distance, a mathematical measure of string similarity that works surprisingly well. I used to use Levenshtein but the others may be worth looking into. Soundex - in my experience - is crap. Actually efficiently storing and searching a large dictionary of misspelled words and having sub second retrieval is again non-trivial, your best bet is to make use of existing full text indexing and retrieval engines (i.e. not your database's one), of which Lucene is currently one of the best and coincidentally ported to many many platforms.
[ "nlp" ]
118
87
32,128
17
0
2008-09-03T10:36:13.270000
2008-09-03T10:55:12.740000
41,429
41,442
Setting viewstate on postback
I am trying to set a ViewState-variable when a button is pressed, but it only works the second time I click the button. Here is the code-behind: protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString()); } } private string YourName { get { return (string)ViewState["YourName"]; } set { ViewState["YourName"] = value; } } protected void btnSubmit_Click(object sender, EventArgs e) { YourName = txtName.Text; } Is there something I am missing? Here is the form-part of the design-file, very basic just as a POC: Enter your name: PS: The sample is very simplified, "use txtName.Text instead of ViewState" is not the correct answer, I need the info to be in ViewState.
Page_Load fires before btnSubmit_Click. If you want to do something after your postback events have fired use Page_PreRender. //this will work because YourName has now been set by the click event protected void Page_PreRender(object sender, EventArgs e) { if (Page.IsPostBack) lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString()); } The basic order goes: Page init fires (init cannot access ViewState) ViewState is read Page load fires Any events fire PreRender fires Page renders
Setting viewstate on postback I am trying to set a ViewState-variable when a button is pressed, but it only works the second time I click the button. Here is the code-behind: protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString()); } } private string YourName { get { return (string)ViewState["YourName"]; } set { ViewState["YourName"] = value; } } protected void btnSubmit_Click(object sender, EventArgs e) { YourName = txtName.Text; } Is there something I am missing? Here is the form-part of the design-file, very basic just as a POC: Enter your name: PS: The sample is very simplified, "use txtName.Text instead of ViewState" is not the correct answer, I need the info to be in ViewState.
TITLE: Setting viewstate on postback QUESTION: I am trying to set a ViewState-variable when a button is pressed, but it only works the second time I click the button. Here is the code-behind: protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString()); } } private string YourName { get { return (string)ViewState["YourName"]; } set { ViewState["YourName"] = value; } } protected void btnSubmit_Click(object sender, EventArgs e) { YourName = txtName.Text; } Is there something I am missing? Here is the form-part of the design-file, very basic just as a POC: Enter your name: PS: The sample is very simplified, "use txtName.Text instead of ViewState" is not the correct answer, I need the info to be in ViewState. ANSWER: Page_Load fires before btnSubmit_Click. If you want to do something after your postback events have fired use Page_PreRender. //this will work because YourName has now been set by the click event protected void Page_PreRender(object sender, EventArgs e) { if (Page.IsPostBack) lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString()); } The basic order goes: Page init fires (init cannot access ViewState) ViewState is read Page load fires Any events fire PreRender fires Page renders
[ "asp.net", "postback", "viewstate" ]
5
12
4,512
1
0
2008-09-03T10:37:43.080000
2008-09-03T10:48:15.817000
41,446
42,491
Generating JavaScript stubs from WSDL
I'm looking for a tool to generate a JavaScript stub from a WSDL. Although I usually prefer to use REST services with JSON or XML, there are some tools I am currently integrating that works only using SOAP. I already created a first version of the client in JavaScript but I'm parsing the SOAP envelope by hand and I doubt that my code can survive a service upgrade for example, seeing how complex the SOAP envelope specification is. So is there any tool to automatically generate fully SOAP compliant stubs for JavaScript from the WSDL so I can be more confident on the future of my client code. More: The web service I try to use is RPC encoded, not document literal.
I had to do this myself in the past and I found this CodeProject article. I changed it up some, but it gave me a good foundation to implement everything I needed. One of the main features it already has is generating the SOAP client based off the WSDL. It also has built in caching of the WSDL for multiple calls. This article also has a custom implementation of XmlHttpRequest for Ajax calls. This is the part that I didn't use. During that time, I think I was using Prototype javascript library and modified the code in this article to use it's Ajax functions instead. I just felt more comfortable using Prototype for the ajax calls, because it was widely used and had been tested on all the browsers.
Generating JavaScript stubs from WSDL I'm looking for a tool to generate a JavaScript stub from a WSDL. Although I usually prefer to use REST services with JSON or XML, there are some tools I am currently integrating that works only using SOAP. I already created a first version of the client in JavaScript but I'm parsing the SOAP envelope by hand and I doubt that my code can survive a service upgrade for example, seeing how complex the SOAP envelope specification is. So is there any tool to automatically generate fully SOAP compliant stubs for JavaScript from the WSDL so I can be more confident on the future of my client code. More: The web service I try to use is RPC encoded, not document literal.
TITLE: Generating JavaScript stubs from WSDL QUESTION: I'm looking for a tool to generate a JavaScript stub from a WSDL. Although I usually prefer to use REST services with JSON or XML, there are some tools I am currently integrating that works only using SOAP. I already created a first version of the client in JavaScript but I'm parsing the SOAP envelope by hand and I doubt that my code can survive a service upgrade for example, seeing how complex the SOAP envelope specification is. So is there any tool to automatically generate fully SOAP compliant stubs for JavaScript from the WSDL so I can be more confident on the future of my client code. More: The web service I try to use is RPC encoded, not document literal. ANSWER: I had to do this myself in the past and I found this CodeProject article. I changed it up some, but it gave me a good foundation to implement everything I needed. One of the main features it already has is generating the SOAP client based off the WSDL. It also has built in caching of the WSDL for multiple calls. This article also has a custom implementation of XmlHttpRequest for Ajax calls. This is the part that I didn't use. During that time, I think I was using Prototype javascript library and modified the code in this article to use it's Ajax functions instead. I just felt more comfortable using Prototype for the ajax calls, because it was widely used and had been tested on all the browsers.
[ "javascript", "soap", "wsdl" ]
15
8
22,214
3
0
2008-09-03T10:54:28.983000
2008-09-03T20:21:25.017000