Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I would like several textboxes to react to changes of an underlying string. So if I were to change the content of the string, all those textboxes would change their content too.
Now, I can't use the String type for that as it is immutable. So I went with StringBuilder. But the Text property of a TextBox object only takes String.
Is there an easy way to "bind" the StringBuilder object to the Text property of a TextBox?
Many thanks!
PS: The TextBox is currently WPF. But I might switch to Windows Forms because of Mono. | You could always expose a property that's getter returns the ToString() of the Stringbuilder. The form could then bind to this property.
```
private StringBuilder _myStringBuilder;
public string MyText
{
get { return _myStringBuilder.ToString(); }
}
``` | Here what I use to bind StringBuilder to TextBox in WPF:
```
public class BindableStringBuilder : INotifyPropertyChanged
{
private readonly StringBuilder _builder = new StringBuilder();
private EventHandler<EventArgs> TextChanged;
public string Text
{
get { return _builder.ToString(); }
}
public int Count
{
get { return _builder.Length; }
}
public void Append(string text)
{
_builder.Append(text);
if (TextChanged != null)
TextChanged(this, null);
RaisePropertyChanged(() => Text);
}
public void AppendLine(string text)
{
_builder.AppendLine(text);
if (TextChanged != null)
TextChanged(this, null);
RaisePropertyChanged(() => Text);
}
public void Clear()
{
_builder.Clear();
if (TextChanged != null)
TextChanged(this, null);
RaisePropertyChanged(() => Text);
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
{
if (propertyExpression == null)
{
return;
}
var handler = PropertyChanged;
if (handler != null)
{
var body = propertyExpression.Body as MemberExpression;
if (body != null)
handler(this, new PropertyChangedEventArgs(body.Member.Name));
}
}
#endregion
}
```
In ViewModel:
```
public BindableStringBuilder ErrorMessages { get; set; }
ErrorMessages.AppendLine("Missing Image: " + imagePath);
```
In Xaml:
```
<TextBox Text="{Binding ErrorMessages.Text, Mode=OneWay}"/>
```
Of course you can expose other StringBuilder methods if you need. | Howto bind TextBox control to a StringBuilder instance? | [
"",
"c#",
".net",
"string",
"textbox",
"stringbuilder",
""
] |
I'm trying to convert all instances of the > character to its HTML entity equivalent, >, within a string of HTML that contains HTML tags. The furthest I've been able to get with a solution for this is using a regex.
Here's what I have so far:
```
public static readonly Regex HtmlAngleBracketNotPartOfTag = new Regex("(?:<[^>]*(?:>|$))(>)", RegexOptions.Compiled | RegexOptions.Singleline);
```
The main issue I'm having is isolating the single > characters that are not part of an HTML tag. I don't want to convert any existing tags, because I need to preserve the HTML for rendering. If I don't convert the > characters, I get malformed HTML, which causes rendering issues in the browser.
This is an example of a test string to parse:
```
"Ok, now I've got the correct setting.<br/><br/>On 12/22/2008 3:45 PM, jproot@somedomain.com wrote:<br/><div class"quotedReply">> Ok, got it, hope the angle bracket quotes are there.<br/>><br/>> On 12/22/2008 3:45 PM, > sbartfast@somedomain.com wrote:<br/>>> Please someone, reply to this.<br/>>><br/>><br/></div>"
```
In the above string, none of the > characters that are part of HTML tags should be converted to >. So, this:
```
<div class"quotedReply">>
```
should become this:
```
<div class"quotedReply">>
```
Another issue is that the expression above uses a non-capturing group, which is fine except for the fact that the match is in group 1. I'm not quite sure how to do a replace only on group 1 and preserve the rest of the match. It appears that a MatchEvaluator doesn't really do the trick, or perhaps I just can't envision it right now.
I suspect my regex could do with some lovin'.
Anyone have any bright ideas? | The trick is to capture everything that *isn't* the target, then plug it back in along with the changed text, like this:
```
Regex.Replace(str, @"\G((?>[^<>]+|<[^>]*>)*)>", "$1>");
```
But Anthony's right: right angle brackets in text nodes shouldn't cause any problems. And matching HTML with regexes is tricky; for example, comments and CDATA can contain practically anything, so a robust regex would have to match them specifically. | Why do you want to do this? What harm are the > doing? Most parsers I've come across are quite happy with a > on its own without it needing to be escaped to an entity.
Additionally, it would be more appropriate to properly encode the content strings with HtmlUtilty.HtmlEncode before concatenating them with strings containing HTML markup, hence if this is under your control you should consider dealing with it there. | Convert > to HTML entity equivalent within HTML string | [
"",
"c#",
"regex",
"parsing",
"html-parsing",
""
] |
I want to initialize a static collection within my C# class - something like this:
```
public class Foo {
private static readonly ICollection<string> g_collection = ???
}
```
I'm not sure of the right way to do this; in Java I might do something like:
```
private static final Collection<String> g_collection = Arrays.asList("A", "B");
```
is there a similar construct in C# 2.0?
I know in later versions of C#/.NET you can do collection initializers (<http://msdn.microsoft.com/en-us/library/bb384062.aspx>), but migration isn't an option for our system at the moment.
To clarify my original question - I'm looking for a way to succinctly declare a simple static collection, such as a simple constant collection of strings. The static-initializer-style way is also really good to know for collections of more complex objects.
Thanks! | If I fully understand your question, it seems some others have missed the point, you're looking to create a static collection in a similar manner to Java in that you can declare and populate in a single line of code without having to create a dedicated method to do this (as per some of the other suggestions). This can be done using an array literal (written over two lines to prevent scrolling):
```
private static readonly ICollection<string> Strings =
new string[] { "Hello", "World" };
```
This both declares and populates the new readonly collection with the item list in one go. Works in 2.0 and 3.5, I tested it just to be doubly sure.
In 3.5 though you can use type inference so you no longer need to use the string[] array which removes even more keystrokes:
```
private static readonly ICollection<string> Strings =
new[] { "Hello", "World" };
```
Notice the missing "string" type in the second line line. String is automatically inferred from the contents of the array initializer.
If you want to populate it as a list, just change up the new string[] for new List a la:
```
private static readonly ICollection<string> Strings =
new List<string>() { "Hello", "World" };
```
Of course, because your type is IEnumerable rather than a specific implementation, if you want to access methods specific to List< string> such as .ForEach(), you will need to convert it to List:
```
((List<string>)Strings).ForEach(Console.WriteLine);
```
But it's a small price to pay for migratability [is that a word?]. | Static construction:
```
public class Foo
{
private static readonly ICollection<string> _collection;
static Foo()
{
_collection = new List<string>();
_collection.Add("One");
_collection.Add("Two");
}
}
```
But note that in this case you can just initialize the collection inline (recommended for [performance reasons](http://blogs.msdn.com/brada/archive/2004/04/17/115300.aspx)):
```
private static readonly ICollection<string> _collection = new List<string>(new string[] { "One", "Two" });
```
It really depends on how complex your initialization code is. | What is the right way to initialize a non-empty static collection in C# 2.0? | [
"",
"c#",
"collections",
""
] |
I noticed that `List<T>` defines its enumerator as a `struct`, while `ArrayList` defines its enumerator as a `class`. What's the difference? If I am to write an enumerator for my class, which one would be preferable?
**EDIT:** My requirements cannot be fulfilled using `yield`, so I'm implementing an enumerator of my own. That said, I wonder whether it would be better to follow the lines of `List<T>` and implement it as a struct. | Like this others, I would choose a class. Mutable structs are nasty. (And as Jared suggests, I'd use an iterator block. Hand-coding an enumerator is fiddly to get right.)
See [this thread](http://web.archive.org/web/20160711111502/http://aspnet-answers.com/microsoft/Csharp/31702392/c-compiler-challenge--see-if-you-can-answer-why.aspx) for an example of the list enumerator being a mutable struct causing problems... | The easiest way to write an enumerator in C# is with the "yield return" pattern. For example.
```
public IEnumerator<int> Example() {
yield return 1;
yield return 2;
}
```
This pattern will generate all of the enumerator code under the hood. This takes the decision out of your hands. | Enumerator Implementation: Use struct or class? | [
"",
"c#",
".net",
"enumeration",
""
] |
I have a file of about 30000 lines of data that I want to load into a sqlite3 database. Is there a faster way than generating insert statements for each line of data?
The data is space-delimited and maps directly to an sqlite3 table. Is there any sort of bulk insert method for adding volume data to a database?
Has anyone devised some deviously wonderful way of doing this if it's not built in?
I should preface this by asking, is there a C++ way to do it from the API? | You can also try [tweaking a few parameters](http://sqlite.org/pragma.html#modify) to get extra speed out of it. Specifically you probably want `PRAGMA synchronous = OFF;`. | * wrap all INSERTs in a transaction, even if there's a single user, it's far faster.
* use prepared statements. | Faster bulk inserts in sqlite3? | [
"",
"c++",
"sqlite",
"insert",
"bulk",
""
] |
I'm the sole developer for an academic consortium headquartered at a university in the northeast. All of my development work involves internal tools, mostly in Java, so nothing that is released to the public. Right now, I feel like my development workflow is very "hobbyist" and is nothing like you would see at an experienced software development firm. I would be inclined to say that it doesn't really matter since I'm the only developer anyway, but it can't hurt to make some changes, if for no other reason than to make my job a little easier and get a few more technologies on my resume. Right now my workflow is something like this:
* I do most of my development work in Eclipse on my laptop. Everything is saved locally on my laptop, and I don't use a VCS, nor do I really backup my code (except for occasionally emailing it to myself so I can see it on a different computer - yeah, I told you my development environment needs work).
* When I'm done with a project and want to deploy it or if I just want to test it, I use the built-in Jar tool in Eclipse to make an executable .jar of my project. If I use external .jar libraries, I use the Fat-Jar plugin to include those .jars in my executable .jar.
* After I create the .jar, I manually upload it to the server via SFTP and test it with something like `java -jar MyProject.jar`.
Oh yeah, did I mention that I don't unit test?
The most glaringly obvious problem that I'd like to fix first is my lack of source control. I like git because of it's distributed nature, but it doesn't seem to integrate with Eclipse well and I've heard that it doesn't work very well on Windows, which is my primary development OS. So, I'm leaning toward SVN, which I do have some experience with. I do have my own personal server, and I think I'll use that for my source control, because I'd rather be my own admin than have to deal with university bureaucracy. I had some trouble setting up SVN once before, but I'll give it another shot. Maybe I'll also install something like Trac or Redmine for bug-tracking, todo list, etc?
What about building and deployment? There has to be a better way than using Fat-Jar and manually uploading my jar to the server. I've heard about tools like Ant and Maven - do these apply to what I want to do? How can I get started using those?
I suppose I'd eventually like to integrate unit testing with JUnit too. Even though it probably should be, that is not my primary concern right now, because so far my applications aren't terribly complex. I'd really like to work on simplifying and streamlining my workflow right now, and then I'll ease into unit testing.
Sorry for the long question. I guess my question boils down to, for a sole developer, what tools and methodologies can/should I be using to not only make my job easier, but also just to expose myself to some technologies that would be expected requisite knowledge at a dedicated development house?
---
edit: Thanks for the great answers so far. I didn't mean to suggest that I wanted to make my workflow "enterprisey" just for the sake of doing it, but to make my job simpler and to get a few technologies under my belt that are typically used in enterprise development environments. That's all I meant by that. | It seems to me like you actually have a pretty good idea of what you need to do.
Using Subversion (or other VCS) is a must. Although it might be wise to setup a separate SVN repository for your work-related code rather than using a personal one.
You can integrate Subversion with Eclipse using a plugin like Subclipse, which I've found works pretty well.
I'd definitely use Ant or Maven - my preference is Ant because it's more flexible, and I think it would suit your development style more than Maven as well. But you might also want to look into [Apache Ivy](http://ant.apache.org/ivy/), which handles dependency-management.
Basically you set up an ant task which runs your compile, build and deployment steps - so that when you create a final JAR package you can be sure that it's been unit tested as that is part of your ant script. The best way to get started with ant is to look at some examples, and read through the [manual](http://ant.apache.org/manual/index.html).
As for unit testing - you can gradually build up with unit testing. I would recommend using JUnit in conjunction with a code coverage tool such as [Cobertura](http://cobertura.sourceforge.net/) (which is easy to set up) - it will help you to understand how much code your tests are covering and is an indicator about how effective your tests are.
It may also be worth your while setting up something like Trac - it's important to be able to keep track of bugs, and a wiki is surprisingly useful for documentation.
In other words, all of this sounds like you're on the right lines, you just need to get started using some of these tools! | If you're really set on distributed source control, I'd recommend you look at [Bazaar](http://bazaar-vcs.org/). Its GIT-like distributed source control that's designed around performing very high quality merges. Out of the box it works on all platforms including Windows and they have a [TortoiseBZR](http://bazaar-vcs.org/TortoiseBzr) client.
Really though, any source control is better than none. If you're the sole developer then there's no need for anything more complex than SVN. Large companies and projects use SVN all the time with little issue.
As far as unit testing goes, you should make yourself familiar with [JUnit](http://www.junit.org/). The fact that you're aware of unit testing and know you should be doing it is still several steps ahead of most ad-hoc developers. | How can I make my development workflow more "enterprisey"? | [
"",
"java",
"workflow",
"development-environment",
""
] |
I have pretty big background of .net, and I've decided that i want to port one of my websites to Java. (now with the asp.net MVC craze, I've figured I'd better learn a more mature approach to MVC).
i've downloaded eclipse (easyeclipse distro to be exact, and am ready and willing to develop my first website in java).
i've programmed j2me application before, so i know the language and some of the framework.
can someone guide me? any advice? | Although I'm not very aware of "asp.net mvc" is all about, I would suggest you to take a look at [Spring](http://www.springsource.org/about) it may be interesting.
Probably is too complicated at the beginning but when you get the concept it turns out very easy to follow.
Spring has 5 core modules ( which I don't remember exactly ) but they were like:
* AOP
* ORM
* MVC
* Core
* ( some other I'm missing here )
The MVC part uses a lot of annotations to make life easier. There's a very big community around Spring.
[Here's](http://www.theserverside.com/tt/articles/article.tss?l=SpringFramework) an introductory article about spring. | Java has a ton of frameworks you can choose from. The technology stack that I use for my Java development is either:
Spring for IoC.
Hibernate for the data layer.
Struts2 for the MVC framework.
I have also swapped out spring and used Guice for the IoC.
Spring also has MVC, but I tend to like Struts2 better. | Helping a beginner for java web application | [
"",
"java",
"eclipse",
"model-view-controller",
""
] |
I've been using extension methods quite a bit recently and have found a lot of uses for them. The only problem I have is remembering where they are and what namespace to use in order to get the extension methods.
However, I recently had a thought of writing the extension methods in the System namespace, System.Collections namespace or some other system namespace that makes sense. So for example, I've implemented the following.
```
namespace System
{
/// <summary>Various array extensions</summary>
public static class ArrayExtensions
{
/// <summary>Converts the array to a hex string</summary>
/// <param name="value">The value.</param>
/// <returns>The array as a hex string</returns>
public static string ToHexString(this byte[] value)
{
var hex = new StringBuilder(value.Length * 2);
foreach (byte b in value)
{
hex.AppendFormat("{0:X2}", b);
}
return hex.ToString();
}
}
}
```
Is this the correct thing to do? | From the Framework Design Guidelines (2nd Edition):
DO NOT put extension methods in the same namespace as the extended type, unless it is for adding methods to interfaces, or for dependency management.
While this doesn't explicitly cover your scenario, you should generally avoid extending a Framework namespace (or any namespace you have no control over) and opt instead to put those extensions in their own namespace. If you feel strongly about "grouping" the extensions (such that the collection extensions are together, etc.) then you could introduce a subnamespace. In your scenario, extension to the collections would go in a `System.Collection.Extensions` namespace or a `Company.Collections` or even a `Company.Collections.Extension` namespace.
In order to use extension methods the namespace containing the sponsor class (the class that defines the extension methods) must be imported. If you add extension methods to one of the standard .NET Framework namespaces they will always (and implicitly) be available. | You should avoid augmenting namespaces over which you do not have primary control as future changes can break your code (by introducing duplicates, for example).
I tend to mimic the standard namespaces with a different root namespace that identifies all child namespaces as belonging to my work. The root namespace could be your name, your organisation's name, or something else that identifies the contents of that namespace as being yours.
For example, if you want to extend `System.Collections`, you could use `NickR.Collections` or `NickR.System.Collections`. | Is it ok to write my own extension methods in the system namespace? | [
"",
"c#",
".net",
"extension-methods",
""
] |
I currently working on an issue tracker for my company to help them keep track of problems that arise with the network. I am using C# and SQL.
Each issue has about twenty things we need to keep track of(status, work loss, who created it, who's working on it, etc). I need to attach a list of teams affected by the issue to each entry in my main issue table. The list of teams affected ideally contains some sort of link to a unique table instance, just for that issue, that shows the list of teams affected and what percentage of each teams labs are affected.
So my question is what is the best way to impliment this "link" between an entry into the issue table and a unique table for that issue? Or am I thinking about this problem wrong. | What you are describing is called a "many-to-many" relationship. A team can be affected by many issues, and likewise an issue can affect many teams.
In SQL database design, this sort of relationship requires a third table, one that contains a reference to each of the other two tables. For example:
```
CREATE TABLE teams (
team_id INTEGER PRIMARY KEY
-- other attributes
);
CREATE TABLE issues (
issue_id INTEGER PRIMARY KEY
-- other attributes
);
CREATE TABLE team_issue (
issue_id INTEGER NOT NULL,
team_id INTEGER NOT NULL,
FOREIGN KEY (issue_id) REFERENCES issues(issue_id),
FOREIGN KEY (team_id) REFERENCES teams(team_id),
PRIMARY KEY (issue_id, team_id)
);
``` | This sounds like a classic many-to-many relationship...
You probably want three tables,
1. One for issues, with one record (row) per each individual unique issue created...
2. One for the teams, with one record for each team in your company...
3. And one table called say, "IssueTeams" or "TeamIssueAssociations" `or "IssueAffectedTeams" to hold the association between the two...
This last table will have one record (row) for each team an issue affects... This table will have a 2-column composite primary key, on the columns IssueId, AND TeamId... Every row will have to have a unique combination of these two values... Each of which is individually a Foreign Key (FK) to the Issue table, and the Team Table, respectively.
For each team, there may be zero to many records in this table, for each issue the team is affected by,
and for each Issue, there may be zero to many records each of which represents a team the issue affects. | Designing an SQL Table and getting it right the first time | [
"",
"sql",
"database-design",
""
] |
I have a PHP application that makes extensive use of Javascript on the client side. I have a simple system on the PHP side for providing translators an easy way to provide new languages. But there are cases where javascript needs to display language elements to the user (maybe an OK or cancel button or "loading" or something).
With PHP, I just have a text file that is cached on the server side which contains phrase codes on one side and their translation on the other. A translator just needs to replace the english with their own language and send me the translated version which I integrate into the application.
I want something similar on the client side. It occurred to me to have a javascript include that is just a set of translated constants but then every page load is downloading a potentially large file most of which is unnecessary.
Has anyone had to deal with this? If so, what was your solution?
**EDIT**: To be clear, I'm not referring to "on-the-fly" translations here. The translations have already been prepared and are ready to go, I just need them to be made available to the client in an efficient way. | How about feeding the javascript from php? So instead of heaving:
```
<script type='text/javascript' src='jsscript.js'></script>
```
do
```
<script type='text/javascript' src='jsscript.php'></script>
```
And then in the php file replace all outputted text with their associated constants.
Be sure to output the correct caching headers from within PHP code.
**EDIT**
These are the headers that I use:
```
header('Content-type: text/javascript');
header('Cache-Control: public');
header('expires: '. date("r", time() + ( 7 * 24 * 60 * 60 ) ) ); // 1 week
header("Pragma: public");
``` | I usually load the appropriate language values as a JavaScript object in a separate file which the rest of my code can reference:
```
var messages = {
"loading": "Chargement"
}
alert(messages.loading);
```
The language library will be cached on the client side after the first load and you can improve load efficiency by splitting values into separate files that are loaded based on context: e.g. a small library for public operations, an additional one behind a login, etc. | Javascript and Translations | [
"",
"javascript",
"translation",
"translation-scheme",
""
] |
I'm working on a Silverlight control that will allow multi-file downloading. At the moment I'm trying to get my mind around the permission model of the browser.
Let's say, on a web page, a user enters a local folder (c:\temp) in a text box. The user then clicks a button.
Is it possible in JavaScript or Silverlight, to write a collection of files (that are stored on the server) to that folder on the user's drive? | From Javascript - NO. It would be way too easy from some scumbag to install a virus on your PC if that were possible.
Silverlight I don't know about, but I would assume writing to the users hard drive would be very limited and tightly controlled. | **Warning: most of these answers are incorrect.**
You *can so* write to a file via Javascript in both MSIE (using ActiveX FileSystemObject) and Firefox (using nsIFileOutputStream). In both cases the user will be presented with a security dialogue, which can be allow or deny the read or write. | Write to local disk from web page | [
"",
"javascript",
"silverlight",
"browser",
""
] |
i'm relatively new to jquery and javascript and am trying to pass
a unique id (number) into a flickr search function (jquery.flickr-1.0-js) like so, (number is the variable where i'm storing the unique id)
```
<script type="text/javascript" src="javascripts/jquery.flickr-1.0.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery(".btnRefresh").click(function(){
var number = $(this).attr("id");
$('#gallery_flickr_'+number+'').show();
jQuery('#gallery_flickr_'+number+'').html("").flickr({
api_key: "XXXXXXXXXXXXXXXXXXXXXXX",
per_page: 15
});
});
});
</script>
```
When i try to pass it in to the flickr-1.0.js function like so (abbreviated)
```
(function($) {
$.fn.flickr = function(o){
var s = {
text: $('input#flickr_search_'+number+'').val(),
};
};
})(jQuery);
```
i get a error
number is not defined
[Break on this error] text: $('input#flickr\_search\_'+numbe...] for type=='search' free text search
please help, what do i need to do to pass the variable between the two scripts?
Thanks, | Try adjusting your scripts as below:
```
...
jQuery('#gallery_flickr_'+number+'').html("").flickr({
api_key: "XXXXXXXXXXXXXXXXXXXXXXX",
per_page: 15,
search_text: $('input#flickr_search_'+number+'').val()
});
...
(function($) {
$.fn.flickr = function(o){
var s = {
text: o.search_text
};
};
})(jQuery);
```
The idea is that you need to find the search text based on the id of the clicked item. You do that in the function where the id is available, then pass the value of the input to the flickr function with the other values in the hash argument. In the flickr function you extract the named item from the hash and use the value. | You can pass parameters in JQuery very easily; for example:
```
$.ajax({
type: "POST",
url: "/<%=domainMap%>/registration/recieptList.jsp",
data: "patientId=" + patientId+"golbalSearch="+golbalSearch,
success: function(response){
// we have the response
$('#loadPatientReciept').html(response);
},
error: function(e){
alert('Error: ' + e);
}
});
}
``` | Passing variables with jQuery | [
"",
"javascript",
"jquery",
""
] |
I would like to do the same thing I do in Java with the `final` keyword. I tried to use the `const` keyword, but it doesn't work. How can I prevent other classes from inheriting from my class? | The keyword you are searching is "sealed".
[MSDN](http://msdn.microsoft.com/en-us/library/88c54tsw.aspx) | "NonInheritable" for VB.NET
[MSDN](http://msdn.microsoft.com/en-us/library/h278d2d4.aspx) | How to make a class protected for inheritance? | [
"",
"c#",
".net",
"oop",
""
] |
I'm looking for ways to display a single row of data as a single column (with multiple rows). For example,
```
FieldA FieldB
------- ---------
1 Some Text [row]
Header Value [col]
------ ------
FieldA 1 [row1]
FieldB SomeText [row2]
```
Is there a way to do this with SQL Server 2005? | Yup, there's a TSQL command, PIVOT. And there are several existing threads on this topic; but I can't find one offhand.
My usual answer (probably 5 or 6 of those threads) is to think about using Excel or Access if appropriate - it's a pretty easy way to deliver value to end-users. But YMMV. | You can use unpivot [explained here](http://wiki.lessthandot.com/index.php/Column_To_Row_(UNPIVOT))
```
Declare @tbl Table
(
c1 int,
c2 int,
c3 int
)
Insert into @tbl Values(1,2,3)
Select
cname,
cval
From
(
Select C1,C2,C3 From @tbl
) t
UNPIVOT
(Cval For Cname In
(C1,C2,C3)
)As U
```
But it is usually inflexible and slow. You can use union but it is usually worse in terms of maintaince but might be fast (need to check) or use dynamic query and union | Display a single record (row) as a single column | [
"",
"sql",
"sql-server",
"sql-server-2005",
"pivot",
""
] |
I have a program that continually polls the database for change in value of some field. It runs in the background and currently uses a while(true) and a sleep() method to set the interval. I am wondering if this is a good practice? And, what could be a more efficient way to implement this? The program is meant to run at all times.
Consequently, the only way to stop the program is by issuing a kill on the process ID. The program could be in the middle of a JDBC call. How could I go about terminating it more gracefully? I understand that the best option would be to devise some kind of exit strategy by using a flag that will be periodically checked by the thread. But, I am unable to think of a way/condition of changing the value of this flag. Any ideas? | > I am wondering if this is a good practice?
No. It's not good. Sometimes, it's all you've got, but it's not good.
> And, what could be a more efficient way to implement this?
How do things get into the database in the first place?
The best change is to fix programs that insert/update the database to make requests which go to the database and to your program. A JMS topic is good for this kind of thing.
The next best change is to add a trigger to the database to enqueue each insert/update event into a queue. The queue could feed a JMS topic (or queue) for processing by your program.
The fall-back plan is your polling loop.
Your polling loop, however, should not trivially do work. It should drop a message into a queue for some other JDBC process to work on. A termination request is another message that can be dropped into the JMS queue. When your program gets the termination message, it absolutely must be finished with the prior JDBC request and can stop gracefully.
Before doing any of this, look at ESB solutions. Sun's [JCAPS](http://www.sun.com/software/javaenterprisesystem/javacaps/index.jsp) or [TIBCO](http://www.tibco.com/) already have this. An open source ESB like [Mulesource](http://www.mulesource.org/display/MULE/Home) or [Jitterbit](http://www.jitterbit.com/) may already have this functionality already built and tested. | This is really too big an issue to answer completely in this format. Do yourself a favour and go buy [Java Concurrency in Practice](https://rads.stackoverflow.com/amzn/click/com/0321349601). There is no better resource for concurrency on the Java 5+ platform out there. There are **whole chapters** devoted to this subject.
On the subject of killing your process during a JDBC call, that should be fine. I believe there are issues with interrupting a JDBC call (in that you can't?) but that's a different issue. | Java while loop and Threads! | [
"",
"java",
"multithreading",
"while-loop",
""
] |
I remember reading once that the order of the members of an evaluation is important.
Such as
```
if (null == myClass)
```
is better (faster?) then
```
if (myClass == null)
```
is this the case?
If so could someone explain how and why?
If the answer requires a language then aim towards c#.
Thanks | No, it is not faster. This is a relic from the old C days, it avoided doing bugs like
```
if(myClass = null) /* accident, sets myClass to null instead of comparing */
```
so you would always have the constant at the left:
```
if(null = myClass) /* throws an error at compile time */
```
However it makes no sense to do this in C# I believe.. | It's not faster since both sides of the == sign need to be evaluated.
If you have more than one condition though then the [short circuit](http://en.wikipedia.org/wiki/Short-circuit_evaluation) rule apply.
The conditions are evaluated one after the other until a definite answer is reached and only till then.
So if you have
```
if ((a != null) && (someLongCheck()) ...
```
and a is null then `someLongCheck()` will not be called. | Optimising if statements by reordering | [
"",
"c#",
"optimization",
""
] |
When writing custom classes it is often important to allow equivalence by means of the `==` and `!=` operators. In Python, this is made possible by implementing the `__eq__` and `__ne__` special methods, respectively. The easiest way I've found to do this is the following method:
```
class Foo:
def __init__(self, item):
self.item = item
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
```
Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing `__dict__`s?
**Note**: A bit of clarification--when `__eq__` and `__ne__` are undefined, you'll find this behavior:
```
>>> a = Foo(1)
>>> b = Foo(1)
>>> a is b
False
>>> a == b
False
```
That is, `a == b` evaluates to `False` because it really runs `a is b`, a test of identity (i.e., "Is `a` the same object as `b`?").
When `__eq__` and `__ne__` are defined, you'll find this behavior (which is the one we're after):
```
>>> a = Foo(1)
>>> b = Foo(1)
>>> a is b
False
>>> a == b
True
``` | Consider this simple problem:
```
class Number:
def __init__(self, number):
self.number = number
n1 = Number(1)
n2 = Number(1)
n1 == n2 # False -- oops
```
So, Python by default uses the object identifiers for comparison operations:
```
id(n1) # 140400634555856
id(n2) # 140400634555920
```
Overriding the `__eq__` function seems to solve the problem:
```
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, Number):
return self.number == other.number
return False
n1 == n2 # True
n1 != n2 # True in Python 2 -- oops, False in Python 3
```
In *Python 2*, always remember to override the `__ne__` function as well, as the [documentation](https://docs.python.org/2.7/reference/datamodel.html#object.__ne__) states:
> There are no implied relationships among the comparison operators. The
> truth of `x==y` does not imply that `x!=y` is false. Accordingly, when
> defining `__eq__()`, one should also define `__ne__()` so that the
> operators will behave as expected.
```
def __ne__(self, other):
"""Overrides the default implementation (unnecessary in Python 3)"""
return not self.__eq__(other)
n1 == n2 # True
n1 != n2 # False
```
In *Python 3*, this is no longer necessary, as the [documentation](https://docs.python.org/3/reference/datamodel.html#object.__ne__) states:
> By default, `__ne__()` delegates to `__eq__()` and inverts the result
> unless it is `NotImplemented`. There are no other implied
> relationships among the comparison operators, for example, the truth
> of `(x<y or x==y)` does not imply `x<=y`.
But that does not solve all our problems. Let’s add a subclass:
```
class SubNumber(Number):
pass
n3 = SubNumber(1)
n1 == n3 # False for classic-style classes -- oops, True for new-style classes
n3 == n1 # True
n1 != n3 # True for classic-style classes -- oops, False for new-style classes
n3 != n1 # False
```
**Note:** Python 2 has two kinds of classes:
* *[classic-style](https://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes)* (or *old-style*) classes, that do *not* inherit from `object` and that are declared as `class A:`, `class A():` or `class A(B):` where `B` is a classic-style class;
* *[new-style](https://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes)* classes, that do inherit from `object` and that are declared as `class A(object)` or `class A(B):` where `B` is a new-style class. Python 3 has only new-style classes that are declared as `class A:`, `class A(object):` or `class A(B):`.
For classic-style classes, a comparison operation always calls the method of the first operand, while for new-style classes, it always calls the method of the subclass operand, [regardless of the order of the operands](https://stackoverflow.com/a/12984987/78234).
So here, if `Number` is a classic-style class:
* `n1 == n3` calls `n1.__eq__`;
* `n3 == n1` calls `n3.__eq__`;
* `n1 != n3` calls `n1.__ne__`;
* `n3 != n1` calls `n3.__ne__`.
And if `Number` is a new-style class:
* both `n1 == n3` and `n3 == n1` call `n3.__eq__`;
* both `n1 != n3` and `n3 != n1` call `n3.__ne__`.
To fix the non-commutativity issue of the `==` and `!=` operators for Python 2 classic-style classes, the `__eq__` and `__ne__` methods should return the `NotImplemented` value when an operand type is not supported. The [documentation](https://docs.python.org/2.7/reference/datamodel.html#the-standard-type-hierarchy) defines the `NotImplemented` value as:
> Numeric methods and rich comparison methods may return this value if
> they do not implement the operation for the operands provided. (The
> interpreter will then try the reflected operation, or some other
> fallback, depending on the operator.) Its truth value is true.
In this case the operator delegates the comparison operation to the *reflected method* of the *other* operand. The [documentation](https://docs.python.org/2.7/reference/datamodel.html#object.__lt__) defines reflected methods as:
> There are no swapped-argument versions of these methods (to be used
> when the left argument does not support the operation but the right
> argument does); rather, `__lt__()` and `__gt__()` are each other’s
> reflection, `__le__()` and `__ge__()` are each other’s reflection, and
> `__eq__()` and `__ne__()` are their own reflection.
The result looks like this:
```
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, Number):
return self.number == other.number
return NotImplemented
def __ne__(self, other):
"""Overrides the default implementation (unnecessary in Python 3)"""
x = self.__eq__(other)
if x is NotImplemented:
return NotImplemented
return not x
```
Returning the `NotImplemented` value instead of `False` is the right thing to do even for new-style classes if *commutativity* of the `==` and `!=` operators is desired when the operands are of unrelated types (no inheritance).
Are we there yet? Not quite. How many unique numbers do we have?
```
len(set([n1, n2, n3])) # 3 -- oops
```
Sets use the hashes of objects, and by default Python returns the hash of the identifier of the object. Let’s try to override it:
```
def __hash__(self):
"""Overrides the default implementation"""
return hash(tuple(sorted(self.__dict__.items())))
len(set([n1, n2, n3])) # 1
```
The end result looks like this (I added some assertions at the end for validation):
```
class Number:
def __init__(self, number):
self.number = number
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, Number):
return self.number == other.number
return NotImplemented
def __ne__(self, other):
"""Overrides the default implementation (unnecessary in Python 3)"""
x = self.__eq__(other)
if x is not NotImplemented:
return not x
return NotImplemented
def __hash__(self):
"""Overrides the default implementation"""
return hash(tuple(sorted(self.__dict__.items())))
class SubNumber(Number):
pass
n1 = Number(1)
n2 = Number(1)
n3 = SubNumber(1)
n4 = SubNumber(4)
assert n1 == n2
assert n2 == n1
assert not n1 != n2
assert not n2 != n1
assert n1 == n3
assert n3 == n1
assert not n1 != n3
assert not n3 != n1
assert not n1 == n4
assert not n4 == n1
assert n1 != n4
assert n4 != n1
assert len(set([n1, n2, n3, ])) == 1
assert len(set([n1, n2, n3, n4])) == 2
``` | You need to be careful with inheritance:
```
>>> class Foo:
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
>>> class Bar(Foo):pass
>>> b = Bar()
>>> f = Foo()
>>> f == b
True
>>> b == f
False
```
Check types more strictly, like this:
```
def __eq__(self, other):
if type(other) is type(self):
return self.__dict__ == other.__dict__
return False
```
Besides that, your approach will work fine, that's what special methods are there for. | Elegant ways to support equivalence ("equality") in Python classes | [
"",
"python",
"equality",
"equivalence",
""
] |
I'm using the code that netadictos posted to the question [here](https://stackoverflow.com/questions/333665/). All I want to do is to display a warning when a user is navigating away from or closing a window/tab.
The code that netadictos posted seems to work fine in IE7, FF 3.0.5, Safari 3.2.1, and Chrome but it doesn't work in Opera v9.63. Does anyone know of way of doing the same thing in Opera?
Thx, Trev | `onbeforeunload` is now supported in Opera 15 based on the WebKit engine but not in any prior versions based on Presto. | Opera does not support window.onbeforeunload at the moment. It will be supported in some future version, but has not been a sufficiently high priority to get implemented as of Opera 11. | onbeforeunload in Opera | [
"",
"javascript",
"events",
"opera",
"onbeforeunload",
""
] |
i have the following directories:
-UI
-BusinessLogic
-DataAccess
-BusinessObjects
if i have a class that is a client stub to a server side service that changes state on a server system, where would that go . . | this code belongs in the recycle bin ;-)
seriously, if you wrote it and don't know where it goes, then either the code is questionable or your partitioning is questionable; how are we supposed to have more information about your system than you have?
now if you just want some uninformed opinions, those we've got by the petabyte:
1. it goes in the UI because you said it's a client stub
2. it goes in the business logic because it implements the effect of a business rule
3. it goes in the data access layer because it is accessing a state-changing service
4. it goes in the business object layer because it results in a state change on the server
it would be more helpful if you told us what the stub actually does; without specifics it is hard to know where it belongs, and/or it is easy to argue in a vacuum about where it "should" belong | I would consider this a form of data access, although it's not clear to me that you need to put it in the same project as the rest of your data access classes. Remember that the layers are mainly conceptual -- to help you keep your design clean. Separating them into different projects helps organizationally, but is not mandatory. If it's an actual stub class, then the data access project is probably the natural home for it, but if it's only used in the UI layer, then keeping it there would probably be ok. | Determining the best way to break up code into different folders and namespaces | [
"",
"c#",
"directory-structure",
""
] |
I'm serializing to XML my class where one of properties has type List<string>.
```
public class MyClass {
...
public List<string> Properties { get; set; }
...
}
```
XML created by serializing this class looks like this:
```
<MyClass>
...
<Properties>
<string>somethinghere</string>
<string>somethinghere</string>
</Properties>
...
</MyClass>
```
and now my question. How can I change my class to achieve XML like this:
```
<MyClass>
...
<Properties>
<Property>somethinghere</Property>
<Property>somethinghere</Property>
</Properties>
...
</MyClass>
```
after serializing. Thanks for any help! | Try [XmlArrayItemAttribute](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute.aspx):
```
using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
public class Program
{
[XmlArrayItem("Property")]
public List<string> Properties = new List<string>();
public static void Main(string[] args)
{
Program program = new Program();
program.Properties.Add("test1");
program.Properties.Add("test2");
program.Properties.Add("test3");
XmlSerializer xser = new XmlSerializer(typeof(Program));
xser.Serialize(new FileStream("test.xml", FileMode.Create), program);
}
}
```
test.xml:
```
<?xml version="1.0"?>
<Program xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Properties>
<Property>test1</Property>
<Property>test2</Property>
<Property>test3</Property>
</Properties>
</Program>
``` | Add `[XmlElement("Property")]` before the declaration of your Properties member. | How do you rename the child XML elements used in an XML Serialized List<string>? | [
"",
"c#",
".net",
"xml",
"serialization",
""
] |
HI i did this code with help of Marc Gravell in
[Why can't I find \_left and \_right in BinarySearchTree?](https://stackoverflow.com/questions/406791/)
&
[How do I correct an implicit conversion error in BST C# Code?](https://stackoverflow.com/questions/406402/bst-c-code-with-errors)
, its Binary search tree , but now I'm having logical error the results coming are wrong the output of my code is the following:
```
2
3
5
6
10
17
------------------------------------------------
17
2
------------------------------------------------
3
6
Press any key to continue . . .
```
the last two number must give the total of inserted elements 6 but its showing 9
and but the way How can i get the height of the tree ?!
---
```
using System;
using System.Collections.Generic;
using System.Text;
namespace errors
{
class Program
{
static void Main(string[] args)
{
BinarySearchTree t = new BinarySearchTree();
t.insert(ref t.root, 10);
t.insert(ref t.root, 5);
t.insert(ref t.root, 6);
t.insert(ref t.root, 17);
t.insert(ref t.root, 2);
t.insert(ref t.root, 3);
BinarySearchTree.print(t.root);
Console.WriteLine("------------------------------------------------");
Console.WriteLine(t.FindMax());
Console.WriteLine(t.FindMin());
Console.WriteLine("------------------------------------------------");
Console.WriteLine(t.CountLeaves(t.root));
Console.WriteLine(t.CountNodes(t.root));
}
public class TreeNode
{
public int n;
public TreeNode _left;
public TreeNode _right;
public TreeNode(int n, TreeNode _left, TreeNode _right)
{
this.n = n;
this._left = _left;
this._right = _right;
}
public void DisplayNode()
{
Console.Write(n);
}
}
public class BinarySearchTree
{
public TreeNode root;
public BinarySearchTree()
{
root = null;
}
public void insert(ref TreeNode root, int x)
{
if (root == null)
{
root = new TreeNode(x, null, null);
}
else
if (x < root.n)
insert(ref root._left, x);
else
insert(ref root._right, x);
}
public int FindMin()
{
TreeNode current = root;
while (current._left != null)
current = current._left;
return current.n;
}
public int FindMax()
{
TreeNode current = root;
while (current._right != null)
current = current._right;
return current.n;
}
public TreeNode Find(int key)
{
TreeNode current = root;
while (current.n != key)
{
if (key < current.n)
current = current._left;
else
current = current._right;
if (current == null)
return null;
}
return current;
}
public void InOrder(ref TreeNode root)
{
if (root != null)
{
InOrder(ref root._left);
root.DisplayNode();
InOrder(ref root._right);
}
}
public int CountNodes(TreeNode root)
{
int count=1;
if (root._left != null)
count += CountNodes(root._left);
if (root._right != null)
count += CountNodes(root._right);
return count;
}
public int CountLeaves(TreeNode root)
{
int count = (root._left == null && root._right == null) ? 1 : 0;
if (root._left != null)
count += CountLeaves(root._left);
if (root._right != null)
count += CountLeaves(root._right);
return count;
}
public static void print(TreeNode root)
{
if (root != null)
{
print(root._left);
Console.WriteLine(root.n.ToString());
print(root._right);
}
}
}
}
}
```
Thanx in advance and special thanx to Marc Gravell . | If what you mean in `CountNodes` is to count all non-leaf nodes you must change this line:
```
int count=1;
```
to read this:
```
int count = (root._left == null && root._right == null) ? 0 : 1;
```
(the opposite of what is in `CountLeaves`).
And this will get you the height of the tree:
```
public int Height(TreeNode root)
{
int height = 1;
if (root._left != null)
height = Math.Max(height, Height(root._left));
if (root._right != null)
height = Math.Max(height, Height(root._right));
return height;
}
``` | Regarding getting the tree height, use the following recursive pseudo-code, calling `nodeHeight(root)`:
```
nodeHeight(node)
left=0
right=0
if (node == null) return 0
left = 1 + nodeHeight(getLeft(node))
right = 1 + nodeHeight(getRight(node))
return max(left,right)
``` | Logical error BST ... wrong results | [
"",
"c#",
"binary-tree",
""
] |
Exactly as the question states: How can you check if a variable in PHP contains a file pointer? Some like `is_string()` or `is_object()`. | You can use `get_resource_type()` - <https://www.php.net/manual/en/function.get-resource-type.php>. The function will return FALSE if its not a resource at all.
```
$fp = fopen("foo", "w");
...
if(get_resource_type($fp) == 'file' || get_resource_type($fp) == 'stream') {
//do what you want here
}
```
The PHP documentation says that the above function calls should return 'file', but on my setup it returns 'stream'. This is why I check for either result above. | You can use [`stream_get_meta_data()`](http://www.php.net/manual/en/function.stream-get-meta-data.php) for this.
```
<?php
$f = fopen('index.php', 'r');
var_dump(stream_get_meta_data($f));
?>
array
'wrapper_type' => string 'plainfile' (length=9)
'stream_type' => string 'STDIO' (length=5)
'mode' => string 'r' (length=1)
'unread_bytes' => int 0
'seekable' => boolean true
'uri' => string 'index.php' (length=9)
'timed_out' => boolean false
'blocked' => boolean true
'eof' => boolean false
```
You can prefix it with @ to supress warnings if the variable is not a resource - then just check if it returned false. | How do you determine if a variable contains a file pointer in PHP? | [
"",
"php",
""
] |
Is there any better alternative for doing string formatting in VC6, with syntax checking before substitution? | `CString` offers the `Format` method for `printf`-style formatting, but this isn't type-safe.
For type-safe string formatting you could either use `std::stringstream` / `std::wstringstream` or the [Boost Format](http://www.boost.org/doc/libs/1_37_0/libs/format/index.html) library, although these both work with the C++ `std::basic_string` class template, and not the MFC `CString` class. I've used both of these successfully in VC6.
Boost Format is nice because it allows you to use `printf`-like syntax, and will throw an exception if the arguments you supply don't match the format string, whereas string formatting with C++ iostreams tends to make your code quite verbose.
Note that you can create a `CString` object from a `std::string` as follows:
```
std::string s;
CString str( s.c_str() );
```
I hope this helps! | Check out [FastFormat](http://www.fastformat.org/). It has an easy syntax, and a "sink" - FastFormat terminology for the thing that receives the result of the formatting operation - for CString.
Something along the lines of:
```
int i = 1;
std::string ss = "a std string";
CString cs = "a Cstring";
CString result;
fastformat::fmt(result, "i={0}, ss={1}, cs={2}", i, ss, cs);
``` | Alternative to CString::Format? | [
"",
"c++",
"string",
"mfc",
"format",
""
] |
Consider the following snippet:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace ForumLogins {
public class VBULLETIN {
HttpWebRequest request;
public void ForumLogins(string url) {
request = (HttpWebRequest)WebRequest.Create(url);
}
}
}
```
According to MSDN the "Create" method can return 4 exceptions. Now I cant dissolve those exceptions.. because well otherwise the class wont function. But what should I do? Should I still wrap it in a try/catch block? and in the catch "throw a new exception".. or let the person who implments this class handle the exceptions?
Cuz this is a constructor .. and I guess constructors arnt really supposed to fail? | If your constructor can fail, then you should probably let the person who implements the class handle the errors. Just be sure to document the fact that it might fail so they know to try/catch.
On a related note, constructors should never fail. =)
Instead, put the logic that can possibly fail into a "Go()" method. That way you can instantiate a real class, but put a try/catch around segments of the code, and still reference the object outside of the try-catch block later. Just my $.02. | What you do depends on the role of the code. If this is a library that your going to share I'd recommend you wrap all exceptions and rethrow meaningful exceptions for your library. This will help you achieve implenentation encapsulation.
For example
```
try
{
if (string.isNullOrEmpty(url))
{
//This will stop the arugment null exception and you can throw a meaningful message
}
request = (HttpWebRequest)WebRequest.Create(url);
}
catch(SecurityException sex)
{
//Can't handle this but maybee you can provide more information about how to configure security here...
throw new YourCustomerException(msg,sex); //It's good practice to put the current exception in the inner exception
}
```
If your not building a component and this is your application then I recommend you somewhere along the stack catch the error, and log it.
Also this isn't a constructor your calling a Factory method on WebRequest called Create. | explanation needed for exceptions/classes | [
"",
"c#",
"design-patterns",
""
] |
I have a table of paged data, along with a dynamically created pager (server-side AJAX call, apply returned HTML to the innerHTML of a div).
When I click next page on my pager, an AJAX call is sent to the server to retrieve the next set of data, which is returned as a string of HTML. I parse the HTML and render the new table rows. I also retrieve the pager HTML and load it into its parent DIV innerHTML. No problems so far.
In Firefox I can click on the pager and all my javascript functions will execute normally. In IE, my first click will now not register, but the second click will perform the expected action.
**What is it about IE that disables the first click on my returned HTML?** | Turns out I have a race condition. The library (coded in-house) is calling my callback function before I get a response from the server. As a result, none of my callback functions do anything, since I'm not passing a valid value. I've set a loop up to check every ten milliseconds for a value, otherwise wait. I modified the tutorial from here:
<http://wonko.com/post/how-to-prevent-yui-get-race-conditions> | I'm not sure if your issue is related to one I ran into with postbacks, but some of the AJAX libraries I was using was inserting extra controls into the page and was causing the generated ID in my link to no longer match up to the ID the server expected for the postback event.
The event was firing, but when the event was hooked up the ID's didn't match between the clicked link and the link object the listener was expecting.
However, after the first click the postback would cause the ID's to resynchronize and the second click would then be able to match up the IDs.
The way I discovered this was by examining the ID in the link before and after the first click.
Again, I'm not certain this is what is happening to you. The symptom is similar, but in my case both Firefox and IE were failing. Hopefully this is helpful. | Returned AJAX html breaks IE click events | [
"",
"javascript",
"html",
"ajax",
"internet-explorer",
""
] |
I have an enumeration for Status for a Task. Some of the statuses are considered obsolete, and I have marked them as obsolete, as seen below:
```
public enum TaskStatus
{
[Description("")]
NotSet = 0,
Pending = 1,
Ready = 2,
Open = 3,
Completed = 4,
Closed = 5,
[Description("On Hold")][Obsolete]
OnHold = 6,
[Obsolete]
Canceled = 7
}
```
In my user interface I populate a drop down with values on the enumerations, but I want to ignore ones that are marked as obsolete. How would I got about doing this? | You could write a LINQ-query:
```
var availableTaks = typeof (TaskStatus).GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)
.Where(f => f.GetCustomAttributes(typeof (ObsoleteAttribute), false).Length == 0);
foreach(var task in availableTaks)
Console.WriteLine(task);
``` | ```
Type enumType = typeof(testEnum);
enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)[i].GetCustomAttributes(true);
```
Then you can use your choice of method to loop through the array and checking if there are any custom attributes. | How to you inspect or look for .NET attributes? | [
"",
"c#",
".net",
"attributes",
""
] |
I have the following use case, a struct with some boolean and int variables
```
struct a {
int field1;
bool field2;
bool field3;
};
```
I am refactoring this code, and writing a constructor for the struct , the problem is the default initialization of fields.
I am not criticizing any language construct here, but ideally I would want null to be part of the language itself
i mean I should be able to define for struct a as
```
a : field1(null.int), field2(null.bool), field3(null.bool) {}
```
C++ does not allow it since null.int or null.bool are not defined. Is the only way to do in C++ is
```
a: field1(-1), field2(false), field3(false) {}
``` | You can do
```
struct a {
a():field1(), field2(), field3() { }
int field1;
bool field2;
bool field3;
};
```
And all fields will be zero and false respectively. If you want to say that the fields have an indeterminate value, i'm afraid you have to use other techniques. One is to use [`boost::optional`](http://www.boost.org/doc/libs/1_35_0/libs/optional/doc/html/index.html):
```
struct a {
a():field1(int()), field2(bool()) { }
optional<int> field1;
optional<bool> field2;
optional<bool> field3;
};
```
Leaves field3 indeterminate. Access the values with `*field_name`. Test for a none value with `field == boost::none` or `if(field) { ... }`. | If you're looking for a type with values {true, false, null}, that type is not bool. However, `boost::optional<bool>` is such a type. In the same way, `boost::optional<int>` can hold any int, or no int at all.
[edit]
Or `std::optional`, since C++17. | Struct with boolean field default initialization? | [
"",
"c++",
""
] |
I'm looking for a way to redirect output in a groovy script to stderr:
```
catch(Exception e) {
println "Want this to go to stderr"
}
``` | Just off the top of my head couldn't you do a bit of self-wiring:
```
def printErr = System.err.&println
printErr("AHHH")
```
but that is a bit manual | Groovy has access to the JRE:
```
System.err.println "goes to stderr"
```
Although there may be a more Groovy-fied way... | How do I redirect output to stderr in groovy? | [
"",
"java",
"scripting",
"groovy",
""
] |
I am currently undertaking a project that involves extensive use of Java RMI and I was wondering if anyone is aware of any good resources about it.
The problem I am having with the material I am finding currently is that its usually quite out of date (like Java 1.3) and / or half complete. I would even be happy to buy a book on it but looking on Amazon all the books are like 7 years old.
So if anyone is aware of any good resources, books or good example implementations I would be very interested to hear about them. | [RMI Hello World](http://java.sun.com/javase/6/docs/technotes/guides/rmi/hello/hello-world.html) looks nice for a start. Of course it's still a simple example, so maybe [tips on RMI performance/scalability](http://www.javaperformancetuning.com/tips/j2ee_rmi.shtml) will be useful since you're already familiar with RMI. | The Java.RMI has changed very little over the years, so most of the old documentation can still be referenced. Note that one significant change is the need to compile the RMI stubs if you are using a version of Java 5.0.
Most people have moved away from RMI and have embraced [River](http://river.apache.org/) (previously called Jini) for distributed systems.
If you are still thinking of moving forward with RMI then I would suggest reading [the Oracle documentation](http://docs.oracle.com/javase/tutorial/rmi/index.html) or posting your questions on [their forums](https://forums.oracle.com/forums/forum.jspa?forumID=930).
As for books… **Java RMI** by William Grosso or **Java Network Programming** by Elliotte Harold. | Java RMI Resources | [
"",
"java",
"networking",
"network-programming",
"rmi",
""
] |
Why doesn't Java include support for unsigned integers?
It seems to me to be an odd omission, given that they allow one to write code that is less likely to produce overflows on unexpectedly large input.
Furthermore, using unsigned integers can be a form of self-documentation, since they indicate that the value which the unsigned int was intended to hold is never supposed to be negative.
Lastly, in some cases, unsigned integers can be more efficient for certain operations, such as division.
What's the downside to including these? | This is from an [interview with Gosling and others](http://www.gotw.ca/publications/c_family_interview.htm), about simplicity:
> Gosling: For me as a language designer, which I don't really count myself as these days, what "simple" really ended up meaning was could I expect J. Random Developer to hold the spec in his head. That definition says that, for instance, Java isn't -- and in fact a lot of these languages end up with a lot of corner cases, things that nobody really understands. Quiz any C developer about unsigned, and pretty soon you discover that almost no C developers actually understand what goes on with unsigned, what unsigned arithmetic is. Things like that made C complex. The language part of Java is, I think, pretty simple. The libraries you have to look up. | Reading between the lines, I think the logic was something like this:
* generally, the Java designers wanted to simplify the repertoire of data types available
* for everyday purposes, they felt that the most common need was for signed data types
* for implementing certain algorithms, unsigned arithmetic is sometimes needed, but the kind of programmers that would be implementing such algorithms would also have the knowledge to "work round" doing unsigned arithmetic with signed data types
Mostly, I'd say it was a reasonable decision. Possibly, I would have:
* made byte unsigned, or at least have provided a signed/unsigned alternatives, possibly with different names, for this one data type (making it signed is good for consistency, but when do you ever need a signed byte?)
* done away with 'short' (when did you last use 16-bit signed arithmetic?)
Still, with a bit of kludging, operations on unsigned values up to 32 bits aren't tooo bad, and most people don't need unsigned 64-bit division or comparison. | Why doesn't Java support unsigned ints? | [
"",
"java",
"language-design",
"unsigned",
"integer",
""
] |
I had a need for a certain functionality on my web apps and I use jQuery a lot, so I thought I would write a jQuery plugin. Since this is my first attempt to write a jQuery plugin, I would really like to get feedback from people, or maybe even get collaboration so others could work with me to modify/enhance my code. I thought the first step would be to setup a project page (I used google code), but now I am at the point of getting input from other developers.
I won't post my project url here because I'm not sure if Stack Overflow is an appropriate place for that (if it is, I can update this post with the URL) - but is there a website I can post to invite people to give input and maybe help with my code? Can I use Stack Overflow, or is that considered spamming or advertising?
I hesitated to even post this question because I'm not even really asking a programming question, but it does deal with the development cycle. I've searched google and I'm just not sure where the proper place is to ask people to look at my code.
Thanks in advance!
Brian | try the [google groups](http://groups.google.com/group/jquery-en) and come into the #jquery irc channel on freenode the guys there will happily look over what you have done. | If you're unsure of your code's quality and you want some good guidelines for plugin writing, check out [this plugin-authoring tutorial](http://www.learningjquery.com/2007/10/a-plugin-development-pattern) on [learningjquery.com](http://www.learningjquery.com).
I'm still wrestling with some of the concepts, but the parts I understand are great. | New jQuery plugin - What is the best way to get input and feedback? | [
"",
"javascript",
"jquery",
"plugins",
"jquery-plugins",
"new-project",
""
] |
Is Java a suitable alternative to C / C++ for realtime audio processing?
I am considering an app with ~100 (at max) tracks of audio with delay lines (30s @ 48khz), filtering (512 point FIR?), and other DSP type operations occurring on each track simultaneously.
The operations would be converted and performed in floating point.
The system would probably be a quad core 3GHz with 4GB RAM, running Ubuntu.
I have seen articles about Java being much faster than it used to be, coming close to C / C++, and now having realtime extensions as well. Is this reality? Does it require hard core coding and tuning to achieve the %50-%100 performance of C some are spec'ing?
I am really looking for a sense if this is possible and a heads up for any gotchas. | For an audio application you often have only very small parts of code where most of the time is spent.
In Java, you can always use the JNI (Java Native interface) and move your computational heavy code into a C-module (or assembly using SSE if you really need the power). So I'd say use Java and get your code working. If it turns out that you don't meet your performance goal use JNI.
90% of the code will most likely be glue code and application stuff anyway. But keep in mind that you loose some of the cross platform features that way. If you can live with that JNI will always leave you the door open for native code performance. | Java is fine for many audio applications. Contrary to some of the other posters, I find Java audio a joy to work with. Compare the API and resources available to you to the horrendous, barely documented mindf\*k that is CoreAudio and you'll be a believer. Java audio suffers from some latency issues, though for many apps this is irrelevant, and a lack of codecs. There are also plenty of people who've never bothered to take the time to write good audio playback engines(hint, never close a SourceDataLine, instead write zeros to it), and subsequently blame Java for their problems. From an API point of view, Java audio is very straightforward, very easy to use, and there is lots and lots of guidance over at [jsresources.org](http://jsresources.org/). | Java for Audio Processing is it Practical? | [
"",
"java",
"performance",
"audio",
"signal-processing",
"real-time",
""
] |
```
<{if $ishtml == true}><font face="Verdana, Arial, Helvetica" size="2"><{$contentshtml}>
<BR><BR>
<{if $settings[t_enhistory] == 1}>
<fieldset style="margin-bottom: 6px; color: #333333;FONT: 11px Verdana, Tahoma;PADDING:3px;">
<legend><{$language[tickethistory]}></legend>
<{foreach key=key value=post from=$postlist}>
<{if $post[ticketpostid] != $ticket[lastpostid]}>
<b><{$post[fullname]}></b> (<{if $post[creator] == "staff"}><{$language[thstaff]}><{elseif $post[creator] == "thirdparty"}><{$language[ththirdparty]}><{elseif $post[creator] == "recipient"}><{$language[threcipient]}><{else}><{$language[thclient]}><{/if}>) <{$language[thpostedon]}> <{$post[date]}>
<hr>
<br>
<{$post[contents]}>
<{if $ticket[hasattachments] == "1" && $post[attachmentcount] > 0}>
<BR /><BR /><fieldset style="margin-bottom: 6px; color: #333333;FONT: 11px Verdana, Tahoma;PADDING:3px;"><legend><{$language[thattachments]}></legend>
<{foreach key=attachkey value=attachment from=$post[attachments]}>
<{$attachment[filename]}> (<{$attachment[attachmentsize]}>)<BR />
<{/foreach}>
</fieldset>
<{/if}>
<br><br>
<{/if}>
<{/foreach}>
</fieldset>
<{/if}>
<fieldset style="margin-bottom: 6px; color: #333333;FONT: 11px Verdana, Tahoma;PADDING:3px;">
<legend><{$language[ticketdetails]}></legend><BR>
<{$language[articketid]}><{$ticket[fticketid]}><BR>
<{$language[ardepartment]}><{$ticket[department]}><BR>
<{$language[arpriority]}><font color="<{$priority[frcolorcode]}>"><{$ticket[priority]}></font><BR>
<{$language[arstatus]}><font color="<{$status[statuscolor]}>"><{$ticket[status]}></font><BR>
</fieldset>
</font><{else}><{$contentstext}>
<{if $settings[t_enhistory] == 1}>
<{$language[tickethistory]}>
===================
<{foreach key=key value=post from=$postlist}>
<{if $post[ticketpostid] != $ticket[lastpostid]}>
<{$post[fullname]}> (<{if $post[creator] == "staff"}><{$language[thstaff]}><{elseif $post[creator] == "thirdparty"}><{$language[ththirdparty]}><{elseif $post[creator] == "recipient"}><{$language[threcipient]}><{else}><{$language[thclient]}><{/if}>) <{$language[thpostedon]}> <{$post[date]}>
===============================================================
<{$post[contentstext]}>
<{if $ticket[hasattachments] == "1" && $post[attachmentcount] > 0}>
<{foreach key=attachkey value=attachment from=$post[attachments]}>
<{$attachment[filename]}> (<{$attachment[attachmentsize]}>)
<{/foreach}>
<{/if}>
<{/if}>
<{/foreach}>
<{/if}>
<{$language[ticketdetails]}>
===================
<{$language[articketid]}><{$ticket[fticketid]}>
<{$language[ardepartment]}><{$ticket[department]}>
<{$language[arpriority]}><{$ticket[priority]}>
<{$language[arstatus]}><{$ticket[status]}><{/if}>
``` | I'd guess it's from a [Smarty](http://www.smarty.net/crashcourse.php) template for PHP. | 100% positive it's smarty, and the typical file extension is .tpl | What programming language is this? | [
"",
"php",
"programming-languages",
"smarty",
""
] |
As the title says: Is there a difference between $str == '' and strlen($str) == 0 in PHP? Is there any real speed difference and is one better to use than the other? | Yes, there is an important difference. The == operator does [type conversion](https://www.php.net/language.operators.comparison), so it's not always going to do what you expect. For example, (0 == "") returns true. So you're making an assumption that $str is actually a string. If you're sure this is the case, or if you don't care about the conversions, then it's fine. Otherwise you should use ===, and take steps to ensure that you're comparing strings. | i find it clearer to just do
"if (!$str)" .. not sure about '==' but '!' should be able to yeld better optimization techniques, as no typecasting is ever done, and is safe for strings, arrays, bools, numbers... | Is there a difference between $str == '' and strlen($str) == 0 in PHP? | [
"",
"php",
"strlen",
""
] |
We've recently implemented Amazon S3 in our site which led us to change the way we handled images. We used to call a controller /fotos.php that would read the file from disk, record some statistics, set headers and return the contents of the file as image/jpeg.
All went OK until S3. Fotos.php now does a 302 redirect to the resource in Amazon and all is nice and working, but you can't save a image in Firefox because it sets its file type as .htm. I found this discussion on the matter, and it seems like a bug in Firefox:
<https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/207670>
Here is a URL exhibiting the problem (try to save the big image):
<http://www.viajeros.com/fotos/el-gran-lago-de-atitlan-y-sus-volcanes/132968>
Internet Explorer 6 at least tries to save it as Untitled.BMP.
Here is the snippet of code we use in fotos.php:
```
$archivo = $fotos->ObtenerPathFotoAmazon( $url, null );
if (empty($_GET['nocache'])) {
header('HTTP/1.0 302 Found');
header("Expires: ".gmdate("D, d M Y H:i:s", time()+315360000)." GMT");
header("Cache-Control: max-age=315360000");
} else {
header('HTTP/1.0 307 Temporary Redirect');
}
header('Location: ' . AWS_BUCKET_URL . $archivo);
die;
```
Do you know a workaround for this?
EDIT: We are using CloudFront as well. | try to specify the content type of the image with
`header('Content-Type: image/jpeg');` or
`header('Content-Type: image/png');`
maybe you'll have to use content disposition attachment to let PHP specify the content-type (location leave the task to the web server)
```
$archivo = $fotos->ObtenerPathFotoAmazon( $url, null );
if (empty($_GET['nocache'])) {
header('HTTP/1.0 302 Found');
header("Expires: ".gmdate("D, d M Y H:i:s", time()+315360000)." GMT");
header("Cache-Control: max-age=315360000");
}
header('Content-Type: image/jpeg');
header("Content-Disposition: attachment; filename='$archivo'");
readfile(AWS_BUCKET_URL .$archivo);
die();
``` | It's not a bug
S3 itself does not know what mimetype the object you store is. When you **PUT** the object in S3 you need to also include **Content-Type** and **Content-Disposition** headers (and whatever else you may want). When you do so, S3 will respond with those header values when you, or anyone else, **GET**'s the object | How do I fix Firefox trying to "Save image as" .htm? | [
"",
"php",
"firefox",
"redirect",
"mime-types",
""
] |
I found the following rather strange. Then again, I have mostly used closures in dynamic languages which shouldn't be suspectable to the same "bug". The following makes the compiler unhappy:
```
VoidFunction t = delegate { int i = 0; };
int i = 1;
```
It says:
> A local variable named 'i' cannot be
> declared in this scope because it
> would give a different meaning to 'i',
> which is already used in a 'child'
> scope to denote something else
So this basically means that variables declared inside a delegate will have the scope of the function declared in. Not exactly what I would have expected. I havn't even tried to call the function. At least Common Lisp has a feature where you say that a variable should have a dynamic name, if you really want it to be local. This is particularly important when creating macros that do not leak, but something like that would be helpful here as well.
So I'm wondering what other people do to work around this issue?
To clarify I'm looking for a solution where the variables I declare in the delegete doesn't interfere with variables declared *after* the delegate. And I want to still be able to capture variables declared before the delegate. | It has to be that way to allow anonymous methods (and lambdas) to use local variables and parameters scoped in the containing method.
The workarounds are to either use different names for the variable, or create an ordinary method. | The "closure" created by an anonymous function is somewhat different from that created in other dynamic languages (I'll use Javascript as an example).
```
function thing() {
var o1 = {n:1}
var o2 = {dummy:"Hello"}
return function() { return o1.n++; }
}
var fn = thing();
alert(fn());
alert(fn());
```
This little chunk of javascript will display 1 then 2. The anonymous function can access the o1 variable because it exists on its scope chain. However the anonymous function has an entirely independant scope in which it could create another o1 variable and thereby hide any other further down the scope chain. Note also that all variables in the entire chain remain, hence o2 would continue to exist holding an object reference for as long as the fn varialbe holds the function reference.
Now compare with C# anonymous functions:-
```
class C1 { public int n {get; set;} }
class C2 { public string dummy { get; set; } }
Func<int> thing() {
var o1 = new C1() {n=1};
var o2 = new C2() {dummy="Hello"};
return delegate { return o1.n++; };
}
...
Func<int> fn = thing();
Console.WriteLine(fn());
Console.WriteLine(fn());
```
In this case the anonymous function is not creating a truely independant scope any more than variable declaration in any other in-function { } block of code would be (used in a `foreach`, `if`, etc.)
Hence the same rules apply, code outside the block cannot access variables declared inside the block but you cannot reuse an identifier either.
A closure is created when the anonymous function is passed outside of the function that it was created in. The variation from the Javascript example is that only those variables actually used by the anonymous function will remain, hence in this case the object held by o2 will be available for GC as soon as thing completes, | Scope of variables in a delegate | [
"",
"c#",
"functional-programming",
"delegates",
"lambda",
"scope",
""
] |
I would like to access information on the logical drives on my computer using C#. How should I accomplish this? Thanks! | For most information, you can use the [DriveInfo](http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx) class.
```
using System;
using System.IO;
class Info {
public static void Main() {
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives) {
//There are more attributes you can use.
//Check the MSDN link for a complete example.
Console.WriteLine(drive.Name);
if (drive.IsReady) Console.WriteLine(drive.TotalSize);
}
}
}
``` | If you want to get information for **single/specific drive** at your local machine. You can do it as follow using [DriveInfo](https://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx) class:
```
//C Drive Path, this is useful when you are about to find a Drive root from a Location Path.
string path = "C:\\Windows";
//Find its root directory i.e "C:\\"
string rootDir = Directory.GetDirectoryRoot(path);
//Get all information of Drive i.e C
DriveInfo driveInfo = new DriveInfo(rootDir); //you can pass Drive path here e.g DriveInfo("C:\\")
long availableFreeSpace = driveInfo.AvailableFreeSpace;
string driveFormat = driveInfo.DriveFormat;
string name = driveInfo.Name;
long totalSize = driveInfo.TotalSize;
``` | How do I retrieve disk information in C#? | [
"",
"c#",
"disk",
""
] |
I now have it set up so that when people go to a "thank you" page after filling out a form, they go to a page that says:
```
thanks for coming <a href="<?php echo $_SERVER['HTTP_REFERER'] ?>here's a link back to where you came from</a>
```
What I want is for it to say:
```
thanks for coming <a href="<?php echo $_SERVER['HTTP_REFERER'] ?>here's a link back to <?php echo TITLE OF REFERRING PAGE ?></a>
```
Is there a simple way to do this? | The simplest way is to pass the page title as a session variable:
```
<?php
$_Session["referrerTitle"] = $pageTitle;
?>
```
If you are working with a Header file include, you may have this variable set already in the referring page.
Then in your link:
```
<p> thanks for coming <a href="<?= $_SERVER['HTTP_REFERER']"?>here's a link back to <?= $_Session["referrerTitle"] ?></a></p>
``` | Put a hidden type input in your form, with page title as value. Then use the submitted hidden value. | Basic php form help - referer title | [
"",
"php",
"http-referer",
""
] |
I love programming with .NET, especially C# 3.0, .NET 3.5 and WPF. But what I especially like is that with Mono .NET is really platform-independent.
Now I heard about the Olive Project in Mono. I couldn't find some kind of Beta.
Does it already work? Have any of you made any experiences with it?
Edit: I know about Moonlight. But I want a standalone WPF application. And **because of** Moonlight I hope WPF on Linux will become true. | You'll have better luck working with Moonlight, which targets the Silverlight API, which is a subset of full WPF.
edit: Sure, Silverlight isn't "intended" for the desktop, but there's no reason why you can't embed a silverlight engine in your application. It's been done before, such as for [the Mac NY Times Reader](http://firstlook.blogs.nytimes.com/2008/05/12/times-reader-beta-coming-this-month/)
more edit: see Miguel's post on [Standalone Silverlight Applications](http://tirania.org/blog/archive/2008/Apr-17.html) | **Update**: Since people keep upvoting this, I want to point out it is *long* since out of date. Mono got acquired by MS years ago, and their posture regarding open-source has changed, so consider this post obsolete. (As obsolete as the WPF framework itself, heh).
Mono is in a bit of an uncomfortable position when it comes to Microsoft APIs such as Winforms and WPF. A subset of the .Net technology is an ECMA standard, but free implementations of these APIs are probably on shakier legal ground. I believe this was a large factor in the covenant between Novell and Microsoft, which is good for Novell customers. But people who use Mono that aren't customers of Novell aren't protected. For this reason a lot of people in the F/OSS community look askance at Mono despite its technical merits.
For this reason, Gtk# will always be preferred, since it is truly Free. Many people consider it to be superior to Winforms anyway. As far as WPF is concerned, it will almost certainly be a low priority for Novell. They may implement it eventually, but I would expect Moonlight to be the closest you could get for the forseeable future.
---
Since posting this, Microsoft has extended their covenant to [anybody who implements the ECMA 334 & 335 standards](http://arstechnica.com/microsoft/news/2009/07/microsoft-issues-patent-promise-dispels-mono-concerns.ars). | Is WPF on Linux (already) possible? | [
"",
"c#",
".net",
"wpf",
"mono",
""
] |
This project started as a development platform because i wanted to be able to write games for mobile devices, but also being able to run and debug the code on my desktop machine too (ie, the EPOC device emulator was so bad): the platforms it currently supports are:
* Window-desktop
* WinCE
* Symbian
* iPhone
The architecture it's quite complete with 16bit 565 video framebuffer, blitters, basic raster ops, software pixel shaders, audio mixer with shaders (dsp fx), basic input, a simple virtual file system... although this thing is at it's first write and so there are places where some refactoring would be needed.
Everything has been abstracted away and the guiding principle are:
* mostly clean code, as if it was a book to just be read
* object-orientation, without sacrifying performances
* mobile centric
The idea was to open source it, but without being able to manage it, i doubt the software itself would benefit from this move.. Nevertheless, i myself have learned a lot from unmaintained projects.
So, thanking you in advance for reading all this... really, what would you do? | I would say that you should open source it.
If you do have the time, it may be helpful for other programmers who are interested in the project to know the status of the project, and what is next to do on the project. Writing a to do list may be helpful, or writing comments in the code may also help.
If you do not have the time to write up a to do list maybe somebody is willing to take the initiative on the project, find out what needs to be done.
Look at it a different way. The worst that can happen is that your work will go unnoticed, and your efforts will be lost. The best that can happen is that you will be recognized for having the foresight to start such a great project, and open sourcing it. | Throw it up on an open source website and attach a bunch of good keywords to help search engines find it. If someone's looking for it, they'll find it and be able to use it. | What would you do if you coded a C++/OO cross-platform framework and realize its laying on your disk for too much due to no time? | [
"",
"c++",
"oop",
"frameworks",
"cross-platform",
""
] |
I have to take over and improve/finish some code that transforms Java objects from a third party library into internal objects. Currently this is done through a big if-else statement along the lines of:
```
if (obj instanceOf X)
{
//code to initialize internal object
}
else if (obj instanceOf Y)
{
//code to initialize different object
}
else if (obj instanceOf Z)
{
//more init code
}
...
```
Personally I don't find this solution satisfactory; it's long and messy and to make matters worse many of the if-else blocks contain more if-else blocks dealing with subclasses and edge cases. Is there a better solution to this problem? | Create an interface like this
```
public interface Converter<S,T> {
public T convert(S source);
}
```
and implement it for each object of X,Y,Z. Then put all known converters into a Map and get happy! | While it doesn't work for edge cases, building a Map between Classes and Converters
X.getClass() -> X Converter
Y.getClass() -> Y Converter
would get you a lot closer. You'd want to also check superclasses if the leaf class is not found. | Simple/elegant way to do object to object transformation in Java? | [
"",
"java",
""
] |
Let's say you have a table for branches in your organization. Some of them are "main" branches, and others are satellite offices that roll up to a main branch. Other than this distinction, which only impacts a few things in the system, the branches are all peers and have the same attributes (address, etc.). One way to model this is in a table like:
```
CREATE TABLE Branch (
branch_id INT NOT NULL PRIMARY KEY IDENTITY(1,1),
branch_name VARCHAR(80) NOT NULL,
street VARCHAR(80) NULL,
city VARCHAR(30) NULL,
state CHAR(2) NULL,
zip CHAR(5) NULL,
is_satellite_office BIT NOT NULL DEFAULT(0),
satellite_to_branch_id INT NULL REFERENCES Branch(branch_id)
)
```
Where `is_satellite_office` = 1 iff this record is a satellite to another branch, and `satellite_to_branch_id` refers to which branch you're a satellite of, if any.
It's easy enough to put a constraint on the table so that those two columns agree on any given record:
```
CONSTRAINT [CK_Branch] CHECK
(
(is_satellite_office = 0 AND satellite_to_branch_id IS NULL)
OR (is_satellite_office = 1 AND satellite_to_branch_id IS NOT NULL)
)
```
However, what I really want is a way to guarantee that this recursion only goes **one** level deep ... that is, that if I point to a branch as my parent, it must not have a parent itself, and its value for `is_satellite_office` must be 0. Put differently, I don't really want a fully recursive tree structure, I just want to limit it to a single parent / child relationship. That's how I'm going to write the code, and if there's a way to enforce it in the database that won't perform like total crap, I'd like to.
Any ideas? I'm working on MSSQL 2005, but general (non-vendor-specific) solutions are preferred. And no triggers need apply, unless there's truly no other way to do it.
EDIT: To be clear, `satellite_to_branch_id` is the recursive pointer to another record in the same Branch table. I know that I could remove the `is_satellite_office BIT` and rely on `IsNull(satellite_to_branch_id)` to give me the same information, but I find it's a little clearer to be explicit, and besides which, that's not the gist of the question. I'm really looking for a pure SQL-constraint way to prevent recursion-depth of greater than 1. | You can bind a check constraint to the return value of a UDF. Create a UDF that takes the columns involved as input parameters, and then check your desired state using a select in the UDF. | Seems to me like a business constraint, difficult to enforce at the data definition level. I don't believe the relational algebra has any support to determine a limit for self references depth. | How to best enforce single-level recursion in a SQL table? | [
"",
"sql",
"recursion",
"constraints",
""
] |
In Ruby, methods which change the object have a bang on the end: `string.downcase!`
In c# you have to do: `foo = foo.ToLower()`
Is there a way to make an extension method like:
`foo.ConvertToLower()`
that would manipulate `foo`?
(I think the answer is no since strings are immutable and you can't do a `ref this` in an extension method.) | No, you cannot do this in an extension method. To reassign the value of a variable passed in as a parameter you have to pass it by reference using the `ref` parameter modifier, what is not allowed for extension methods.
Even if this would be possible, there might not be a variable to reassign, like in `"foo".ConvertToLower()`. | There are two ways of mutating a string instance:
* Reflection
* Unsafe code
I wouldn't recommend using either of them. Your fellow developers will hate you forever - particularly if the method is ever used to change a string which happens to be a literal... | Is there a way to make "destructive" string methods a-la Ruby? | [
"",
"c#",
"string",
"extension-methods",
""
] |
I want to use this pattern:
```
SqlCommand com = new SqlCommand(sql, con);
com.CommandType = CommandType.StoredProcedure;//um
com.CommandTimeout = 120;
//com.Connection = con; //EDIT: per suggestions below
SqlParameter par;
par = new SqlParameter("@id", SqlDbType.Int);
par.Direction = ParameterDirection.Input;
com.Parameters.Add(par);
HttpContext.Current.Cache["mycommand"] = com;
```
Obviously I don't want to run into odd problems like person A retrieving this from the cache, updating param1, person 2 getting it from the cache and updating param2 and each user running the command with a blend of the two.
And cloning the command taken out of the cache is likely more expensive that creating a new one from scratch.
How thread safe is the ASP.NET Cache? Am I missing any other potential pitfalls? Would this technique work for parameterless commands despite threading issues?
**Clarefication:** If I want to metaphorically shoot myself in the foot, how do I aim? Is there a way to lock access to objects in the cache so that access is serialized? | I should have asked how to lock an item in ASP.NET cache, instead of saying what I was intending to put in the cache.
```
lock(Cache)
{
// do something with cache that otherwise wouldn't be threadsafe
}
```
Reference: <http://www.codeguru.com/csharp/.net/net_asp/article.php/c5363> | Quite simply: don't. If you can't see that this is wrong, you need to read up more on ADO.NET. There is plenty of literature that explains the right way to do it: just create connections and commands when you need them, and make sure you dispose them properly. | How to safely and effectively cache ADO.NET commands? | [
"",
"c#",
".net",
"asp.net",
"vb.net",
"ado.net",
""
] |
Suppose I've got a table:
```
Role
----
person_id company_id financial_year
```
How can I tell the following:
1. Whether each person\_id occurs at most once per company\_id per financial\_year in this table
2. If 1. is false, which person\_id's and company\_id's and financial\_year's co-occur more than once
Edit 1: Edited to add financial\_year col
Edit 2: the RDBMS platform here happens to be MySQL, though I don't expect that this would require much vendor-specific SQL | For the first, it's generally a good idea to just have a grouping which you can then filter on if you want:
```
select
r.company_id, r.person_id, r.financial_year, count(r.person_id)
from
Role as r
group by
r.company_id, r.person_id, r.financial_year
```
For the second, you can just modify the above like so:
```
select
r.company_id, r.person_id, r.financial_year, count(r.person_id)
from
Role as r
group by
r.company_id, r.person_id, r.financial_year
having
count(r.person_id) > 1
``` | This should do what you need:
```
select left.person_id, left.company_id, left.financial_year, count(*)
from role left
inner join role right
on left.person_id = right.person_id
and left.company_id = right.company_id
and left.financial_year = right.financial_year
group by left.person_id, left.company_id, left.financial_year
```
Note that this is T-SQL (MS), but the only thing I know of that might change is the table alias syntax, as the rest is ANSI SQL. This will return one row per repeated person/company/year combination, with a count of the number of times that combination is repeated (though the count wasn't mentioned in the question, I know it can sometimes be useful). | SQL: tell whether columns are unique with respect to each other | [
"",
"sql",
""
] |
> **Possible Duplicate:**
> [What is the best way to do loops in JavaScript](https://stackoverflow.com/questions/193547/what-is-the-best-way-to-do-loops-in-javascript)
> [What’s the best way to loop through a set of elements in JavaScript?](https://stackoverflow.com/questions/157260/whats-the-best-way-to-loop-through-a-set-of-elements-in-javascript)
Any ideas? | Check this [JavaScript loop benchmarks](http://www.devpro.it/examples/loopsbench/). | What's wrong with a good old-fashioned `for` loop?
```
for( var i = 0; i < list.length; i++ ) {
// do something with list[i]
}
```
The semantics of `for...in` and `for...each...in` tend to confuse people and lead to unexpected results. | What is the Fastest way of looping over an array on javascript? | [
"",
"javascript",
"performance",
""
] |
I saw this tip in another question and was wondering if someone could explain to me how on earth this works?
```
try { return x; } finally { x = null; }
```
I mean, does the `finally` clause really execute *after* the `return` statement? How thread-unsafe is this code? Can you think of any additional hackery that can be done w.r.t. this `try-finally` hack? | No - at the IL level you can't return from inside an exception-handled block. It essentially stores it in a variable and returns afterwards
i.e. similar to:
```
int tmp;
try {
tmp = ...
} finally {
...
}
return tmp;
```
for example (using reflector):
```
static int Test() {
try {
return SomeNumber();
} finally {
Foo();
}
}
```
compiles to:
```
.method private hidebysig static int32 Test() cil managed
{
.maxstack 1
.locals init (
[0] int32 CS$1$0000)
L_0000: call int32 Program::SomeNumber()
L_0005: stloc.0
L_0006: leave.s L_000e
L_0008: call void Program::Foo()
L_000d: endfinally
L_000e: ldloc.0
L_000f: ret
.try L_0000 to L_0008 finally handler L_0008 to L_000e
}
```
This basically declares a local variable (`CS$1$0000`), places the value into the variable (inside the handled block), then after exiting the block loads the variable, then returns it. Reflector renders this as:
```
private static int Test()
{
int CS$1$0000;
try
{
CS$1$0000 = SomeNumber();
}
finally
{
Foo();
}
return CS$1$0000;
}
``` | The finally statement is executed, but the return value isn't affected. The execution order is:
1. Code before return statement is executed
2. Expression in return statement is evaluated
3. finally block is executed
4. Result evaluated in step 2 is returned
Here's a short program to demonstrate:
```
using System;
class Test
{
static string x;
static void Main()
{
Console.WriteLine(Method());
Console.WriteLine(x);
}
static string Method()
{
try
{
x = "try";
return x;
}
finally
{
x = "finally";
}
}
}
```
This prints "try" (because that's what's returned) and then "finally" because that's the new value of x.
Of course, if we're returning a reference to a mutable object (e.g. a StringBuilder) then any changes made to the object in the finally block will be visible on return - this hasn't affected the return value itself (which is just a reference). | What really happens in a try { return x; } finally { x = null; } statement? | [
"",
"c#",
".net",
"exception",
""
] |
i've got a ComboBox that i generate dynamically and fill with some items. i would like to set this control's width to the width of the longest item. how do i count the display width of some text?
edit: i'm using windows forms, but i would like to do it in asp.net as well | Depends. Are you using ASP.NET or Windows Forms or WPF? Are you using a fixed-width or proportional font?
If you're using Windows Forms, you will want to call [MeasureString()](http://www.java2s.com/Tutorial/VB/0300__2D-Graphics/Measurestringanddrawstring.htm) in order to find out how wide you want the text to be.
If you're using ASP.NET, you can do something like MeasureString(), but you don't know exactly what font is being rendered on the browser, so you can't just put that in your script. | See the **Graphics.MeasureString** method.
<http://msdn.microsoft.com/en-us/library/9bt8ty58.aspx> | comboBox width depending on longest item | [
"",
"c#",
"combobox",
""
] |
I am writing a web server application in C# and using StreamReader class to read from an underlying NetworkStream:
```
NetworkStream ns = new NetworkStream(clientSocket);
StreamReader sr = new StreamReader(ns);
String request = sr.ReadLine();
```
This code is prone to DoS attacks because if the attacker never disconnects we will never finish reading the line. Is there any way to limit the number of characters read by StreamReader.ReadLine() in .NET? | You would have to use the `Read(char[], int, int)` overload (which does limit the length) and do your own end-of-line detection; shouldn't be too tricky.
For a slightly lazy version (that uses the single-characted reading version):
```
static IEnumerable<string> ReadLines(string path, int maxLineLength)
{
StringBuilder currentLine = new StringBuilder(maxLineLength);
using (var reader = File.OpenText(path))
{
int i;
while((i = reader.Read()) > 0) {
char c = (char) i;
if(c == '\r' || c == '\n') {
yield return currentLine.ToString();
currentLine.Length = 0;
continue;
}
currentLine.Append((char)c);
if (currentLine.Length > maxLineLength)
{
throw new InvalidOperationException("Max length exceeded");
}
}
if (currentLine.Length > 0)
{
yield return currentLine.ToString();
}
}
}
``` | You might need one of `StreamReader.Read` overload:
Taken from <http://msdn.microsoft.com/en-us/library/9kstw824.aspx>
```
using (StreamReader sr = new StreamReader(path))
{
//This is an arbitrary size for this example.
char[] c = null;
while (sr.Peek() >= 0)
{
c = new char[5];
sr.Read(c, 0, c.Length);
//The output will look odd, because
//only five characters are read at a time.
Console.WriteLine(c);
}
}
```
Focus on the `sr.Read(c, 0, c.Length)` line. This reads only 5 character from stream and put in into `c` array. You may want to change 5 to value you want. | How to limit the number of characters read by StreamReader.ReadLine() in .NET? | [
"",
"c#",
"readline",
"streamreader",
"ddos",
""
] |
I am attempting to write a .NET component. The component will be dropped onto a form/user control and needs to access attributes in assemblies referenced by the components parent form/user control at design-time. Is it possible to obtain these assemblies at design time? | This is the proof of concept that I finally came up with for this question. It is not without flaws but I believe that with a little work it will function properly.
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Reflection;
using System.Windows.Forms;
namespace ReferencedAssemblies
{
public partial class GetReferencedComponents : Component, ISupportInitialize
{
private Control hostingControl;
public GetReferencedComponents(IContainer container) : this()
{
container.Add(this);
}
public GetReferencedComponents()
{
InitializeComponent();
Assemblies = new List<string>();
GetAssemblies();
}
public List<string> Assemblies { get; private set; }
[Browsable(false)]
public Control HostingControl
{
get
{
if (hostingControl == null && this.DesignMode)
{
IDesignerHost designer = this.GetService(typeof(IDesignerHost)) as IDesignerHost;
if (designer != null)
hostingControl = designer.RootComponent as Control;
}
return hostingControl;
}
set
{
if (!this.DesignMode && hostingControl != null && hostingControl != value)
throw new InvalidOperationException("Cannot set at runtime.");
else
hostingControl = value;
}
}
public void BeginInit()
{
}
public void EndInit()
{
// use ISupportInitialize.EndInit() to trigger loading assemblies at design-time.
GetAssemblies();
}
private void GetAssemblies()
{
if (HostingControl != null)
{
if (this.DesignMode)
MessageBox.Show(String.Format("Getting Referenced Assemblies from {0}", HostingControl.Name));
Assemblies.Clear();
AssemblyName[] assemblyNames = HostingControl.GetType().Assembly.GetReferencedAssemblies();
foreach (AssemblyName item in assemblyNames)
Assemblies.Add(item.Name);
}
}
}
```
}
Thanks for your answers!
Mike | [Visual Studio Automation and Extensibility](http://msdn.microsoft.com/en-us/library/ms228763(VS.80).aspx) would allow you access to that sort of information at design time, in the sense that you could have and add-in access the data at design time. | Can I iterate referenced assemblies at design-time in C#? | [
"",
"c#",
"components",
"design-time",
""
] |
As an exercise, I'm translating parts of our large and battle-hardened Delphi-framework to C#.
Included in this framework is a generic singleton parent class. Of course, implementing a singleton in C# is fairly easy (there is even a Jon Skeet article, so what more could I wish for), but our Delphi singleton has a slightly different take on the pattern: as opposed to publishing an 'instance' property/method, it has a "fake" constructor that always returns the same instance. The essential characteristic of this approach is that the *user of the singleton class doesn't know that he is dealing with a singleton*:
as far as they know, they just construct any old class and request some information from it.
I want to accomplish the same thing in C# (as an exercise, so it doesn't have to be production-quality code, evil hackery is fine), but so far I've failed.
Any suggestion to make a simple `myInstance = new MyClass();` always return the same instance is most welcome!
---
## Additional info
* We are talking a convenience-implementation of the singleton pattern, as offered by the framework. It doesn't necessarely have to be a parent-class, but it does have to assist the developers in creating their own singletons as well. Requiring them to manually redirect all their method calls to the single-instance will not make them overflow with joy. :-)
* I'm not really interested in debating whether or not this is the right way to deal with singletons, for now I'm just interested in the finer art of c#-tweaking. | As far as I know, this cannot be done for real because of how C# handles object instances. In order for a constructor to be called, the instance has to actually be created, and you can't just "return" another object from a constructor.
The best thing I can come up with (other than using a factory method) is to treat the class internally as a Singleton, and create "dummy" instances that all just point back to that original instance, when created. So for example, in your constructor you would check to see if the singleton has been initialized, and if not, would initialize it, then you would basically just proxy each instance's methods and properties back to the singleton.
In this implementation, the singleton needn't even be necessarily the same class, but you could if you wanted to keep things contained.
**Update:** One drawback of this approach is that although each instance would *behave* as a singleton, it would still have its own object reference and therefore you might also want to override `Equals()` for equality comparisons. | You would do a Proxy (Edit: As Tom points out below, the proper design pattern is Monostate):
```
public class MyClass {
MyActualClass _actual;
public MyClass() {
_actual = MyActualClass. Instance;
}
public DoStuff() {
_actual.DoStuff();
}
}
internal class MyActualClass {
private MyActualClass {
}
public DoStuff() {
...
}
MyActualClass _instance;
public static Instance {
get {
if(_instance == null)
_instance = new MyActualClass()
return _instance;
}
}
}
```
....
```
public static void Main() {
var my1 = new MyClass();
var my2 = new MyClass();
}
```
my1 != my2 but my1.DoStuff() calls the same instance of the method as my2.DoStuff()
This would be simplified even further if you programmed of an interface only.
Edit: The equality problem could partially be solved by making \_actual protected internal and overwriting MyClass.Equals(object obj) to check whether this.\_actual == obj.\_actual | Singleton with a public (single-instance) constructor | [
"",
"c#",
"design-patterns",
""
] |
I've got a simple asmx web service that just needs to log some information to a transactional database. However it is timing out for the client. The call to update the database just calls 1 stored procedure and I don't beleive it could be optimized further for better performance. I've been reduced to just logging the run using log4net and then reading the log in by a separate process that updates the database.
I was wondering if there is a better way to do this. I was wondering if there is a way to make my code do something like:
```
public bool method(...)
{
LogRun(...)
Asynchronously call method to insert transaction
return true;
}
``` | **EDIT:** I was wrong about BackgroundWorker. So I chaged it to the Thread version, tested.
If you want the work done asynchronously, you can study how to start another thread.
```
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public void Log(int foo, int bar)
{
Thread a = new Thread(new ThreadStart(delegate()
{
// Do some processing here
// For example, let it sleep for 10 secs
Thread.Sleep(10000);
}));
a.Start();
}
}
```
It would take 10 seconds for Log method to finish processing if the Thread.Sleep(10000) line is in the Log method itself. However, with *Thread a*, The Log method will return immediately after call.
Also note that, there is no easy way to guarantee the calling client if the insert operation is completed or not, with this style of asynchronous call. | One thing you may want to try is [Tracing](http://www.asp101.com/articles/robert/tracing/default.asp). | Web Service Performance Issue | [
"",
"c#",
"web-services",
"asmx",
""
] |
Suppose someone (other than me) writes the following code and compiles it into an assembly:
```
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (var transaction = conn.BeginTransaction())
{
/* Update something in the database */
/* Then call any registered OnUpdate handlers */
InvokeOnUpdate(conn);
transaction.Commit();
}
}
```
The call to InvokeOnUpdate(IDbConnection conn) calls out to an event handler that I can implement and register. Thus, in this handler I will have a reference to the IDbConnection object, but I won't have a reference to the pending transaction. Is there any way in which I can get a hold of the transaction? In my OnUpdate handler I want to execute something similar to the following:
```
private void MyOnUpdateHandler(IDbConnection conn)
{
var cmd = conn.CreateCommand();
cmd.CommandText = someSQLString;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
```
However, the call to cmd.ExecuteNonQuery() throws an InvalidOperationException complaining that
> "ExecuteNonQuery requires the command
> to have a transaction when the
> connection assigned to the command is
> in a pending local transaction. The
> Transaction property of the command
> has not been initialized".
Can I in any way enlist my SqlCommand cmd with the pending transaction? Can I retrieve a reference to the pending transaction from the IDbConnection object (I'd be happy to use reflection if necessary)? | Wow I didn't believe this at first. I am surprised that `CreateCommand()` doesn't give the command it's transaction when using local SQL Server transactions, and that the transaction is not exposed on the `SqlConnection` object. Actually when reflecting on `SqlConnection` the current transaction is not even stored in that object. In the edit bellow, I gave you some hints to track down the object via some of their internal classes.
I know you can't modify the method but could you use a TransactionScope around the method bar? So if you have:
```
public static void CallingFooBar()
{
using (var ts=new TransactionScope())
{
var foo=new Foo();
foo.Bar();
ts.Complete();
}
}
```
This will work, I tested using similar code to yours and once I add the wrapper all works fine if you can do this of course. As pointed out watch out if more then one connection is opened up within the `TransactionScope` you'll be escalated to a Distributed Transaction which unless your system is configured for them you will get an error.
Enlisting with the DTC is also several times slower then a local transaction.
# Edit
if you really want to try and use reflection, SqlConnection has a SqlInternalConnection this in turn has a Property of AvailableInternalTransaction which returns an SqlInternalTransaction, this has a property of Parent which returns the SqlTransaction you'd need. | In case anyone is interested in the reflection code to accomplish this, here it goes:
```
private static readonly PropertyInfo ConnectionInfo = typeof(SqlConnection).GetProperty("InnerConnection", BindingFlags.NonPublic | BindingFlags.Instance);
private static SqlTransaction GetTransaction(IDbConnection conn) {
var internalConn = ConnectionInfo.GetValue(conn, null);
var currentTransactionProperty = internalConn.GetType().GetProperty("CurrentTransaction", BindingFlags.NonPublic | BindingFlags.Instance);
var currentTransaction = currentTransactionProperty.GetValue(internalConn, null);
var realTransactionProperty = currentTransaction.GetType().GetProperty("Parent", BindingFlags.NonPublic | BindingFlags.Instance);
var realTransaction = realTransactionProperty.GetValue(currentTransaction, null);
return (SqlTransaction) realTransaction;
}
```
Notes:
* The types are internal and the properties private so you can't use dynamic
* internal types also prevent you from declaring the intermediate types as I did with the first ConnectionInfo. Gotta use GetType on the objects | Can I get a reference to a pending transaction from a SqlConnection object? | [
"",
"c#",
".net",
"sql-server",
"transactions",
"ado.net",
""
] |
In VB6 code, I have the following:
```
dim I as Long
I = Weekday(Now, vbFriday)
```
I want the equivalent in C#. Can any one help? | ```
public static int Weekday(DateTime dt, DayOfWeek startOfWeek)
{
return (dt.DayOfWeek - startOfWeek + 7) % 7;
}
```
This can be called using:
```
DateTime dt = DateTime.Now;
Console.WriteLine(Weekday(dt, DayOfWeek.Friday));
```
The above outputs:
```
4
```
as Tuesday is 4 days after Friday. | You mean the [DateTime.DayOfWeek](http://msdn.microsoft.com/en-us/library/system.datetime.dayofweek.aspx) property?
```
DayOfWeek dow = DateTime.Now.DayOfWeek;
``` | Equivalent of WeekDay Function of VB6 in C# | [
"",
"c#",
"datetime",
"vb6",
"dayofweek",
"weekday",
""
] |
I created a simple report and uploaded it to my report server. It looks correct on the report server, but when I set up an email subscription, the report is much narrower than it is supposed to be.
Here is what the report looks like in the designer. It looks similar when I view it on the report server: [<http://img58.imageshack.us/img58/4893/designqj3.png]>
Here is what the email looks like: [<http://img58.imageshack.us/img58/9297/emailmy8.png]>
Does anyone know why this is happening? | This issue is fixed in SQL Server 2005 SP3 (it is part of cumulitive update package build 3161)
Problem issue described below.
<http://support.microsoft.com/kb/935399>
Basically Full Outlook 2007 Client Uses MS Word HTML Rendering Engine (Which Makes Web Archive Report Looked Jacked Up).
NOTE: Web Outlook 2007 Client Uses IE HTML Rendering Engine (Which makes Web Archive Report Look Okay).
We have installed the patch on DB housing Reporting Services and it does fix the issue. Emails look all nice and fancy now. | I notice that the screenshots show Outlook 2007. Perhaps you're not aware that Microsoft somewhat hobbled the HTML capabilities of Outlook in 2007, and now it uses the Word HTML engine, and not the more advanced Internet Explorer one? Might this explain the lacklustre appearance?
<http://www.sitepoint.com/blogs/2007/01/10/microsoft-breaks-html-email-rendering-in-outlook/> | SQL Reporting Services: Why does my report shrink when it's emailed? | [
"",
"sql",
"email",
"reporting-services",
""
] |
I have this `If` condition in VB6
```
If ( X AND ( 2 ^ Y)) Then
a = a + " 1"
Else
a = a + " 0"
```
I want the same equivalent in C#
I tried doing like
```
if ( X && ( 2 ^ Y)) // ERROR: && can not be used between int to int
a = a + "1";
else
a = a + "0";
```
but this thing is giving me an error.
Here is my complete VB code that I want to convert into C#
```
For i = 7 To 0 Step -1
If intNumber And (2 ^ i) Then ' Use the logical "AND" operator.
bin = bin + "1"
Else
bin = bin + "0"
End If
Next
```
In above code `intNumber` could be any number. | **Note**: This answer has been heavily edited due to lack of information in original question. This version of the answer is now based on the updated question with enough information. For history, check the edit log.
Two things:
* `&&` is used between Boolean expressions, to determine the logical AND-value
* `^` in C# means XOR, not raised-to-the-power-of. You didn't ask a question about this but it was inevitable that you discovered that `^` didn't appear to be doing its job.
The `&&` is easily handled, since it can be replaced with a single `&` instead, which has a dual meaning, depending on context. Either it is a full-evaluation logical AND operator (`&&` is a short-circuited one), or it is a bitwise operator, which is what you want here.
The `^` is different though. The most direct equivalent is [Math.Pow](http://msdn.microsoft.com/en-us/library/system.math.pow.aspx), but in this case, a better alternative is available, bit-shift.
The case of `2^X` can be thought of as *shift the 1-bit X positions to the left*, and *shift bits to the left* has its own operator, the `<<` operator.
So `2^X` can be replaced with `1 << X`.
In this context, here's what you want for your inner-most if-statement:
```
if ((intNumber & (1 << index)) != 0)
a = a + "1";
else
a = a + "0";
```
Plug that into a loop like you have in your bottom example, and you get this:
```
for (Int32 index = 7; index >= 0; index--)
if ((intNumber & (1 << index)) != 0)
bin = bin + "1";
else
bin = bin + "0";
```
Now, concatenating strings like this generates GC pressure, so you should probably either store these digits into a `Char` array, and construct the string afterwards, or use the StringBuilder class. Otherwise you're going to build up 8 (from my example) differently sized strings, and you're only going to use and keep the last one. Depending on circumstances this might not pose a problem, but if you call this code many times, it will add up.
Here's a better version of the final code:
```
Char[] digits = new Char[8]; // change if you want more/fewer digits
for (Int32 index = 0; index < digits.Length; index++)
if ((intNumber & (1 << index)) != 0)
digits[digits.Length - 1 - index] = '1';
else
digits[digits.Length - 1 - index] = '0';
bin = new String(digits);
```
However, and here's the kicker. There is already a way to convert an Int32 value to a string full of binary digits in .NET, and it's the Convert.ToString method. The only difference is that it doesn't add any leading zeros, so we have to do that ourselves.
So, here's the final code you should be using:
```
String bin = Convert.ToString(intNumber, 2).PadLeft(8, '0');
```
This replaces the whole loop. | It looks like it is using VB to do bitwise AND in this case, so perhaps:
```
if ( (1 & ( 2 ^ 1)) != 0)
```
However, this is a constant! Are you sure there isn't a variable in there somewhere?
2 ^ 1 is 3; 1 & 3 is 1; so this would always be true
(at least, under C#, where ^ is XOR; I'm told that in VB ^ is POWER, so 2 ^ 1 is 2; 1 & 2 is 0; so this would always be false...) | Equivalent of `IF ( X AND ( 2 ^ Y ) ) Then` in C# | [
"",
"c#",
"vb6",
"operators",
"translation",
""
] |
Here's a problem that I've been running into lately - a misconfigured apache on a webhost. This means that all scripts that rely on `$_SERVER['DOCUMENT_ROOT']` break. The easiest workaround that I've found is just set the variable in some global include files that is shared, but it's a pain not to forget it. My question is, how do I determine the correct document root programatically?
For example, on one host, the setup is like this:
```
$_SERVER['DOCUMENT_ROOT'] == '/htdocs'
```
The real document roots are:
```
test.example.com -> /data/htdocs/example.com/test
www.example.com -> /data/htdocs/example.com/www
```
And I'd like a script that's run from `www.example.com/blog/` (on the path `/data/htdocs/example.com/www/blog`) to get the correct value of `/data/htdocs/example.com/www`.
On another host, the setup is a bit different:
```
$_SERVER['DOCUMENT_ROOT'] == '/srv'
test.example.com -> /home/virtual_web/example.com/public_html/test
www.example.com -> /home/virtual_web/example.com/public_html/www
```
Is there any solution to this? Or is the only way simply not to ever rely on `$_SERVER['DOCUMENT_ROOT']` and fix all the software that I'm running on my sites? Fixing this on the hosting's side doesn't seem to be an option, I've yet to encounter a host where this is was configured correctly. The best I got was a document root pointing to www.example.com, which was at least inside open\_basedir - they used yet another naming scheme, www.example.com would point to `/u2/www/example_com/data/www/`. | Based on <http://www.helicron.net/php/>:
```
$localpath=getenv("SCRIPT_NAME");
$absolutepath=getenv("SCRIPT_FILENAME");
$_SERVER['DOCUMENT_ROOT']=substr($absolutepath,0,strpos($absolutepath,$localpath));
```
I had to change the basename/realpath trick because it returned an empty string on my host. Instead, I use `SCRIPT_FILENAME`. This probably won't work on IIS anymore (but the original scripts that used the $\_SERVER variable probably wouldn't either). | In PHP5 there is the magic constant `__FILE__` that contains the absolute path of the file in which it appears. You can use it in combination with dirname to calculate the document root.
You can put a statement like the following one in a config file
```
define ('DOCUMENT_ROOT', dirname(__FILE__));
```
this should do the trick | How to programmatically determine the document root in PHP? | [
"",
"php",
"apache",
"configuration",
""
] |
I have some configuration data that I'd like to model in code as so:
```
Key1, Key2, Key3, Value
null, null, null, 1
1, null, null, 2
9, null, null, 21
1, null, 3, 3
null, 2, 3, 4
1, 2, 3, 5
```
With this configuration set, I then need to do lookups on bazillion (give or take) {Key1, Key2, Key3} tuples to get the "effective" value. The effective value to use is based on a Key/Priority sum whereby in this example:
```
Key1 - Priority 10
Key2 - Priority 7
Key3 - Priority 5
```
So a specifc query which has a config entry on Key1=null, Key2=match, and Key3=match beats out one that has Key1=match, Key2=null, and Key3=null since Key2+Key3 priority > Key1 priority... That make sense?!
```
given a key of {1, 2, 3} the value should be 5.
given a key of {3, 2, 3} the value should be 4.
given a key of {8, 10, 11} the value should be 1.
given a key of {1, 10, 11} the value should be 2.
given a key of {9, 2, 3} the value should be 4.
given a key of {8, 2, 3} the value should be 4.
given a key of {9, 3, 3} the value should be 21.
```
Is there an easy way to model this data structure and lookup algorithm that is generic in that the # and types of keys is variable, and the "truth table" (the ordering of the lookups) can be defined dynamically? The types being generics instead of ints would be perfect (floats, doubles, ushorts, etc), and making it easy to expand to n number of keys is important too!
Estimated "config" table size: 1,000 rows, Estimated "data" being looked up: 1e14
That gives an idea about the type of performance that would be expected.
I'm looking for ideas in C# or something that can translate to C# easily. | I'm assuming that there are few rules, and a large number of items that you're going to check against the rules. In this case, it might be worth the expense of memory and up-front time to pre-compute a structure that would help you find the object faster.
The basic idea for this structure would be a tree such that at depth i, you would follow the ith element of the rule, or the null branch if it's not found in the dictionary.
To build the tree, I would build it recursively. Start with the root node containing all possible rules in its pool. The process:
* Define the current value of each rule in the pool as the score of the current rule given the path taken to get to the node, or -infinity if it is impossible to take the path. For example, if the current node is at the '1' branch of the root, then the rule {null, null, null, 1} would have a score of 0, and the rule {1, null, null, 2} would have a score 10
* Define the maximal value of each rule in the pool as its current score, plus the remaining keys' score. For example, if the current node is at the '1' branch of the root, then the rule {null, 1, 2, 1} would have a score of 12 (0 + 7 + 5), and the rule {1, null, null, 2} would have a score 10 (10 + 0 + 0).
* Remove the elements from the pool that have a maximal value lower than the highest current value in the pool
* If there is only one rule, then make a leaf with the rule.
* If there are multiple rules left in the pool, and there are no more keys then ??? (this isn't clear from the problem description. I'm assuming taking the highest one)
* For each unique value of the (i+1)th key in the current pool, and null, construct a new tree from the current node using the current pool.
As a final optimization check, I would check if all children of a node are leaves, and if they all contain the same rule, then make the node a leaf with that value.
given the following rules:
```
null, null, null = 1
1, null, null = 2
9, null, null = 21
1, null, 3 = 3
null, 2, 3 = 4
1, 2, 3 = 5
```
an example tree:
```
key1 key2 key3
root:
|----- 1
| |----- 2 = 5
| |-----null
| |----- 3 = 3
| |-----null = 2
|----- 9
| |----- 2
| | |----- 3 = 4
| | |-----null = 21
| |-----null = 21
|-----null
|----- 2 = 4
|-----null = 1
```
If you build the tree up in this fashion, starting from the highest value key first, then you can possibly prune out a lot of checks against later keys.
Edit to add code:
```
class Program
{
static void Main(string[] args)
{
Config config = new Config(10, 7, 5)
{
{ new int?[]{null, null, null}, 1},
{ new int?[]{1, null, null}, 2},
{ new int?[]{9, null, null}, 21},
{ new int?[]{1, null, 3}, 3 },
{ new int?[]{null, 2, 3}, 4 },
{ new int?[]{1, 2, 3}, 5 }
};
Console.WriteLine("5 == {0}", config[1, 2, 3]);
Console.WriteLine("4 == {0}", config[3, 2, 3]);
Console.WriteLine("1 == {0}", config[8, 10, 11]);
Console.WriteLine("2 == {0}", config[1, 10, 11]);
Console.WriteLine("4 == {0}", config[9, 2, 3]);
Console.WriteLine("21 == {0}", config[9, 3, 3]);
Console.ReadKey();
}
}
public class Config : IEnumerable
{
private readonly int[] priorities;
private readonly List<KeyValuePair<int?[], int>> rules =
new List<KeyValuePair<int?[], int>>();
private DefaultMapNode rootNode = null;
public Config(params int[] priorities)
{
// In production code, copy the array to prevent tampering
this.priorities = priorities;
}
public int this[params int[] keys]
{
get
{
if (keys.Length != priorities.Length)
{
throw new ArgumentException("Invalid entry - wrong number of keys");
}
if (rootNode == null)
{
rootNode = BuildTree();
//rootNode.PrintTree(0);
}
DefaultMapNode curNode = rootNode;
for (int i = 0; i < keys.Length; i++)
{
// if we're at a leaf, then we're done
if (curNode.value != null)
return (int)curNode.value;
if (curNode.children.ContainsKey(keys[i]))
curNode = curNode.children[keys[i]];
else
curNode = curNode.defaultChild;
}
return (int)curNode.value;
}
}
private DefaultMapNode BuildTree()
{
return new DefaultMapNode(new int?[]{}, rules, priorities);
}
public void Add(int?[] keys, int value)
{
if (keys.Length != priorities.Length)
{
throw new ArgumentException("Invalid entry - wrong number of keys");
}
// Again, copy the array in production code
rules.Add(new KeyValuePair<int?[], int>(keys, value));
// reset the tree to know to regenerate it.
rootNode = null;
}
public IEnumerator GetEnumerator()
{
throw new NotSupportedException();
}
}
public class DefaultMapNode
{
public Dictionary<int, DefaultMapNode> children = new Dictionary<int,DefaultMapNode>();
public DefaultMapNode defaultChild = null; // done this way to workaround dict not handling null
public int? value = null;
public DefaultMapNode(IList<int?> usedValues, IEnumerable<KeyValuePair<int?[], int>> pool, int[] priorities)
{
int bestScore = Int32.MinValue;
// get best current score
foreach (KeyValuePair<int?[], int> rule in pool)
{
int currentScore = GetCurrentScore(usedValues, priorities, rule);
bestScore = Math.Max(bestScore, currentScore);
}
// get pruned pool
List<KeyValuePair<int?[], int>> prunedPool = new List<KeyValuePair<int?[], int>>();
foreach (KeyValuePair<int?[], int> rule in pool)
{
int maxScore = GetCurrentScore(usedValues, priorities, rule);
if (maxScore == Int32.MinValue)
continue;
for (int i = usedValues.Count; i < rule.Key.Length; i++)
if (rule.Key[i] != null)
maxScore += priorities[i];
if (maxScore >= bestScore)
prunedPool.Add(rule);
}
// base optimization case, return leaf node
// base case, always return same answer
if ((prunedPool.Count == 1) || (usedValues.Count == prunedPool[0].Key.Length))
{
value = prunedPool[0].Value;
return;
}
// add null base case
AddChild(usedValues, priorities, prunedPool, null);
foreach (KeyValuePair<int?[], int> rule in pool)
{
int? branch = rule.Key[usedValues.Count];
if (branch != null && !children.ContainsKey((int)branch))
{
AddChild(usedValues, priorities, prunedPool, branch);
}
}
// if all children are the same, then make a leaf
int? maybeOnlyValue = null;
foreach (int v in GetAllValues())
{
if (maybeOnlyValue != null && v != maybeOnlyValue)
return;
maybeOnlyValue = v;
}
if (maybeOnlyValue != null)
value = maybeOnlyValue;
}
private static int GetCurrentScore(IList<int?> usedValues, int[] priorities, KeyValuePair<int?[], int> rule)
{
int currentScore = 0;
for (int i = 0; i < usedValues.Count; i++)
{
if (rule.Key[i] != null)
{
if (rule.Key[i] == usedValues[i])
currentScore += priorities[i];
else
return Int32.MinValue;
}
}
return currentScore;
}
private void AddChild(IList<int?> usedValues, int[] priorities, List<KeyValuePair<int?[], int>> prunedPool, Nullable<int> nextValue)
{
List<int?> chainedValues = new List<int?>();
chainedValues.AddRange(usedValues);
chainedValues.Add(nextValue);
DefaultMapNode node = new DefaultMapNode(chainedValues, prunedPool, priorities);
if (nextValue == null)
defaultChild = node;
else
children[(int)nextValue] = node;
}
public IEnumerable<int> GetAllValues()
{
foreach (DefaultMapNode child in children.Values)
foreach (int v in child.GetAllValues())
yield return v;
if (defaultChild != null)
foreach (int v in defaultChild.GetAllValues())
yield return v;
if (value != null)
yield return (int)value;
}
public void PrintTree(int depth)
{
if (value == null)
Console.WriteLine();
else
{
Console.WriteLine(" = {0}", (int)value);
return;
}
foreach (KeyValuePair<int, DefaultMapNode> child in children)
{
for (int i=0; i<depth; i++)
Console.Write(" ");
Console.Write(" {0} ", child.Key);
child.Value.PrintTree(depth + 1);
}
for (int i = 0; i < depth; i++)
Console.Write(" ");
Console.Write("null");
defaultChild.PrintTree(depth + 1);
}
}
``` | EDIT: This code is apparently not what's required, but I'm leaving it as it's interesting anyway. It basically treats Key1 as taking priority, then Key2, then Key3 etc. I don't really understand the intended priority system yes, but when I do I'll add an answer for that.
I would suggest a triple layer of Dictionaries - each layer has:
```
Dictionary<int, NextLevel> matches;
NextLevel nonMatch;
```
So at the first level you'd look up Key1 - if that matches, that gives you the next level of lookup. Otherwise, use the next level which corresponds with "non-match".
Does that make any sense? Here's some sample code (including the example you gave). I'm not entirely happy with the actual implementation, but the idea behind the data structure is sound, I think:
```
using System;
using System.Collections;
using System.Collections.Generic;
public class Test
{
static void Main()
{
Config config = new Config
{
{ null, null, null, 1 },
{ 1, null, null, 2 },
{ 1, null, 3, 3 },
{ null, 2, 3, 4 },
{ 1, 2, 3, 5 }
};
Console.WriteLine(config[1, 2, 3]);
Console.WriteLine(config[3, 2, 3]);
Console.WriteLine(config[9, 10, 11]);
Console.WriteLine(config[1, 10, 11]);
}
}
// Only implement IEnumerable to allow the collection initializer
// Not really implemented yet - consider how you might want to implement :)
public class Config : IEnumerable
{
// Aargh - death by generics :)
private readonly DefaultingMap<int,
DefaultingMap<int, DefaultingMap<int, int>>> map
= new DefaultingMap<int, DefaultingMap<int, DefaultingMap<int, int>>>();
public int this[int key1, int key2, int key3]
{
get
{
return map[key1][key2][key3];
}
}
public void Add(int? key1, int? key2, int? key3, int value)
{
map.GetOrAddNew(key1).GetOrAddNew(key2)[key3] = value;
}
public IEnumerator GetEnumerator()
{
throw new NotSupportedException();
}
}
internal class DefaultingMap<TKey, TValue>
where TKey : struct
where TValue : new()
{
private readonly Dictionary<TKey, TValue> mapped = new Dictionary<TKey, TValue>();
private TValue unmapped = new TValue();
public TValue GetOrAddNew(TKey? key)
{
if (key == null)
{
return unmapped;
}
TValue ret;
if (mapped.TryGetValue(key.Value, out ret))
{
return ret;
}
ret = new TValue();
mapped[key.Value] = ret;
return ret;
}
public TValue this[TKey key]
{
get
{
TValue ret;
if (mapped.TryGetValue(key, out ret))
{
return ret;
}
return unmapped;
}
}
public TValue this[TKey? key]
{
set
{
if (key != null)
{
mapped[key.Value] = value;
}
else
{
unmapped = value;
}
}
}
}
``` | How to build a "defaulting map" data structure | [
"",
"c#",
".net",
"algorithm",
""
] |
I have a subclass with an over-ridden method that I know always returns a particular subtype of the return type declared in the base class. If I write the code this way, it won't compile. Since that probably doesn't make sense, let me give a code example:
```
class BaseReturnType { }
class DerivedReturnType : BaseReturnType { }
abstract class BaseClass {
public abstract BaseReturnType PolymorphicMethod();
}
class DerivedClass : BaseClass {
// Compile Error: return type must be 'BaseReturnType' to match
// overridden member 'BaseClass.PolymorphicMethod()'
public override DerivedReturnType PolymorphicMethod() {
return new DerivedReturnType();
}
}
```
Is there any way to accomplish this in C#? If not, what's the best way to achieve something similar? And why isn't it allowed? It doesn't seem to allow any logical inconsistency, since any object returned from the over-ridden method still `is BaseReturnType`. Maybe there is something I hadn't considered though. Or maybe the reason is technological or historical. | Unfortunately no, covariant return types aren't supported in C# for method overriding. (Ditto contravariant parameter types.)
If you're implementing an interface you can implement it explicitly with the "weak" version and also provide a public version with the stronger contract. For simple overriding of a parent class, you don't have this luxury I'm afraid :(
(EDIT: Marc has a [reasonable solution](https://stackoverflow.com/questions/421851/how-to-return-subtype-in-overridden-method-of-subclass-in-c#421881) - although it's pretty ugly, and method hiding is generally a bad thing for readability. No offence meant, Marc ;)
I *believe* this is actually a CLR restriction, not just a language one - but I could well be wrong.
(As a matter of history, Java (the language) had the same restriction until 1.5 - but it gained covariance at the same time as generics.) | You could make the class generic if that doesn't bothers you:
```
class BaseReturnType { }
class DerivedReturnType : BaseReturnType { }
abstract class BaseClass<T> where T : BaseReturnType
{
public abstract T PolymorphicMethod();
}
class DerivedClass : BaseClass<DerivedReturnType>
{
// Error: return type must be 'BaseReturnType' to match
// overridden member 'BaseClass.PolymorphicMethod()'
public override DerivedReturnType PolymorphicMethod()
{
return new DerivedReturnType();
}
}
``` | How to return subtype in overridden method of subclass in C#? | [
"",
"c#",
"inheritance",
""
] |
i am new to .net 3.5.
I have a collection of items:
```
IList<Model> models;
```
where
```
class Model
{
public string Name
{
get;
private set;
}
}
```
I would like to get the element, which has the longest name's length.
I tried
```
string maxItem = models.Max<Model>(model => model.Name.Length);
```
but it of course returns the maximum length (and I need a `Model` object). I know there is a way of doing this using the extension methods but I don't know how. | This is how I got it to work. Maybe there's a better way, I'm not sure:
```
decimal de = d.Max(p => p.Name.Length);
Model a = d.First(p => p.Name.Length == de);
``` | There isn't a built-in way of doing this, unfortunately - but it's really easy to write an extension method to do it.
It was in [one of my very first blog posts](http://msmvps.com/blogs/jon_skeet/archive/2005/10/02/a-short-case-study-in-linq-efficiency.aspx), in fact... note that there's a better implementation in one of the comments. I'll move it into the body if I get time.
EDIT: Okay, I have a slightly abbreviated version - it just returns the maximal element, using the given selector. No need to do a projection as well - do that once afterwards if you need to. Note that you could remove the constraint on `TValue` and use `Comparer<TValue>.Default` instead, or have an overload which allows the comparison to be specified as another parameter.
```
public static TSource MaxBy<TSource, TValue>(this IEnumerable<TSource> source,
Func<TSource, TValue> selector)
where TValue : IComparable<TValue>
{
TValue maxValue = default(TValue);
TSource maxElement = default(TSource);
bool gotAny = false;
foreach (TSource sourceValue in source)
{
TValue value = selector(sourceValue);
if (!gotAny || value.CompareTo(maxValue) > 0)
{
maxValue = value;
maxElement = sourceValue;
gotAny = true;
}
}
if (!gotAny)
{
throw new InvalidOperationException("source is empty");
}
return maxElement;
}
```
Sample use: (note type inference):
```
string maxName = models.MaxBy(model => model.Name.Length).Name;
``` | Select the maximal item from collection, by some criterion | [
"",
"c#",
".net-3.5",
"extension-methods",
""
] |
My question is, if an interface that is implemented implicitly by extending a class that already implements it, should be explicitly implemented by the class, if the class wants to advertise the fact, that it fulfills the contract of that interface.
For instance, if you want to write a class, that fulfills the contract of the interface `java.util.List`. You implement this, extending the class `java.util.AbstractList`, that already implements the interface `List`. Do you explicitly declare, that you implement List?
```
public class MyList extends AbstractList implements List
```
Or do you save typing by using the implicit way?
```
public class MyList extends AbstractList
```
Which way is considered better style? What reasons do you have to prefer one way or another? In which situations you would prefer way 1 or way 2? | I asked [this same question long ago on my blog](http://tech.puredanger.com/2007/03/30/java-inheritance-question/). There is a long discussion there as well if you're interested in seeing some other people's thoughts. It's interesting to note that both strategies are taken within the JDK.
I ultimately decided that a hard rule on this didn't make sense - it's better to use best judgement as to what I wanted to communicate. | Avoid redundancy. Use method 2.
Use @Override for overrides. | Should an interface that is inherited from base-class be implemented explicitly in subclass? | [
"",
"java",
"interface",
"contract",
""
] |
I am trying to write a generic Parse method that converts and returns a strongly typed value from a NamedValueCollection. I tried two methods but both of these methods are going through boxing and unboxing to get the value. Does anyone know a way to avoid the boxing? If you saw this in production would you not like it, how bad is it for performance?
Usuage:
```
var id = Request.QueryString.Parse<int>("id");
```
Attempt #1:
```
public static T Parse<T>(this NameValueCollection col, string key)
{
string value = col[key];
if (string.IsNullOrEmpty(value))
return default(T);
if (typeof(T) == typeof(int))
{
//return int.Parse(value); // cannot convert int to T
//return (T)int.Parse(value); // cannot convert int to T
return (T)(object)int.Parse(value); // works but boxes
}
if (typeof(T) == typeof(long))
{
return (T)(object)long.Parse(value); // works but boxes
}
...
return default(T);
}
```
Attempt #2 (using reflection):
```
public static T Parse<T>(this NameValueCollection col, string key)
{
string value = col[key];
if (string.IsNullOrEmpty(value))
return default(T);
try
{
var parseMethod = typeof(T).GetMethod("Parse", new Type[] { typeof(string) });
if (parseMethod == null)
return default(T);
// still boxing because invoke returns an object
var parsedVal = parseMethod.Invoke(null, new object[] { value });
return (T)parsedVal;
}
// No Proper Parse Method found
catch(AmbiguousMatchException)
{
}
return default(T);
}
``` | I think you are over estimating the impact of the boxing/unboxing. The parse method will have a much bigger overhead (string parsing), dwarfing the boxing overhead. Also all the if statements will have a bigger impact. Reflection has the biggest impact of all.
I'd would not like to see this kind of code in production, as there is a cleaner way of doing it. The major problem I have with it is the large number of if statements you will need to cover all cases and the fact that someone could pass any old type to it.
What I would do is write a parse function for each type I want to parse (ie ParseInt()). It's clearer and it is well defined what the function will try to do. Also with short static methods, the compiler is more likely to inline them, saving a function call.
I think this is a bad application of generics, any particular reason for doing it this way? | ```
public static T Parse<T>(this NameValueCollection col, string key)
{
return (T)Convert.ChangeType(col[key], typeof(T));
}
```
I'm not entirely sure of ChangeType boxes or not (I guess reading the docs would tell me, but I'm pressed for time right now), but at least it gets rid of all that type-checking. The boxing overhead is not very high, though, so I wouldn't worry too much about it. If you're worried about run-time type consistency, I'd write the function as:
```
public static T Parse<T>(this NameValueCollection col, string key)
{
T value;
try
{
value = (T)Convert.ChangeType(col[key], typeof(T));
}
catch
{
value = default(T);
}
return value;
}
```
This way the function won't bomb if the value cannot be converted for whatever reason. That means, of course, that you'll have to check the returned value (which you'd have to do anyway since the user can edit the querystring). | Generic Parse Method without Boxing | [
"",
"c#",
"generics",
"reflection",
""
] |
I can never remember how I do this because it comes up so infrequently for me. But in C or C++, what is the best way to read a character from standard input without waiting for a newline (press enter).
Also ideally it wouldn't echo the input character to the screen. I just want to capture keystrokes with out effecting the console screen. | That's not possible in a portable manner in pure C++, because it depends too much on the terminal used that may be connected with `stdin` (they are usually line buffered). You can, however use a library for that:
1. conio available with Windows compilers. Use the `_getch()` function to give you a character without waiting for the Enter key. I'm not a frequent Windows developer, but I've seen my classmates just include `<conio.h>` and use it. See [`conio.h`](http://en.wikipedia.org/wiki/Conio.h) at Wikipedia. It lists `getch()`, which is declared deprecated in Visual C++.
2. curses available for Linux. Compatible curses implementations are available for Windows too. It has also a `getch()` function. (try `man getch` to view its manpage). See [Curses](http://en.wikipedia.org/wiki/Curses_%28programming_library%29) at Wikipedia.
I would recommend you to use curses if you aim for cross platform compatibility. That said, I'm sure there are functions that you can use to switch off line buffering (I believe that's called "raw mode", as opposed to "cooked mode" - look into `man stty`). Curses would handle that for you in a portable manner, if I'm not mistaken. | On Linux (and other unix-like systems) this can be done in following way:
```
#include <unistd.h>
#include <termios.h>
char getch() {
char buf = 0;
struct termios old = {0};
if (tcgetattr(0, &old) < 0)
perror("tcsetattr()");
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSANOW, &old) < 0)
perror("tcsetattr ICANON");
if (read(0, &buf, 1) < 0)
perror ("read()");
old.c_lflag |= ICANON;
old.c_lflag |= ECHO;
if (tcsetattr(0, TCSADRAIN, &old) < 0)
perror ("tcsetattr ~ICANON");
return (buf);
}
```
Basically you have to turn off canonical mode (and echo mode to suppress echoing). | Capture characters from standard input without waiting for enter to be pressed | [
"",
"c++",
"c",
"inputstream",
""
] |
I have two characters displayed in a game I am writing, the player and the enemy. defined as such:
```
public void player(Graphics g) {
g.drawImage(plimg, x, y, this);
}
public void enemy(Graphics g) {
g.drawImage(enemy, 200, 200, this);
}
```
Then called with:
```
player(g);
enemy(g);
```
I am able to move player() around with the keyboard, but I am at a loss when trying to detect a collision between the two. A lot of people have said to use Rectangles, but being a beginner I cannot see how I would link this into my existing code. Can anyone offer some advice for me? | I think your problem is that you are not using good OO design for your player and enemies. Create two classes:
```
public class Player
{
int X;
int Y;
int Width;
int Height;
// Getters and Setters
}
public class Enemy
{
int X;
int Y;
int Width;
int Height;
// Getters and Setters
}
```
Your Player should have X,Y,Width,and Height variables.
Your enemies should as well.
In your game loop, do something like this (C#):
```
foreach (Enemy e in EnemyCollection)
{
Rectangle r = new Rectangle(e.X,e.Y,e.Width,e.Height);
Rectangle p = new Rectangle(player.X,player.Y,player.Width,player.Height);
// Assuming there is an intersect method, otherwise just handcompare the values
if (r.Intersects(p))
{
// A Collision!
// we know which enemy (e), so we can call e.DoCollision();
e.DoCollision();
}
}
```
To speed things up, don't bother checking if the enemies coords are offscreen. | First, use the bounding boxes as described by [Jonathan Holland](https://stackoverflow.com/questions/335600/collision-detection-between-two-images-in-java#335632) to find if you may have a collision.
From the (multi-color) sprites, create black and white versions. You probably already have these if your sprites are transparent (i.e. there are places which are inside the bounding box but you can still see the background). These are "masks".
Use `Image.getRGB()` on the mask to get at the pixels. For each pixel which isn't transparent, set a bit in an integer array (`playerArray` and `enemyArray` below). The size of the array is `height` if `width <= 32` pixels, `(width+31)/32*height` otherwise. The code below is for `width <= 32`.
If you have a collision of the bounding boxes, do this:
```
// Find the first line where the two sprites might overlap
int linePlayer, lineEnemy;
if (player.y <= enemy.y) {
linePlayer = enemy.y - player.y;
lineEnemy = 0;
} else {
linePlayer = 0;
lineEnemy = player.y - enemy.y;
}
int line = Math.max(linePlayer, lineEnemy);
// Get the shift between the two
x = player.x - enemy.x;
int maxLines = Math.max(player.height, enemy.height);
for ( line < maxLines; line ++) {
// if width > 32, then you need a second loop here
long playerMask = playerArray[linePlayer];
long enemyMask = enemyArray[lineEnemy];
// Reproduce the shift between the two sprites
if (x < 0) playerMask << (-x);
else enemyMask << x;
// If the two masks have common bits, binary AND will return != 0
if ((playerMask & enemyMask) != 0) {
// Contact!
}
}
```
Links: [JGame](http://www.13thmonkey.org/~boris/jgame/), [Framework for Small Java Games](http://vredungmand.dk/programming/sjg/) | Collision Detection between two images in Java | [
"",
"java",
"collision-detection",
""
] |
I have been running an UPDATE on a table containing 250 million rows with 3 index'; this UPDATE uses another table containing 30 million rows. It has been running for about 36 hours now. I am wondering if their is a way to find out how close it is to being done for if it plans to take a million days to do its thing, I will kill it; yet if it only needs another day or two, I will let it run. Here is the command-query:
```
UPDATE pagelinks SET pl_to = page_id
FROM page
WHERE
(pl_namespace, pl_title) = (page_namespace, page_title)
AND
page_is_redirect = 0
;
```
The EXPLAIN is not the issue here and I only mention the big table's having multiple indexes in order to somewhat justify how long it takes to UPDATE it. But here is the EXPLAIN anyway:
```
Merge Join (cost=127710692.21..135714045.43 rows=452882848 width=57)
Merge Cond: (("outer".page_namespace = "inner".pl_namespace) AND ("outer"."?column4?" = "inner"."?column5?"))
-> Sort (cost=3193335.39..3219544.38 rows=10483593 width=41)
Sort Key: page.page_namespace, (page.page_title)::text
-> Seq Scan on page (cost=0.00..439678.01 rows=10483593 width=41)
Filter: (page_is_redirect = 0::numeric)
-> Sort (cost=124517356.82..125285665.74 rows=307323566 width=46)
Sort Key: pagelinks.pl_namespace, (pagelinks.pl_title)::text"
-> Seq Scan on pagelinks (cost=0.00..6169460.66 rows=307323566 width=46)
```
Now I also sent a parallel query-command in order to DROP one of *pagelinks'* indexes; of course it is waiting for the UPDATE to finish (but I felt like trying it anyway!). Hence, I cannot SELECT anything from *pagelinks* for fear of corrupting the data (unless you think it would be safe to kill the DROP INDEX postmaster process?).
So I am wondering if their is a table that would keep track of the amount of dead tuples or something for It would be nice to know how fast or how far the UPDATE is in the completion of its task.
Thx
(PostgreSQL is not as intelligent as I thought; it needs heuristics) | Did you read the PostgreSQL documentation for "[Using EXPLAIN](http://www.postgresql.org/docs/8.3/static/using-explain.html)", to interpret the output you're showing?
I'm not a regular PostgreSQL user, but I just read that doc, and then compared to the `EXPLAIN` output you're showing. Your `UPDATE` query seems to be using no indexes, and it's forced to do table-scans to sort both `page` and `pagelinks`. The sort is no doubt large enough to need temporary disk files, which I think are created under your `temp_tablespace`.
Then I see the estimated database pages read. The top-level of that `EXPLAIN` output says `(cost=127710692.21..135714045.43)`. The units here are in disk I/O accesses. So it's going to access the disk over 135 million times to do this `UPDATE`.
Note that even 10,000rpm disks with 5ms seek time can achieve at best 200 I/O operations per second under optimal conditions. This would mean that your `UPDATE` would take 188 hours (7.8 days) of disk I/O, even if you could sustain saturated disk I/O for that period (i.e. continuous reads/writes with no breaks). This is impossible, and I'd expect the actual throughput to be off by at least an order of magnitude, especially since you have no doubt been using this server for all sorts of other work in the meantime. So I'd guess you're only a fraction of the way through your `UPDATE`.
If it were me, I would have killed this query on the first day, and found another way of performing the `UPDATE` that made better use of indexes and didn't require on-disk sorting. You probably can't do it in a single SQL statement.
As for your `DROP INDEX`, I would guess it's simply blocking, waiting for exclusive access to the table, and while it's in this state I think you can probably kill it. | This is very old, but if you want a way for you to monitore your update... Remember that sequences are affected globally, so you just can create one to monitore this update in another session by doing this:
```
create sequence yourprogress;
UPDATE pagelinks SET pl_to = page_id
FROM page
WHERE
(pl_namespace, pl_title) = (page_namespace, page_title)
AND
page_is_redirect = 0 AND NEXTVAL('yourprogress')!=0;
```
Then in another session just do this (don't worry about transactions, as sequences are affected globally):
```
select last_value from yourprogress;
```
This will show how many lines are being affected, so you can estimate how long you will take.
At just end restart your sequence to do another try:
```
alter sequence yourprogress restart with 1;
```
Or just drop it:
```
drop sequence yourprogress;
``` | Long UPDATE in postgresql | [
"",
"sql",
"postgresql",
"sql-update",
""
] |
I have a class that after it does some stuff, sends a JMS message.
I'd like to unit test the "stuff", but not necessarily the sending of the message.
When I run my test, the "stuff" green bars, but then fails when sending the message (it should, the app server is not running).
What is the best way to do this, is it to mock the message queue, if so, how is that done.
I am using Spring, and "jmsTemplate" is injected, along with "queue". | The simplest answer I would use is to stub out the message sending functionality. For example, if you have this:
```
public class SomeClass {
public void doit() {
//do some stuff
sendMessage( /*some parameters*/);
}
public void sendMessage( /*some parameters*/ ) {
//jms stuff
}
}
```
Then I would write a test that obscures the sendMessage behavior. For example:
```
@Test
public void testRealWorkWithoutSendingMessage() {
SomeClass thing = new SomeClass() {
@Override
public void sendMessage( /*some parameters*/ ) { /*do nothing*/ }
}
thing.doit();
assertThat( "Good stuff happened", x, is( y ) );
}
```
If the amount of code that is stubbed out or obscured is substantial, I would not use an *anonymous* inner class but just a "normal" inner class. | You can inject a mocked jmsTemplate.
Assuming easymock, something like
```
JmsTemplate mockTemplate = createMock(JmsTemplate.class)
```
That would do the trick. | Unit testing code that sends JMS messages | [
"",
"java",
"unit-testing",
"spring",
"jms",
"jmstemplate",
""
] |
If I have a double (234.004223), etc., I would like to round this to x significant digits in C#.
So far I can only find ways to round to x decimal places, but this simply removes the precision if there are any 0s in the number.
For example, 0.086 to one decimal place becomes 0.1, but I would like it to stay at 0.08. | The framework doesn't have a built-in function to round (or truncate, as in your example) to a number of significant digits. One way you can do this, though, is to scale your number so that your first significant digit is right after the decimal point, round (or truncate), then scale back. The following code should do the trick:
```
static double RoundToSignificantDigits(this double d, int digits){
if(d == 0)
return 0;
double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1);
return scale * Math.Round(d / scale, digits);
}
```
If, as in your example, you really want to truncate, then you want:
```
static double TruncateToSignificantDigits(this double d, int digits){
if(d == 0)
return 0;
double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1 - digits);
return scale * Math.Truncate(d / scale);
}
``` | I've been using pDaddy's sigfig function for a few months and found a bug in it. You cannot take the Log of a negative number, so if d is negative the results is NaN.
The following corrects the bug:
```
public static double SetSigFigs(double d, int digits)
{
if(d == 0)
return 0;
decimal scale = (decimal)Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1);
return (double) (scale * Math.Round((decimal)d / scale, digits));
}
``` | Round a double to x significant figures | [
"",
"c#",
"math",
"rounding",
"significant-digits",
""
] |
I have a MATLAB class which contains a reference to a java object
```
classdef MyClass
properties
j = myJavaClass
end
methods
...
end
end
```
and after I use it (using clear, scope exit or explicitly setting myClass = 0; ) the java object is still alive - even after calling Runtime.gc.
I see in the dump that the object is still in the JVM heap for the MATLAB process (using jmap -histo pID) and thus I assume MATLAB itself is still referencing the object - despite calling to clear, clear JAVA, clear classes, etc. - nothing helps
Any ideas? | The workaround gnovice suggested seem to work - adding to the destructor the line
```
function delete( obj )
...
jObject = 0;
end
```
Caused the object not to be present in MATLAB's JVM heap.
It look like a bug in MATLAB that causes the referencing of the JAVA objects in unreferenced MCOS classes. | The newest object-oriented programming format for MATLAB is still something I haven't jumped into with both feet yet, but I can try and give you a few ideas...
I'm guessing you are creating a "value class" as opposed to a "handle class" (You can check out more about these [here](http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_oop/brfylwk-1.html)). When copies of value classes are made, all the contents are copied. If you have an errant copy of the object floating around somewhere, then there is still a handle to the Java object in existence.
If you were to build your class off of the handle class instead, you could explicitly destroy the Java object within the class destructor (i.e. the overloaded DELETE method).
Just a couple random ideas. Hope they are helpful. | MATLAB Java referencing problem | [
"",
"java",
"matlab",
"reference",
"garbage-collection",
""
] |
On a 64-bit machine is the size of an int in Java 32 bits or 64 bits? | 32 bits. It's one of the Java language features that the size of the integer does not vary with the underlying computer. See [the relevant section of the spec](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2). | The size of primitive data is part of the [virtual machine specification,](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2) and doesn't change. What will change is the size of object references, from 32 bits to 64. So, the same program will require more memory on a 64 bit JVM. The impact this has depends on your application, but can be significant. | On a 64-bit machine is the size of an int in Java 32 bits or 64 bits? | [
"",
"java",
""
] |
I'm allocating an array of T, T extends Number inside a class. I can do it this way:
```
myClass test = new myClass(Double.class, 20);
```
Then the constructor itself:
```
myClass(Class<T> type, size)
{
array = (T[]) Array.newInstance(type, size);
}
```
I'd like to know if it's possible to do it like this:
```
myClass(Number n, size)
{
array = (T[]) Array.newInstance(n.getClass(), size);
}
```
But, I've tried instatiating an object with the second constructor with:
```
myClass test = new myClass(Double, 15);
```
And it doesn't work. Am I doing anything wrong, or is it just not possible? | You can't use Class names as input parameters in Java. The `Object.class` was introduced to allow the passing of "Class names"
So the answer is No, you can't pass `Number` as a parameter but you can pass `Number.class`. That is what it is for :)
\*\* Update \*\*
Also from you second constructor definition
```
myClass(Number n, int size)
{
array = (T[]) Array.newInstance(n.getClass(), size);
}
```
It is clear the input parameter is an instance of Number or it's subclasses not the class is itself. I know it is obvious but it makes clearer why it is not possible to do what you intended | You should use:
```
myClass test = new myClass( Double.class, 15 );
```
You were missing the `.class` part. | Is there a way to pass a Number as a parameter in Java? | [
"",
"java",
"generics",
""
] |
I need to get all dlls in my application root directory. What is the best way to do that?
```
string root = Application.StartupPath;
```
Or,
```
string root = new FileInfo(Assembly.GetExecutingAssembly().Location).FullName;
```
And after that,
```
Directory.GetFiles(root, "*.dll");
```
Which way is better? Are there better ways? | `AppDomain.CurrentDomain.BaseDirectory` is my go to way of doing so.
However:
`Application.StartupPath` gets the directory of your executable
`AppDomain.BaseDirectory` gets the directory used to resolve assemblies
Since they can be different, perhaps you want to use Application.StartupPath, unless you care about assembly resolution. | It depends. If you want the directory of the EXE that started the application, then either of your two examples will work. Remember though, that .NET is very flexible, and it could be that another application has linked to your EXE and is calling it, possibly from another directory.
That doesn't happen very often and you would probably have written if it did, but it is a possibility. Because of that, I prefer to specify which assembly I am interested in and get the directory from that. Then I know that I am getting all of the DLLs in the same directory as that specific assembly. For example, if you have an application MyApp.exe with a class in it MyApp.MyClass, then you would do this;
```
string root = string.Empty;
Assembly ass = Assembly.GetAssembly( typeof( MyApp.MyClass ) );
if ( ass != null )
{
root = ass.Location;
}
``` | What is the best way to determine application root directory? | [
"",
"c#",
".net",
"winforms",
""
] |
For example I have two tables. The first table is student while the second table are the courses that the a student is taking. How can I use a select statement so that I can see two columns student and courses so that the courses are separated by commas.
Thanks. | Assuming you're using SQL Server 2005:
This should do what you're after - obviously replace fields as you need:
For demo purposes, consider the following two table structures:
```
Students(
STU_PKEY Int Identity(1,1) Constraint PK_Students_StuPKey Primary Key,
STU_NAME nvarchar(64)
)
Courses(
CRS_PKEY Int Identity(1, 1) Constraint PK_Courses_CrsPKey Primary Key,
STU_KEY Int Constraint FK_Students_StuPKey Foreign Key References Students(STU_PKEY),
CRS_NAME nvarchar(64)
)
```
Now this query should do the job you're after:
```
Select s.STU_PKEY, s.STU_NAME As Student,
Stuff((
Select ',' + c.CRS_NAME
From Courses c
Where s.STU_PKEY = c.STU_KEY
For XML Path('')
), 1, 1, '') As Courses
From Students s
Group By s.STU_PKEY, s.STU_NAME
```
Way simpler than the currently accepted answer... | ```
create table Project (ProjectId int, Description varchar(50));
insert into Project values (1, 'Chase tail, change directions');
insert into Project values (2, 'ping-pong ball in clothes dryer');
create table ProjectResource (ProjectId int, ResourceId int, Name varchar(15));
insert into ProjectResource values (1, 1, 'Adam');
insert into ProjectResource values (1, 2, 'Kerry');
insert into ProjectResource values (1, 3, 'Tom');
insert into ProjectResource values (2, 4, 'David');
insert into ProjectResource values (2, 5, 'Jeff');
SELECT *,
(SELECT Name + ' ' AS [text()]
FROM ProjectResource pr
WHERE pr.ProjectId = p.ProjectId
FOR XML PATH (''))
AS ResourceList
FROM Project p
-- ProjectId Description ResourceList
-- 1 Chase tail, change directions Adam Kerry Tom
-- 2 ping-pong ball in clothes dryer David Jeff
``` | SQL Help: Select statement Concatenate a One to Many relationship | [
"",
"sql",
"sql-server",
"concatenation",
""
] |
i wonder if there is a simple way to remove already registered types from a unity container or at least replace existing Interface/Type mappings with another one.
is it enough to just map another class type to an interface and the old one is overwritten?
---
this should not happen very often. actually hardly any time, but there are situations were i want to replace a service implemeting some interface with another without having the other parts disturbed. | Listening to the webcast (see msdn webcasts search for unity) it replaces registered types in a last in wins scenario. So if you use config to load your container, then use code to register the same type the code one wins (the reverse also true btw). | With Unity 2, if you're trying to replace one registration with another you'll need to specify both the From type and To type in the new registration if they were included in the original registration.
For example, if you have:
```
public interface IService
{
void DoSomething();
}
public class SomeService : IService
{
public void DoSomething();
}
public class AnotherService : IService
{
public void DoSomething();
}
```
and you register SomeService as:
```
container.RegisterType<IService, SomeService>();
```
then if another part of your system wants to override the IService registration to resolve an AnotherService you'll need to register it as:
```
container.RegisterType<IService, AnotherService>();
```
That seems pretty straightforward, but I got hung up on it when AnotherService needed to be created by a factory:
```
container.RegisterType<IService>(new InjectionFactory(x =>
{
// this would be some complicated procedure
return new AnotherService();
}));
```
In this case you'll still get SomeService. To get AnotherService like you'd expect you need to specify the TTo type:
```
container.RegisterType<IService, AnotherService>(new InjectionFactory(x =>
{
return new AnotherService();
}));
``` | Removing already registered types from UnityContainer at runtime? | [
"",
"c#",
"unity-container",
""
] |
I am looking to create a search engine that will be based on 5 columns in a SQL 2000 DB. I have looked into Lucene.NET and read the documentation on it, but wondering if anyone has any previous experience with this?
Thanks | IMHO it's not so much about performance, but about maintainability. In order to index your content using Lucene.NET you'll have to create some mechanism (service of triggered) which will add new rows (and remove deleted rows) from the Lucene index.
From a beginner's perspective I think it's probably easier to use the SQL Server built-in full text search engine. | i haven't dealt with Lucene yet but a friend of mine has and he said that their performance was 4 to 5 times better with lucene than full text indexing. | Create a Search Engine with SQL 2000 and ASP.NET C# | [
"",
"c#",
"asp.net",
"sql-server",
"search",
""
] |
How can I retuen a Object from a web service:
[WebMethod]
public DataSet GetVendors(string Database)
{
SqlConnection sqlConn = new SqlConnection();
```
sqlConn.ConnectionString = GetConnString(Database);
// build query
string strSQL = @" SELECT [No_] AS [VendorNo],
LTRIM([Name]) AS [VendorName]
FROM [********_$Vendor]
WHERE LEN(RTRIM([Name])) > 0 /* avoid blank names */
AND [Vendor Posting Group] = 'VEND'
ORDER BY LTRIM([Name]) ASC; /* LTRIM fixes spaces before name */ ";
SqlDataAdapter da = new SqlDataAdapter(strSQL, sqlConn);
DataSet ds = new DataSet();
da.Fill(ds, "Vendors");
return (ds);
}
``` | If I'm interpreting your question properly, populate an object on your end with your information in the `DataSet` and set your return type to `object`. Or just return the object you populate as that object. | An alternative would be to return the dataset xml as a string and create a dataset from it on the client side.
Although I'm sure encrypting the object would be fairly straightforward, this approach helped me out when my web services needed encryption (serialize everything, encrypt that string, return string, decrypt, deserialize). | Return Object From Webservice | [
"",
"sql",
"web-services",
""
] |
I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.
I start the server using
```
python manage.py testserver
```
I can see each GET request (PNGs and style sheets) take about half a second.
Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.
It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.
Django runs on python2.4, I'm running Vista. I have also checked python2.5.
Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as
instead of <http://localhost:8000/app> I go to <http://127.0.0.1:8000/app>.
But what could it be caused by? My host file has only two entries:
```
127.0.0.1 localhost
::1 localhost
``` | Firefox has a problem browsing to localhost on some Windows machines. You can solve it by switching off ipv6, which isn't really recommended. Using 127.0.0.1 directly is another way round the problem. | None of these posts helped me. In my specific case, [Justin Carmony](http://www.justincarmony.com/blog/2011/07/27/mac-os-x-lion-etc-hosts-bugs-and-dns-resolution/) gave me the answer.
**Problem**
I was mapping [hostname].local to 127.0.0.1 in my /etc/hosts file for easy development purposes and dns requests were taking 5 seconds at to resolve. Sometimes they would resolve quickly, other times they wouldn't.
**Solution**
Apple is using .local to do some bonjour magic on newer Snow Leopard builds (I think i started noticing it after updating to 10.6.8) and Mac OS X Lion. If you change your dev hostname to start with local instead of end with local you should be all set. Additionally, you can pretty much use any TLD besides local and it will work without conflict.
**Example**
test.local could become:
* local.test.com
* test.dev
* test.[anything but local]
and your hosts file entry would read:
```
local.test.com 127.0.0.1
```
*Note: This solution has the added benefit of being a subdomain of [hostname].com which makes it easier to specify an app domain name for Facebook APIs, etc.*
Might also want to run `dscacheutil -flushcache` in the terminal for good measure after you update /etc/hosts | django is very slow on my machine | [
"",
"python",
"django",
"dns",
""
] |
I have a dll that contains a templated class. Is there a way to export it without explicit specification? | Since the code for templates is usually in headers, you don't need to export the functions at all. That is, the library that is using the dll can instantiate the template.
This is the only way to give users the freedom to use any type with the template, but in a sense it's working against the way dlls are supposed to work. | Are you looking into exporting an instantiation of a template class through a dll? A class along the lines:
```
typedef std::vector<int> IntVec;
```
There is some discussion how to do this on:
[http://support.microsoft.com/kb/168958](https://jeffpar.github.io/kbarchive/kb/168/Q168958/)
Another approach is to explicitly exporting each function you are interested in through a wrapper class working against this template instance. Then you won't clutter the dll with more symbols than you are actually interested in using. | How do I export templated classes from a dll without explicit specification? | [
"",
"c++",
"dll",
"templates",
""
] |
What is the recommended location to save user preference files? Is there a recommended method for dealing with user preferences?
Currently I use the path returned from `typeof(MyLibrary).Assembly.Location` as a default location to store files generated or required by the application.
EDIT:
I found two related/interesting questions:
* [Best place to save user information for Windows XP and Vista applications](https://stackoverflow.com/questions/147533/best-place-to-save-user-information-xp-and-vista)
* [What's the way to implement Save / Load functionality?](https://stackoverflow.com/questions/348022/whats-the-way-to-implement-save-load-functionality)
EDIT #2:
This is just a note for people like me who had never used settings before.
Settings are pretty useful, but I had to do a whole bunch of digging to figure out what was going on (coming from the Python world, not something I am used too). Things got complicated as I wanted to save dictionaries and apparently they can't be serialized. Settings also seem to get stored in 3 different files depending on what you do. There is an `app.config`, `user.config` and a `settings.setting` file. So here are two more links that I found useful:
* <http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/ddeaca86-a093-4997-82c9-01bc0c630138>
* <http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/efe370dc-f933-4e55-adf7-3cd8063949b0/> | You can use the Application Settings easily enough.
If you haven't done so before just right click on the project and choose Properties. Select the Settings tab. Make sure you chose "User" for the scope (otherwise the setting is read-only).
The code to access this is simple:
```
forms.Width = Application1.Properties.Settings.Default.Width;
```
If you need to save it:
```
Application1.Properties.Settings.Default.Width = forms.Width;
Application1.Properties.Settings.Default.Save();
```
In the sample above, Width is the custom setting name you define in the Settings tab and Application1 is the Namespace of your application.
**Edit: Responding to further questions**
You mentioned you wanted to store Dictionary objects in the Settings. As you discovered, you can't do this directly because Dictionary objects are not serializable. However, you can create your own serializable dictionary pretty easily. Paul Welzer had an excellent example [on his blog](http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx).
You have a couple of links which sort of muddy the situation a little. Your original question is where to save "User Preference Files". I'm pretty certain Microsoft's intention with the Settings functionality is exactly that... storing user skin preferences, layout choices, etc. It not meant as a generic repository for an application's data although it could be easily abused that way.
The data is stored in separate places for a good reason. Some of the settings are Application settings and are read-only. These are settings which the app needs to function but is not specific to a user (for example, URIs to app resources or maybe a tax rate). These are stored in the app.config.
User settings are stored in an obfuscated directory deep within the User Document/Settings folder. The defaults are stored in app.config (I think, can't recall for certain off the top of my head) but any user changes are stored in their personal folder. This is meant for data that changes from user to user. (By "user" I mean Windows user, not your app's user.)
Hope this clarified this somewhat for you. The system is actually pretty simple. It might seem a little foreign at first but after a few days of using it you'll never have to think of it again... it just works. | When running as non-admin or on Vista you can't write to the "Program files" folder (or any sub folder of it).
The correct location to store user preference is (replace MyCompanyName and MyApplicationName with the correct names, obviously)
On disk:
```
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MyCompanyName\\MyApplicationName"
```
Or in the registry under the key:
```
HKEY_CURRENT_USER\Software\MyCompanyName\MyApplicationName
```
Those location are per-user and they work with non-admin user, several users using the same computer, fast user switching, terminal services and all the other ways people can interact with your software.
If you need a common location for all users then:
1. It will only work when the user run as an administrator
2. It will not work reliably on Vista
3. You have to take care of everything yourself (like two users running the application on the same computer at the same time via fast user switching).
and the locations are:
```
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationCommonData) + "\\MyCompanyName\\MyApplicationName"
```
Or in the registry under the key:
```
HKEY_LOCAL_MACHINE\Software\MyCompanyName\MyApplicationName
``` | WPF/C#: Where should I be saving user preferences files? | [
"",
"c#",
"wpf",
"file",
""
] |
I'm looking for a better way to do the following query. I have a table that looks like this:
```
game_id | home_team_id | away_team_id
1 | 100 | 200
2 | 200 | 300
3 | 200 | 400
4 | 300 | 100
5 | 100 | 400
```
And I want to write a query that counts the number of home games and away games for each team and outputs the following:
```
team_id | home_games | away_games
100 | 2 | 1
200 | 2 | 1
300 | 1 | 1
400 | 0 | 2
```
Right now, I wrote this monstrosity that works, but it's slow (I know it's pulling the entire 2,800 row from the table twice).
```
SELECT
home_team_id as team_id,
(SELECT count(*) FROM `game` WHERE home_team_id = temp_game.home_team_id) as home_games,
(SELECT count(*) FROM `game` WHERE home_team_id = temp_game.away_team_id) as away_games
FROM (SELECT * FROM `game`) as temp_game
GROUP BY home_team_id
```
Can a SQL guru help me knock out a better way? I think my problem is that I don't understand how to get a distinct list of the team IDs to throw at the count queries. I bet there's a better way with a better placed, nested SELECT. Thanks in advance! | It's cleaner if you have another table team with team\_id and team\_name.
```
SELECT team_id, team_name,
sum(team_id = home_team_id) as home_games,
sum(team_id = away_team_id) as away_games
FROM game, team
GROUP BY team_id
```
What's going on: the no WHERE clause causes a Cartesian Product between the two tables; we group by team\_id to get back to one row per team. Now there are all the rows from the game table for each team\_id so you need to count them but the SQL count function isn't quite right (it would count all the rows or all the distinct rows). So we say team\_id = home\_team\_id which resolves to 1 or 0 and we use sum to add up the 1's.
The team\_name is just because it's geeky to say that 'team 200 had 20 home games' when we ought to say that 'Mud City Stranglers had 20 home games'.
PS. this will work even if there are no games (often a problem in SQL where there is a team with 0 games and that row will not show up because the join fails). | If you want the distinct list of teams, you have to select from the game table twice, unioning the home and the away teams (theoretically, one team could play all its games on the road or at home, if you have logic that prevents that, then you could adjust this query):
```
select home_team_id as team_id from game union
select away_team_id as team_id from game
```
The `union` operator will make sure you only get distinct elements in the return set (unless you use `union all`)
From there, you can use left outer joins to aggregate your data:
```
select
u.team_id, count(h.game_id) as home_games, count(a.game_id) as away_games
from
(
select home_team_id as team_id from game union
select away_team_id as team_id from game
) as u
left outer join game as h on h.home_team_id = u.team_id
left outer join game as a on a.away_team_id = u.team_id
group by
u.team_id
```
If you want to reduce your table scans even further (the above will produce four), you can add more code, but it will cost you. You can get a list of rows with the team\_id, and whether or not the game was played at home or away:
```
select
case ha.home when 0 then g.away_team_id else g.home_team_id end as team_id,
case ha.home when 0 then 0 else 1 end as home_games,
case ha.home when 0 then 1 else 0 end as away_games
from
game as g, (select 0 as home union select 1 as home) as ha
```
From there, you can simply sum up the games at home and away for each team:
```
select
t.team_id, sum(t.home_games) as home_games, sum(t.away_games) as away_games
from
(
select
case ha.home when 0 then g.away_team_id else g.home_team_id end as team_id,
case ha.home when 0 then 0 else 1 end as home_games,
case ha.home when 0 then 1 else 0 end as away_games
from
game as g, (select 0 as home union select 1 as home) as ha
) as t
group by
t.team_id
```
This will result in a single table scan. | SQL Help: Counting Rows in a Single Query With a Nested SELECT | [
"",
"sql",
""
] |
Is there a way to run plain c code on top of the JVM?
Not connect via JNI, running, like you can run ruby code via JRuby, or javascript via Rhino.
If there is no current solution, what would you recommend I should do?
Obviously I want to use as many partials solutions as I can to make it happen.
ANTLR seems like a good place to start, having a full "ANSI C" grammar implementation...
should I build a "toy" VM over the JVM using ANTLR generated code? | Updated 2012-01-26: According to [this page on the company's site](http://axiomsol.com/ampc-acquired-by-private-company) the product has been bought out and is no longer available.
Yes.
Here's [a commercial C compiler that produces JVM bytecode](http://www.axiomsol.com/pro_serv/compiler.php). | There are two other possibilities, both open-source:
[JPC](https://github.com/ianopolous/JPC) emulates an entire x86 pc within the JVM, and is capable of running both DOS and Linux.
[NestedVM](http://nestedvm.ibex.org/) provides binary translation for Java Bytecode. This is done by having GCC compile to a MIPS binary which is then translated to a Java class file. Hence any application written in C, C++, Fortran, or any other language supported by GCC can be run in 100% pure Java with no source changes. | Running/Interpreting C on top of the JVM? | [
"",
"java",
"c",
"jvm",
"antlr",
"interpreter",
""
] |
I'm implementing a COM interface that should return int values either `S_OK` or `E_FAIL`. I'm ok returning `S_OK` as I get that back from another call (Marshal.QueryInterface), but if I want to return a failure value what actual value do I use for `E_FAIL`?
(It's such a basic fundamental question that it's hard to find an answer to)
Assuming it's a specific number defined in the Win32 API, is there way to use it within .net code without declaring my own constant?
thanks!
**Update (answered below):**
Maybe I'm being a complete plonker, but I'm having problems with this. According to my Platform SDK, `HRESULT` is a `LONG`, which is a 32-bit signed integer, right? So possible values –2,147,483,648 to 2,147,483,647. But 0x80004005 = 2,147,500,037 which is > 2,147,483,647. What gives!?
This means when I try to put this in my code:
```
const int E_FAIL = 0x80004005;
```
I get a compiler error *Cannot implicitly convert type 'uint' to 'int'*.
**Update 2:**
I'm going to declare it like this:
```
const int E_FAIL = -2147467259;
```
because if I try to do something like this:
```
const UInt32 E_FAIL = 0x80004005;
return (Int32)E_FAIL;
```
I get a compiler error *Constant value '2147500037' cannot be converted to a 'int' (use 'unchecked' syntax to override)*
Phew! Who knew how tricky it would be to declare a standard return value.... Somewhere there must be a class lurking that I should have used like **return Win32ReturnCodes.E\_FAIL;** ... *sigh*
**ULTIMATE SOLUTION:**
I now do this by getting the (massive but very useful) HRESULT enum from [pinvoke.net](http://www.pinvoke.net/default.aspx/Enums/HRESULT.html) and adding it to my solution. Then use it something like this:
```
return HRESULT.S_OK;
``` | E\_FAIL is Hex 80004005 in WinError.h
You can see the full [Common HRESULT Values](http://msdn.microsoft.com/en-us/library/windows/desktop/aa378137(v=vs.85).aspx). You don't have to install C++ just to see the values.
**UPDATE:**
The signed and unsigned versions of 0x80004005 are just two representations of the same bit mask. If you're getting a casting error then use the negative signed value. When casted to an UN signed long it will be the "correct" value. Test this yourself in C#, it'll work
e.g.
This code
```
static void Main(string[] args)
{
UInt32 us = 0x80004005;
Int32 s = (Int32)us;
Console.WriteLine("Unsigned {0}", us);
Console.WriteLine("Signed {0}", s);
Console.WriteLine("Signed as unsigned {0}", (UInt32)s);
Console.ReadKey();
}
```
will produce this output
* Unsigned 2147500037
* Signed -2147467259
* Signed as unsigned 2147500037
So it's safe to use -2147467259 for the value of E\_FAIL | From WinError.h for Win32
```
#define E_FAIL _HRESULT_TYPEDEF_(0x80004005L)
```
To find answers like this, use visual studio's file search to search the header files in the VC Include directory of your visual studio install directory.
```
C:\Program Files\Microsoft Visual Studio 9.0\VC\include
``` | What values to return for S_OK or E_FAIL from c# .net code? | [
"",
"c#",
".net",
"com",
"return-value",
""
] |
How do I take a jar file that I have and add it to the dependency system in maven 2? I will be the maintainer of this dependency and my code needs this jar in the class path so that it will compile. | You'll have to do this in two steps:
### 1. Give your JAR a groupId, artifactId and version and add it to your repository.
If you don't have an internal repository, and you're just trying to add your JAR to your local repository, you can install it as follows, using any arbitrary groupId/artifactIds:
```
mvn install:install-file -DgroupId=com.stackoverflow... -DartifactId=yourartifactid... -Dversion=1.0 -Dpackaging=jar -Dfile=/path/to/jarfile
```
You can also deploy it to your internal repository if you have one, and want to make this available to other developers in your organization. I just use my repository's web based interface to add artifacts, but you should be able to accomplish the same thing using `mvn deploy:deploy-file ...`.
### 2. Update dependent projects to reference this JAR.
Then update the dependency in the pom.xml of the projects that use the JAR by adding the following to the element:
```
<dependencies>
...
<dependency>
<groupId>com.stackoverflow...</groupId>
<artifactId>artifactId...</artifactId>
<version>1.0</version>
</dependency>
...
</dependencies>
``` | You can also specify a dependency not in a maven repository. Could be usefull when no central maven repository for your team exist or if you have a [CI](http://en.wikipedia.org/wiki/Continuous_integration) server
```
<dependency>
<groupId>com.stackoverflow</groupId>
<artifactId>commons-utils</artifactId>
<version>1.3</version>
<scope>system</scope>
<systemPath>${basedir}/lib/commons-utils.jar</systemPath>
</dependency>
``` | Add a dependency in Maven | [
"",
"java",
"macos",
"maven-2",
"dependencies",
""
] |
I'm trying to optimize query performance and have had to resort to using optimizer hints. But I've never learned if the optimizer will use more than one hint at a time.
e.g.
```
SELECT /*+ INDEX(i dcf_vol_prospect_ids_idx)*/
/*+ LEADING(i vol) */
/*+ ALL_ROWS */
i.id_number,
...
FROM i_table i
JOIN vol_table vol on vol.id_number = i.id_number
JOIN to_a_bunch_of_other_tables...
WHERE i.solicitor_id = '123'
AND vol.solicitable_ind = 1;
```
The explain plan shows the same cost, but I know that's just an estimate.
Please assume that all table and index statistics have been calculated. FYI, the index dcf\_vol\_prospect\_ids\_idx is on the i.solicitor\_id column.
Thanks,
Stew | Try specifying all the hints in a single comment block, as shown in this example from the wonderful Oracle documentation (<http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/hintsref.htm>).
> 16.2.1 Specifying a Full Set of Hints
>
> When using hints, in some cases, you
> might need to specify a full set of
> hints in order to ensure the optimal
> execution plan. For example, if you
> have a very complex query, which
> consists of many table joins, and if
> you specify only the INDEX hint for a
> given table, then the optimizer needs
> to determine the remaining access
> paths to be used, as well as the
> corresponding join methods. Therefore,
> even though you gave the INDEX hint,
> the optimizer might not necessarily
> use that hint, because the optimizer
> might have determined that the
> requested index cannot be used due to
> the join methods and access paths
> selected by the optimizer.
>
> In Example 16-1, the LEADING hint
> specifies the exact join order to be
> used; the join methods to be used on
> the different tables are also
> specified.
>
> Example 16-1 Specifying a Full Set of
> Hints
```
SELECT /*+ LEADING(e2 e1) USE_NL(e1) INDEX(e1 emp_emp_id_pk)
USE_MERGE(j) FULL(j) */
e1.first_name, e1.last_name, j.job_id, sum(e2.salary) total_sal
FROM employees e1, employees e2, job_history j
WHERE e1.employee_id = e2.manager_id
AND e1.employee_id = j.employee_id
AND e1.hire_date = j.start_date
GROUP BY e1.first_name, e1.last_name, j.job_id ORDER BY total_sal;
``` | Oracle 19c introduced [Hint Usage Reporting feature](https://blogs.oracle.com/optimizer/livesql-now-live-on-oracle-database-19c):
```
EXPLAIN PLAN FOR
SELECT /*+ INDEX(i dcf_vol_prospect_ids_idx)*/
/*+ LEADING(i vol) */
/*+ ALL_ROWS */
i.id_number,
...
FROM i_table i
JOIN vol_table vol on vol.id_number = i.id_number
JOIN to_a_bunch_of_other_tables...
WHERE i.solicitor_id = '123'
AND vol.solicitable_ind = 1;
SELECT * FROM table(DBMS_XPLAN.DISPLAY(FORMAT=>'BASIC +HINT_REPORT'));
--============
```
It shows another section `Hint Report`:
```
Hint Report (identified by operation id / Query Block Name / Object Alias):
Total hints for statement: ...
---------------------------------------------------
...
``` | Will Oracle optimizer use multiple Hints in the same SELECT? | [
"",
"sql",
"oracle",
"optimization",
"hints",
""
] |
This would be very handy as typecasting gets boring fast. | If you use generics (java 5), you can avoid all casting with
```
List<String> myList = new ArrayList<String>();
myList.add(" a test");
String temp = myList.get(0);
```
Unless I am missing something in your question that should cover both needs. | If by "variable length" you mean that the size will change over time, then you probably want a LinkedList rather than an ArrayList:
```
print("List<Foo> fooList = new LinkedList<Foo>();");
```
That way you get better performance when adding a bunch of elements. | Is there a Java array/list which is statically typed AND variable length | [
"",
"java",
"arrays",
"list",
""
] |
I have an object tree that looks something like
```
Ball
/ \
LegalBall IllegalBall
```
And I have 2 methods:
```
class o {
AddBall(LegalBall l)
AddBall(IllegalBall i)
}
```
in another class I'd like to do the following:
```
o.AddBall(myBall);
```
where myBall is of type Ball.
And get it to call the correct method depending on the subtype.
Apparently I can't do this... the arguments are not applicable.
Does anyone know how I can achieve what I want? Or if there is a good work around
Thanks
EDIT : the application I'm trying to build is a Cricket scorecard type thing. So depending on the type of ball that is bowled various other elements should change.
my original intention was to be able to specify the ball type and runs scored from some form of UI and then create an appropriate type ball from a BallFactory and then for example when I send a no ball to the team score it will add the value onto the team score but also add the value to the no balls counter. But when i give the same ball to the Batsmens Analysis to deal with it should only score value-1 to the batsmens total..
I hope thats not too bad an explanation of my original intention. | You could use the [Visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern).
```
class Basket {
void AddBall(LegalBall l) {
System.out.println("LegalBall added to basket");
}
void AddBall(IllegalBall i) {
System.out.println("IllegalBall added to basket");
}
}
interface Ball {
void AddBall(Basket b);
}
class LegalBall implements Ball {
void AddBall(Basket b) {
b.AddBall(this);
}
}
class IllegalBall implements Ball {
void AddBall(Basket b) {
b.AddBall(this);
}
}
```
or to make it more general:
```
interface BallVisitor {
void visit(LegalBall l);
void visit(IllegalBall i);
}
interface Ball {
void accept(BallVisitor v);
}
class LegalBall implements Ball {
void accept(BallVisitor v) {
v.visit(this);
}
}
class IllegalBall implements Ball {
void accept(BallVisitor v) {
v.visit(this);
}
}
class Basket implements BallVisitor {
void visit(LegalBall l) {
System.out.println("LegalBall added to basket");
}
void visit(IllegalBall i) {
System.out.println("IllegalBall added to basket");
}
}
``` | You should try to implement only *one* method:
```
class o {
AddBall(Ball b)
}
```
and try to rely on polymorphism for different behavior with respect to different classes. Of course the details depend on the implementation of the Ball hierarchy. | Passing superclass as parameter to method expecting sub class | [
"",
"java",
"inheritance",
"methods",
"polymorphism",
"overloading",
""
] |
I hope I can explain this clearly enough. I have my main form (A) and it opens 1 child form (B) using form.Show() and a second child form (C) using form.Show(). Now I want child form B to open a form (D) using form.ShowDialog(). When I do this, it blocks form A and form C as well. Is there a way to open a modal dialog and only have it block the form that opened it? | If you run Form B on a separate thread from A and C, the ShowDialog call will only block that thread. Clearly, that's not a trivial investment of work of course.
You can have the dialog not block any threads at all by simply running Form D's ShowDialog call on a separate thread. This requires the same kind of work, but much less of it, as you'll only have one form running off of your app's main thread. | Using multiple GUI threads is tricky business, and I would advise against it, if this is your only motivation for doing so.
A much more suitable approach is to use `Show()` instead of `ShowDialog()`, and disable the owner form until the popup form returns. There are just four considerations:
1. When `ShowDialog(owner)` is used, the popup form stays on top of its owner. The same is true when you use `Show(owner)`. Alternatively, you can set the `Owner` property explicitly, with the same effect.
2. If you set the owner form's `Enabled` property to `false`, the form shows a disabled state (child controls are "grayed out"), whereas when `ShowDialog` is used, the owner form still gets disabled, but doesn't show a disabled state.
When you call `ShowDialog`, the owner form gets disabled in Win32 code—its `WS_DISABLED` style bit gets set. This causes it to lose the ability to gain the focus and to "ding" when clicked, but doesn't make it draw itself gray.
When you set a form's `Enabled` property to `false`, an additional flag is set (in the framework, not the underlying Win32 subsystem) that certain controls check when they draw themselves. This flag is what tells controls to draw themselves in a disabled state.
So to emulate what would happen with `ShowDialog`, we should set the native `WS_DISABLED` style bit directly, instead of setting the form's `Enabled` property to `false`. This is accomplished with a tiny bit of interop:
```
const int GWL_STYLE = -16;
const int WS_DISABLED = 0x08000000;
[DllImport("user32.dll")]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
void SetNativeEnabled(bool enabled){
SetWindowLong(Handle, GWL_STYLE, GetWindowLong(Handle, GWL_STYLE) &
~WS_DISABLED | (enabled ? 0 : WS_DISABLED));
}
```
3. The `ShowDialog()` call doesn't return until the dialog is dismissed. This is handy, because you can suspend the logic in your owner form until the dialog has done its business. The `Show()` call, necessarily, does not behave this way. Therefore, if you're going to use `Show()` instead of `ShowDialog()`, you'll need to break your logic into two parts. The code that should run after the dialog is dismissed (which would include re-enabling the owner form), should be run by a `Closed` event handler.
4. When a form is shown as a dialog, setting its `DialogResult` property automatically closes it. This property gets set whenever a button with a `DialogResult` property other than `None` is clicked. A form shown with `Show` will not automatically close like this, so we must explicitly close it when one of its dismissal buttons is clicked. Note, however, that the `DialogResult` property still gets set appropriately by the button.
Implementing these four things, your code becomes something like:
```
class FormB : Form{
void Foo(){
SetNativeEnabled(false); // defined above
FormD f = new FormD();
f.Closed += (s, e)=>{
switch(f.DialogResult){
case DialogResult.OK:
// Do OK logic
break;
case DialogResult.Cancel:
// Do Cancel logic
break;
}
SetNativeEnabled(true);
};
f.Show(this);
// function Foo returns now, as soon as FormD is shown
}
}
class FormD : Form{
public FormD(){
Button btnOK = new Button();
btnOK.DialogResult = DialogResult.OK;
btnOK.Text = "OK";
btnOK.Click += (s, e)=>Close();
btnOK.Parent = this;
Button btnCancel = new Button();
btnCancel.DialogResult = DialogResult.Cancel;
btnCancel.Text = "Cancel";
btnCancel.Click += (s, e)=>Close();
btnCancel.Parent = this;
AcceptButton = btnOK;
CancelButton = btnCancel;
}
}
``` | Is it possible to use ShowDialog without blocking all forms? | [
"",
"c#",
"winforms",
"showdialog",
""
] |
i have a c function which returns a `long double`. i'd like to call this function from python using ctypes, and it mostly works. setting `so.func.restype = c_longdouble` does the trick -- except that python's float type is a `c_double` so if the returned value is larger than a double, but well within the bounds of a long double, python still gets inf as the return value. i'm on a 64 bit processor and `sizeof(long double)` is 16.
any ideas on getting around this (e.g. using the decimal class or numpy) without modifying the c code? | I'm not sure you can do it without modifying the C code. ctypes seems to have really bad support for `long double`s - you can't manipulate them like numbers at all, all you can do is convert them back and forth between the native `float` Python type.
You can't even use a byte array as the return value instead of a `c_longdouble`, because of the ABI - floating-point values aren't returned in the `%eax` register or on the stack like normal return values, they're passed through the hardware-specific floating-point registers. | If you have a function return a *subclass* of `c_longdouble`, it will return the ctypes wrapped field object rather than converting to a python `float`. You can then extract the bytes from this (with `memcpy` into a c\_char array, for example) or pass the object to another C function for further processing. The `snprintf` function can format it into a string for printing or conversion into a high-precision python numeric type.
```
import ctypes
libc = ctypes.cdll['libc.so.6']
libm = ctypes.cdll['libm.so.6']
class my_longdouble(ctypes.c_longdouble):
def __str__(self):
size = 100
buf = (ctypes.c_char * size)()
libc.snprintf(buf, size, '%.35Le', self)
return buf[:].rstrip('\0')
powl = libm.powl
powl.restype = my_longdouble
powl.argtypes = [ctypes.c_longdouble, ctypes.c_longdouble]
for i in range(1020,1030):
res = powl(2,i)
print '2**'+str(i), '=', str(res)
```
Output:
```
2**1020 = 1.12355820928894744233081574424314046e+307
2**1021 = 2.24711641857789488466163148848628092e+307
2**1022 = 4.49423283715578976932326297697256183e+307
2**1023 = 8.98846567431157953864652595394512367e+307
2**1024 = 1.79769313486231590772930519078902473e+308
2**1025 = 3.59538626972463181545861038157804947e+308
2**1026 = 7.19077253944926363091722076315609893e+308
2**1027 = 1.43815450788985272618344415263121979e+309
2**1028 = 2.87630901577970545236688830526243957e+309
2**1029 = 5.75261803155941090473377661052487915e+309
```
(Note that my estimate of 35 digits of precision turned out to be excessively optimistic for `long double` calculations on Intel processors, which only have 64 bits of mantissa. You should use `%a` rather than `%e`/`f`/`g` if you intend to convert to a format that is not based on decimal representation.) | long double returns and ctypes | [
"",
"python",
"ctypes",
""
] |
This appears to be the most commonly asked C# interop question and yet seems to be difficult to find a working solution for.
I am in need of allocating an array of matrix datastructure in C# passing it to a C DLL which fills up the data and returns it to the caller to deal with.
Based on various pages on the web, I seem to have managed to get data and memory from C# into C++ but not, it appears, back...
Code follows.
thanks in advance for any help
Shyamal
---
I have a C++ structure as follows
```
typedef struct tagTMatrix
{
int Id;
int NumColumns;
int NumRows;
double* aData;
} TMatrix;
```
which I declare in C# as
```
[StructLayout(LayoutKind.Sequential)]
unsafe public struct TMatrix
{
public Int32 id;
public Int32 NumCols;
public Int32 NumRows;
public Int32 NumPlanes;
public IntPtr aData;
};
[DllImport("kernel32.dll")]
internal static extern IntPtr LoadLibrary(String dllname);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetProcAddress(IntPtr hModule, String
procname);
unsafe internal delegate void FillMatrices(IntPtr mats, long num);
[DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")] // Saw this
mentioned somewhere
static extern void CopyMemory(IntPtr dest, IntPtr[] src, int cb);
unsafe private void butTest_Click(object sender, EventArgs e)
{
IntPtr library = LoadLibrary("TestDLL.dll");
IntPtr procaddr = GetProcAddress(library, "FillMatrices");
FillMatrices fm =
(FillMatrices)Marshal.GetDelegateForFunctionPointer(procaddr,
typeof(FillMatrices));
TMatrix[] mats = new TMatrix[2];
mats[0]=new TMatrix();
mats[1]=new TMatrix();
mats[0].id=1;
mats[0].NumCols=2;mats[0].NumRows=1;mats[0].NumPlanes=0;
mats[0].aData = Marshal.AllocHGlobal(sizeof(double) * 2);
double [] array=new double[2];
array[0]=12.5;array[1]=2.3;
fixed (double* a = array)
{
IntPtr intPtr = new IntPtr((void*)a);
mats[1].aData = Marshal.AllocHGlobal(sizeof(double) * 2);
//mats[1].aData = 13;
mats[1].aData = intPtr;
mats[1].id = 2;
mats[1].NumCols = 1; mats[1].NumRows = 2; mats[1].NumPlanes = 0;
}
IntPtr[] ptrs = new IntPtr[2];
int total=0;
for (int i = 0; i < ptrs.Length; i++)
{
total = total + sizeof(IntPtr) * (4 + mats[i].NumCols * mats[i].NumRows);
ptrs[i] =
Marshal.AllocHGlobal(sizeof(IntPtr)*(4+mats[i].NumCols*mats[i].NumRows));
}
Marshal.StructureToPtr(mats[0], ptrs[0], false);
Marshal.StructureToPtr(mats[1], ptrs[1], false);
//_list.test_list =
IntPtr pointer=Marshal.AllocHGlobal(total);
CopyMemory(pointer, ptrs, 2 * IntPtr.Size);
//TMatrix m1=new TMatrix();
//mats[0].aData = 10;// new double[20];
//TMatrix m2 = new TMatrix();
// mats[1].aData = 20;// new double[9];
//Marshal.StructureToPtr(m2, p1, false);
//mats.Add(m2);
//Marshal.StructureToPtr(mats, p1, false);
//IntPtr p2=Marshal.AllocHGlobal(270);
//Marshal.StructureToPtr(mats.ToArray(),p2,false);
fm(pointer,2);
// Now I want to get back this data ???
}
// C++ function
extern "C" void FillMatrices(TMatrix** mats, int matcount)
{
FILE* fp=fopen("C:\\mats.txt","w+");
fprintf(fp,"Number of matrices = %d\n",matcount);
fflush(fp);
for(int i=0;i<matcount;++i)
{
TMatrix* m=mats[i];
fprintf(fp,"id = %d rows %d cols %d \n",m->Id,m->NumRows,m->NumColumns);
fflush(fp);
for(int j=0;j<m->NumRows;++j)
{
fprintf(fp,"%d ",j);
fflush(fp);
for(int k=0;k<m->NumColumns;++k)
{
fprintf(fp,"%f ", m->aData[k*m->NumRows+j]);
// modify the data - it should be available back in C#
m->aData[k*m->NumRows+j]=k;
fflush(fp);
}
fprintf(fp,"\n");
fflush(fp);
}
fprintf(fp,"--------------------------\n");
fflush(fp);
}
fclose(fp);
}
``` | Here's a modified version of my initial code that works with an array of matrices:
```
typedef struct Matrix
{
int rowsCount;
int colsCount;
int* data;
} TMatrix;
extern "C" __declspec(dllexport) void InitializeMatrix(TMatrix** matrices, int count)
{
srand(time(NULL));
printf("<unmanaged>\n");
for(int i = 0; i < count; i++)
{
TMatrix* m = matrices[i];
printf("rows %d cols %d\n", m->rowsCount, m->colsCount);
for(int j = 0; j < m->rowsCount; j++)
{
for(int k = 0; k < m->colsCount; k++)
{
printf("%d ", m->data[k * m->rowsCount + j]);
// modify the data - it should be available back in C#
m->data[k * m->rowsCount + j] = rand() % 10;
}
printf("\n");
}
}
printf("</unmanaged>\n\n");
}
```
And the managed part:
```
[StructLayout(LayoutKind.Sequential)]
struct Matrix
{
public int RowsCount;
public int ColsCount;
public IntPtr Data;
}
class Program
{
[DllImport("TestLib.dll")]
private static extern void InitializeMatrix(IntPtr ptr, int count);
static void Main(string[] args)
{
const int count = 3;
// Allocate memory
IntPtr ptr = Marshal.AllocHGlobal(count * Marshal.SizeOf(typeof(IntPtr)));
IntPtr[] matrices = new IntPtr[count];
for (int i = 0; i < count; i++)
{
Matrix matrix = new Matrix();
// Give some size to the matrix
matrix.RowsCount = 4;
matrix.ColsCount = 3;
int size = matrix.RowsCount * matrix.ColsCount;
int[] data = new int[size];
matrix.Data = Marshal.AllocHGlobal(size * Marshal.SizeOf(typeof(int)));
Marshal.Copy(data, 0, matrix.Data, size);
matrices[i] = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Matrix)));
Marshal.StructureToPtr(matrix, matrices[i], true);
}
Marshal.Copy(matrices, 0, ptr, count);
// Call unmanaged routine
InitializeMatrix(ptr, count);
Console.WriteLine("<managed>");
// Read data back
Marshal.Copy(ptr, matrices, 0, count);
for (int i = 0; i < count; i++)
{
Matrix m = (Matrix)Marshal.PtrToStructure(matrices[i], typeof(Matrix));
int size = m.RowsCount * m.ColsCount;
int[] data = new int[size];
Marshal.Copy(m.Data, data, 0, size);
// Pretty-print the matrix
Console.WriteLine("rows: {0} cols: {1}", m.RowsCount, m.ColsCount);
for (int j = 0; j < m.RowsCount; j++)
{
for (int k = 0; k < m.ColsCount; k++)
{
Console.Write("{0} ", data[k * m.RowsCount + j]);
}
Console.WriteLine();
}
}
Console.WriteLine("</managed>");
// Clean the whole mess (try...finally block omitted for clarity)
for (int i = 0; i < count; i++)
{
Matrix m = (Matrix)Marshal.PtrToStructure(matrices[i], typeof(Matrix));
Marshal.FreeHGlobal(m.Data);
Marshal.FreeHGlobal(matrices[i]);
}
Marshal.FreeHGlobal(ptr);
}
}
```
HTH | Here's a couple of methods I used to marshal C++ network structs on a C# client application:
```
public static T Get<T>(byte[] msg, int offset)
{
T[] t = new T[] { default(T) };
int len = Marshal.SizeOf(typeof(T));
GCHandle th = GCHandle.Alloc(t, GCHandleType.Pinned);
GCHandle mh = GCHandle.Alloc(msg, GCHandleType.Pinned);
try
{
unsafe
{
byte* pb = (byte*)mh.AddrOfPinnedObject();
byte* srcptr = pb + offset;
byte* dest = ((byte*)th.AddrOfPinnedObject());
for (int i = 0; i < len; i++)
{
dest[i] = srcptr[i];
}
}
}
finally
{
mh.Free();
th.Free();
}
return t[0];
}
public static string GetString(byte[] msg, int offset, int length)
{
StringBuilder retVal = new StringBuilder(length);
unsafe
{
fixed (byte* pb = msg)
{
byte* pc = (byte*)(pb + offset);
for (int x = 0; x < length; x++)
{
if (pc[x] == 0) break;
retVal.Append((char)pc[x]);
}
}
}
return retVal.ToString(0, retVal.Length);
}
``` | Helper functions for marshalling arrays of structures (with pointers) | [
"",
"c#",
"arrays",
"pinvoke",
"marshalling",
"intptr",
""
] |
I have a base class with a virtual method, and multiple subclasses that override that method.
When I encounter one of those subclasses, I would like to call the overridden method, but without knowledge of the subclass. I can think of ugly ways to do this (check a value and cast it), but it seems like there should be an in-language way to do it. I want the List to contain multiple subclasses within the same list, otherwise obviously I could just make a List.
EDIT: Fixed the comment in the code that was wrong, which lead to the very appropriate first answer I got :)
For instance:
```
Class Foo
{
public virtual printMe()
{
Console.Writeline("FOO");
}
}
Class Bar : Foo
{
public override printMe()
{
Console.Writeline("BAR");
}
}
List<Foo> list = new List<Foo>();
// then populate this list with various 'Bar' and other overriden Foos
foreach (Foo foo in list)
{
foo.printMe(); // prints FOO.. Would like it to print BAR
}
``` | ```
class Foo
{
public virtual void virtualPrintMe()
{
nonVirtualPrintMe();
}
public void nonVirtualPrintMe()
{
Console.Writeline("FOO");
}
}
class Bar : Foo
{
public override void virtualPrintMe()
{
Console.Writeline("BAR");
}
}
List<Foo> list = new List<Foo>();
// then populate this list with various 'Bar' and other overriden Foos
foreach (Foo foo in list)
{
foo.virtualPrintMe(); // prints BAR or FOO
foo.nonVirtualPrintMe(); // always prints FOO
}
``` | Why should it print "Foo"? That is not the purpose of virtual methods. The whole point is that the derived classes can change the way the function works without changing the interface. A Foo object will print "Foo" and a Bar object will print "Bar". Anything else would be wrong. | C# calling overridden subclass methods without knowledge that it's a subclass instance | [
"",
"c#",
"inheritance",
"virtual",
"overriding",
"subclass",
""
] |
I'm in the process of refactoring an application and I've decided to use a mobile/embedded database.
I've been reading about SQL Server Compact Edition, but I was wondering if any of you knew of any other databases that could be used and don't have huge download sizes, as my current application is about ~2MB (installer). SQLite would be nice, but AFAIK the GSoC implementation of LINQ-to-SQLite is rather buggy at the moment.
Thanks! | [VistaDB](http://www.vistadb.net/) and (as you mentioned) [Sql Server Compact Edition](http://www.microsoft.com/Sqlserver/2005/en/us/compact-downloads.aspx) are two small options for an embedded database. Sql Server Compact Edition can be used with Linq to SQL or Entity Framework. I believe VistaDB can be used with the Entity Framework.
Also, if you do not require a relational database, you may want to consider [db4o](http://www.db4o.com/). Rob Conery writes about this [here](http://blog.wekeroad.com/blog/crazy-talk-reducing-orm-friction/).
Hope this helps! | I have tried out db40 once (not the compact edition) - it is an object database. However, depending on your needs it may be a rather comfortable thing to use. They note that they support linq even for the compact edition:
<http://www.db4o.com/s/compactframeworkdb.aspx> | What's a good "mobile" .NET database that supports LINQ? | [
"",
"c#",
".net",
"linq",
"embedded-database",
""
] |
I would need some basic vector mathematics constructs in an application. Dot product, cross product. Finding the intersection of lines, that kind of stuff.
I can do this by myself (in fact, have already) but isn't there a "standard" to use so bugs and possible optimizations would not be on me?
Boost does not have it. Their mathematics part is about statistical functions, as far as I was able to see.
**Addendum:**
Boost 1.37 indeed seems to have [this](http://www.boost.org/doc/libs/1_37_0/libs/numeric/ublas/doc/overview.htm). They also gracefully introduce a number of other solutions at the field, and why they still went and did their own. I like that. | Re-check that ol'good friend of C++ programmers called [Boost](http://www.boost.org). It has [a linear algebra package](http://www.boost.org/doc/libs/1_37_0/libs/numeric/ublas/doc/index.htm) that may well suits your needs. | I've not tested it, but the C++ [eigen library](http://eigen.tuxfamily.org/index.php?title=Main_Page) is becoming increasingly more popular these days. According to them, they are on par with the fastest libraries around there and their API looks quite neat to me. | Open source C++ library for vector mathematics | [
"",
"c++",
"math",
""
] |
Are there any resources with information creating a self contained, reusable module?
I need to create modules that I can drop into projects quickly and easily. An example would be a news module that would contain an admin area, news listing page, It supporting `CSS` & `JavaScript`, etc.
Am I smoking my socks or is this even possible? | You need plugins for your application.
I've got a [plugin library](http://www.thealphasite.org/es/c/librerias/monet_plugins_library) (in development and in Spanish) that you might use as an example or a starting point. I don't know how good google translate will be but you can check a C# plugin tutorial in <http://translate.google.com/translate?hl=es&ie=UTF-8&u=http://www.thealphasite.org/es/sistema_de_plugins_con_c_y_net&sl=es&tl=en>
A plugin allows you to plug in :P functionality into your application and, with a proper design, it will allow you to move functionality dinamically from one application to another.
Anyway, plugin just provide with ease of use but require a design specifically thought with them in mind. On the other hand, basic "take this module and use it in another project" is just proper encapsulation and good design. If a module is well designed the it should be able to be ported to another site or application with very little effort.
Keep in mind that, specifically for web, "theming" is a complex subject, that is, adapting your plugin to the way an specific web looks is another step of customization which has to be included into the module itself. You can see an example in the [Drupal theming functions](http://drupal.org/node/55126) and the [theming api documentation](http://api.drupal.org/api/function/theme/6). | Look at [www.allnewsmanager.net](http://www.allnewsmanager.net), maybe is what you are looking for. It is a reusable module, free and open source. | Creating a reusable cms module (C#) | [
"",
"c#",
"asp.net",
""
] |
If I have, say, a table of films which amongs other things has a int FilmTypeId field and a table of film types, with the id and a meaningful description along the lines of:
* 1 - horror
* 2 - comedy
* ...
Whats the best way of using that information in a C# class?
currently I would have them as Constants in a helper class (unsuprisingly air code):
```
public class FilmHelper
{
public const int HorrorFilmType = 1;
public const int ComedyFilmType = 2;
...
}
```
but this doesn't seem that maintainable. But I would like to avoid a database call everytime I came to use the constant or an additional db call everytime I used either the helper or the main entity. | Is the list of types fixed or does it change?
If fixed, I would encapsulate it in an enum:
```
public enum FilmType {
Horror = 1,
Comedy = 2
}
```
Then just cast. You can use attributes (and a few lines of bespoke code) to store an extra description per enum item.
If the list changes I would probably read it once early on in the app, and cache the list in a lookup somewhere (perhaps static, perhaps in a specific cache). Then just do the lookups from the cached copy.
You can take this further by adding properties that change between the two representations. | You can use a strong type without strongly-typing the values.
```
class FilmType : Dictionary<int, string> {}
```
Then just load the values at app load time, as Joel suggested.
If you're more concerned about the actual values at compile-time, then you're not going to do better than an enum. | Database Constants in a Class | [
"",
"c#",
""
] |
I have a page with a button that when I click, it retrieves data from a database and stores it into a datatable and binds it to a GridView. This datatable is stored in a Session variable. I also have a button that exports specified columns from the datatable to an excel file, but when I click the export button a second time, I get the following error:
Object reference not set to an instance of an object.
It seems to happen at this line:
dtExport.Columns["Business"].ColumnName = "Licensee";
I think I know why, the original column is called "Business", but when I export, I want to export the column header as Licensee, so I change the ColumnName to "Licensee"; however when I call Export a second time, it is looking for dtExport.Columns["Business"] again which it does not find, so it throws an error. Do I just need to check if the column as already been renamed to resolve this or is there another way?
Here is the code that does the Export:
```
private void ExportExcel()
{
DataTable dtExport = Session["dtSearchResults"] as DataTable;
dtExport.Columns["Business"].ColumnName = "Licensee";
List<int> columnSelect = new List<int>();
columnSelect.Add(dtExport.Columns["Licensee"].Ordinal);
columnSelect.Add(dtExport.Columns["Name"].Ordinal);
columnSelect.Add(dtExport.Columns["Address"].Ordinal);
columnSelect.Add(dtExport.Columns["City"].Ordinal);
columnSelect.Add(dtExport.Columns["State"].Ordinal);
columnSelect.Add(dtExport.Columns["Zip"].Ordinal);
int[] ColList = columnSelect.ToArray();
GridViewExportUtil.ExportDetails(dtExport,
ColList,
GridViewExportUtil.ExportFormat.Excel,
string.Format("{0}_{1}-{2}-{3}{4}",
"SearchResults",
DateTime.Now.Month,
DateTime.Now.Day,
DateTime.Now.Year,
".xls"));
}
```
When you change a ColumnName, does it persit, even if you get a new DataTable from Session again? | I am guessing the value is by reference, and when you change the Business column name it is changed in Session as well. I would try this:
```
DataTable dtExport = (Session["dtSearchResults"] as DataTable).Copy();
``` | You're not getting a new DataTable you are getting the same one that you originally generated. Any changes you make to it will remain to be seen by subsequent uses.
In this case I would rename the column back to its original name after the export. | Why am I losing the Session here? | [
"",
"c#",
"asp.net",
""
] |
I am new to grails.I am doing web application that uploads the image from client side and it stores that in server.
My Gsp code is:
```
<g:uploadForm action="saveImage">
<input type="file" name="image">
<input type="submit" value="Submit">
</g:uploadForm>
```
My saveImage action in controller is:
```
def saveImage={
def file = request.getFile('image')
if (file && !file.empty) {
file.transferTo(new java.io.File("image.jpg"))
flash.message = 'Image uploaded'
redirect(action: 'uploadImage')
}
}
```
In this code if i upload some other files like text files it throws Exception.For that i want to check the file Extension and I want to use If loop that ensures the uploaded file is image file or not.But i dont know how to find the file extension in grails.
Is there any other way to upload images in grails application.It has to accept only image files.
can anyone provide help?
thanks. | I dont know the following answer is a right way to find the extension of the file.I am also new to this.But this answer is working
Use **file.getOriginalFilename()** method.It returns a string like "test.jpg".Then you split the filename using tokenize method by ".".Then you take the last string element from the splitted list.That is extension of the file.Now you can do the remaining process. | Getting file extension from file.getOriginalFilename() works good.I think that is the better way. | image uploading in grails | [
"",
"java",
"grails",
"groovy",
"frameworks",
""
] |
Hello there and Merry Christmas !!!
I am new to WPF and I am trying to build a text editor for a assembly language. The assembler provides me a two lists:
* a list of errors
* a list of warnings
My editor should have the ability to inport the contents of a file and display it in a text-panel. I want it to be similar to Visual Studio. Line numbers on the side. And a tabbed pane for the warning/error messages.
Each list element contains the line number as an Int and a String that contains the error/warning message. (It would be really cool if I could click on it in the tabbed pane and it would jump to that line and highlight it.)
How I said I am new to WPF, I don't know the control library and I don't have too much time to dig and get friendly with google.
So I would really appreciate it if someone could point me to at least the controls I need to develop my GUI.
My best regards,
John | All I has for you is two links:
* [CodeyProject](http://www.codeproject.com/KB/WPF/WPFdockinglib.aspx)
* [Commercial one (SandDock)](http://www.divelements.co.uk/net/controls/sanddockwpf/) | Free one <http://blog.bodurov.com/Wpf-Source-Code-Editor> | How to build a simple source code editor using WPF? | [
"",
"c#",
"wpf",
"text-editor",
""
] |
I'm in need of a C++ (pseudo, i don't care) random number generator that can get me different numbers every time I call the function. This could be simply the way I seed it, maybe there's a better method, but every random generator I've got doesn't generate a new number every time it's called. I've got a need to get several random numbers per second on occasion, and any RNG i plug in tends to get the same number several times in a row.
Of course, I know why, because it's seeded by the second, so it only generates a new number every second, but I need to, somehow, get a new number on every call. Can anyone point me in the right direction? | Sounds like you do it like this:
```
int get_rand() {
srand(time(0));
return rand();
}
```
Which would explain why you get the same number within one second. But you have to do it like this:
```
int get_rand() {
return rand();
}
```
And call srand *once* at program startup. | You only need to seed the generator once with `srand()` when you start, after that just call the `rand()` function. If you seed the generator twice with the same seed, you'll get the same value back each time. | A random number generator that can get different numbers in < a second | [
"",
"c++",
"random",
""
] |
This is my first time with Web services. I have to develop web services in java which should be having good WS-\* standards, should loosely-coupled, scalable, highly secure, fast response time. I know I've to consider trade-offs. I have checked on some frameworks like Axis2, CXF, Spring WS. Please share your experiences and views on these frameworks and other frameworks, which will help me in deciding which one to go to. | I would also recommend taking a look at [JAX-WS 2.0](http://jcp.org/en/jsr/detail?id=224). It is also easy to use with very little configuration and annotations. Mark Hansen's [book](https://rads.stackoverflow.com/amzn/click/com/0130449687) does a good job explaining SOA using jax-ws. | I'm a Spring user, so I'm doing it with Spring WS 1.5.5. Very nice, especially using annotations. | Java web service frameworks | [
"",
"java",
"web-services",
""
] |
We're doing a great deal of floating-point to integer number conversions in our project. Basically, something like this
```
for(int i = 0; i < HUGE_NUMBER; i++)
int_array[i] = float_array[i];
```
The default C function which performs the conversion turns out to be quite time consuming.
Is there any work around (maybe a hand tuned function) which can speed up the process a little bit? We don't care much about a precision. | Most of the other answers here just try to eliminate loop overhead.
Only [deft\_code's answer](https://stackoverflow.com/a/429812/768469) gets to the heart of what is likely the real problem -- that converting floating point to integers is shockingly expensive on an x86 processor. deft\_code's solution is correct, though he gives no citation or explanation.
Here is the source of the trick, with some explanation and also versions specific to whether you want to round up, down, or toward zero: [Know your FPU](http://www.stereopsis.com/sree/fpu2006.html)
Sorry to provide a link, but really anything written here, short of reproducing that excellent article, is not going to make things clear. | ```
inline int float2int( double d )
{
union Cast
{
double d;
long l;
};
volatile Cast c;
c.d = d + 6755399441055744.0;
return c.l;
}
// this is the same thing but it's
// not always optimizer safe
inline int float2int( double d )
{
d += 6755399441055744.0;
return reinterpret_cast<int&>(d);
}
for(int i = 0; i < HUGE_NUMBER; i++)
int_array[i] = float2int(float_array[i]);
```
The double parameter is not a mistake! There is way to do this trick with floats directly but it gets ugly trying to cover all the corner cases. In its current form this function will round the float the nearest whole number if you want truncation instead use 6755399441055743.5 (0.5 less). | How to speed up floating-point to integer number conversion? | [
"",
"c++",
"c",
"performance",
"optimization",
"floating-point",
""
] |
I need to lock the browser scrollbars when I show a div that represent a modal window in Internet Explorer 7 only.
Googling I found that I can use `document.body.style.overflow='hidden'` but this doesn't work for IE7. I also tried with `document.body.scroll="no"` which works but only after I mouse over the scrollbar :-S
Does anybody knows a better aproach?
Thansks | To answer your various questions (including that in your other comment), I think you're using the wrong positioning method.
Try `position:fixed`. It's basically the same as `position:absolute` apart from it's relative to the absolute viewport. Ie: if the user scrolls, the item stays in the same place on the screen.
So with this in mind, you can lay out a `position:fixed` overlay. Within that you can have your `position:absolute` (or `fixed` again, if you prefer -- it *shouldn't* make a difference) modal box. | Set your modal overlay div to fill the body, so even if they scroll there's nothing they can do because everything is hidden underneath it. | How to disable scrollbars with JavaScript? | [
"",
"javascript",
"internet-explorer-7",
"scrollbar",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.