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 ta...
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(); } }...
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...
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&gt;"); ``` But Anthony's right: right angle brackets in text nodes shouldn't cause any problems. And matching HTML with regexes is tricky; fo...
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 con...
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 = Arra...
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 ...
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 inlin...
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 o...
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...
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 an...
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 exper...
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,...
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.o...
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). ...
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 reme...
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.Collect...
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 an...
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 coul...
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...
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 te...
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 "I...
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 som...
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 c...
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 effici...
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, t...
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/javascri...
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() }); ... (func...
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(respo...
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 i...
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 a...
> 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 ...
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 subje...
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 ...
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 y...
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, ...
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 ``` Overridin...
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 ``` Ch...
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...
`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 t...
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...
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> ...
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 ...
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 , bu...
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(Tre...
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 docum...
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' (l...
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++...
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; f...
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.C...
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. Th...
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 s...
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...
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...
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 ...
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")][...
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...
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`]...
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...
[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/) (previousl...
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...
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 ...
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 ...
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 ...
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 par...
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 float...
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. ...
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 app...
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=$postl...
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...
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 t...
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, nu...
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 th...
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 th...
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...
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) { //The...
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:\\Win...
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...
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_REF...
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 M...
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](ht...
**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 ...
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 arch...
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 hav...
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 in...
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 ...
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...
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".ConvertToL...
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....
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:...
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: ...
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.compa...
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-throu...
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...
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()...
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; c...
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...
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 disc...
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) { StringB...
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...
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...
[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 slig...
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 t...
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 { ...
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 r...
**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 = ...
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 O...
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 t...
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) ...
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....
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 Clien...
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/0...
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 i...
**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...
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...
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 questio...
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 `SC...
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 d...
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 o...
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 ...
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 ...
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 : BaseRetu...
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 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> ...
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....
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...
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 contrac...
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 h...
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,...
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,...
``` 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 boxi...
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...
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 wai...
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 &...
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 mov...
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 Sett...
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 tr...
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 ...
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 u...
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_na...
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 ...
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 ...
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 ...
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 = (d...
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 ...
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/helpdes...
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 de...
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: ```...
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 ``` myCla...
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 th...
`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 as...
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 ...
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 Ide...
``` 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...
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...
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 : ISer...
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 ...
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], ...
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, ...
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...
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 taki...
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 ...
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 explici...
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/interes...
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...
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.ApplicationD...
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 c...
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 t...
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 unio...
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 ...
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...
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 fin...
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...
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...
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</artif...
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...
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 o...
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 vo...
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 ...
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 { ...
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 ...
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, bu...
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 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 lo...
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_...
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 `snprin...
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 s...
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"); ...
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 ...
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 a...
``` 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...
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 (installe...
[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...
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....
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 i...
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://tra...
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 helpe...
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 ...
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...
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...
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 splitt...
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...
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 se...
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 experience...
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 ...
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, tho...
``` 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<...
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 :-...
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. S...
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", "" ]