Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am trying to right align a control in a [`StatusStrip`](http://msdn.microsoft.com/en-us/library/system.windows.forms.statusstrip.aspx). How can I do that? I don't see a property to set on `ToolStripItem` controls that specifies their physical alignment on the parent `StatusStrip`. [How do I get Messages drop down t...
Found it via MSDN forums almost immediately after posting :) You can use a [`ToolStripLabel`](http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripstatuslabel.aspx) to pseudo right align controls by setting the `Text` property to `string.Empty` and setting the `Spring` property to `true`. This will ca...
For me it took two simple steps: 1. Set `MyRightIntendedToolStripItem.Alignment` to `Right` 2. Set `MyStatusStrip.LayoutStyle` to `HorizontalStackWithOverflow`
How do I right align controls in a StatusStrip?
[ "", "c#", "winforms", "statusstrip", "" ]
I've managed to use [Sun's MSCAPI provider](http://java.sun.com/javase/6/docs/technotes/guides/security/SunProviders.html#SunMSCAPI) in my application. The problem I'm having now is that it always pops up a window, asking for a password, even though I've provided it in the code. This is a problem, because I need the cr...
The MSCAPI provider does not support providing the password to CAPI: > A compatibility mode is supported for applications that assume a password must be supplied. It permits (but ignores) a non-null password. The mode is enabled by default. [(1)](http://www.java2s.com/Open-Source/Java-Document/6.0-JDK-Platform/windows...
My guess is that Windows is popping up the pop up. Import your key again using the Certificate Import Wizard, but make sure that you don't check the following option on the "Password" screen. > [\_] Enable strong private key protection. You will be prompted every time the private key is used by an application if you ...
Java security - MSCAPI provider: How to use without password popup?
[ "", "java", "security", "cryptography", "cryptoapi", "" ]
I was refactoring some code, and part of it included moving it from VB.Net to C#. The old code declared a member like this: ``` Protected viewMode As New WebControl ``` The new code, I eventually got working, like this: ``` protected WebControl _viewMode = new WebControl(HtmlTextWriterTag.Span); ``` I can presume ...
The reason this worked in VB, and not in C#, had nothing to do with assemblies. The default constructor for WebControl is protected. VB and C# have different interpretations of what "protected" means. In VB, you can access a protected member of a class from any method in any type that derives from the class. That i...
The default constructor for WebControl (implicit in the VB line) is to use a span. You can call that constructor in c# as well as VB.NET.
Difference between VB.Net and C# "As New WebControl"
[ "", "c#", ".net", "asp.net", "vb.net", "clr", "" ]
I am familiar with sending email from Java programs. Is it possible to configure the email so that Outlook will recognize that it should expire at a certain time?
Add a header to the `MimeMessage` called `"Expiry-Date"` using the (joda-time) format `"EEE MMM d HH:mm:ss yyyy Z"` The other answers are good, but I used a slightly different format.
I believe Outlook honors the, now deprecated, Expiry-Date header. You can add this to the MimeMessage headers. The format for the value is `"EEE, d MMM yyyy hh:mm:ss Z"`
How can I send an email from Java that will auto-expire in Outlook?
[ "", "java", "email", "outlook", "" ]
So I was playing around the other day just to see exactly how mass assignment works in JavaScript. First I tried this example in the console: ``` a = b = {}; a.foo = 'bar'; console.log(b.foo); ``` The result was "bar" being displayed in an alert. That is fair enough, `a` and `b` are really just aliases to the same o...
In the first example, you are setting a property of an existing object. In the second example, you are assigning a brand new object. ``` a = b = {}; ``` `a` and `b` are now pointers to the same object. So when you do: ``` a.foo = 'bar'; ``` It sets `b.foo` as well since `a` and `b` point to the same object. *Howev...
Your question has already been satisfyingly answered by Squeegy - it has nothing to do with objects vs. primitives, but with reassignment of variables vs. setting properties in the same referenced object. There seems to be a lot of confusion about JavaScript types in the answers and comments, so here's a small introdu...
How does variable assignment work in JavaScript?
[ "", "javascript", "" ]
I'm writing some code that handles logging xml data and I would like to be able to replace the content of certain elements (eg passwords) in the document. I'd rather not serialize and parse the document as my code will be handling a variety of schemas. Sample input documents: doc #1: ``` <user> <userid>jsm...
This problem is best solved with XSLT: ``` <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> ...
I'd say you're better off parsing the content with a .NET XmlDocument object and finding password elements using XPath, then changing their innerXML properties. It has the advantage of being more correct (since XML isn't regular in the first place), and it's conceptually easy to understand.
Using C# Regular expression to replace XML element content
[ "", "c#", ".net", "xml", "regex", "parsing", "" ]
I a modeling a system to evaluate expressions. Now the operands in these expressions can be of one of several types including some primitive .NET types. When defining my Expression class, I want some degree of type-safety and therefore don't want to use 'object' for the operand object type, so I am considering defining...
How about `Expression` in 3.5? I recently wrote an expression parser/compiler using this.
I'm not sure if C based languages have this, however Java has several packages that would really make sense for this. The JavaCC or java compiler compiler allows you to define a language (your expressions for example) and them build the corresponding java classes. A somewhat more user friendly if not more experimental...
Expression evaluation design questions
[ "", "c#", "oop", "" ]
A few weeks ago I asked the question *"Is a PHP, Python, PostgreSQL design suitable for a non-web business application?"* [Is a PHP, Python, PostgreSQL design suitable for a business application?](https://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application) A lot of...
You seem to be saying that choosing Django would prevent you from using a more heterogenous solution later. This isn't the case. Django provides a number of interesting connections between the layers, and using Django for all the layers lets you take advantage of those connections. For example, using the Django ORM mea...
Django will happily let you use whatever libraries you want for whatever you want to use them for -- you want a different ORM, use it, you want a different template engine, use it, and so on -- but is designed to provide a common default stack used by many interoperable applications. In other words, if you swap out an ...
Does Django development provide a truly flexible 3 layer architecture?
[ "", "python", "django", "model-view-controller", "orm", "" ]
Following up on [this comment](https://stackoverflow.com/questions/452139/writing-firmware-assembly-or-high-level#452401) from the question [Writing firmware: assembly or high level?](https://stackoverflow.com/questions/452139/writing-firmware-assembly-or-high-level): When compiling C++ code for the [Arduino](http://a...
The Arduino environment uses the AVR version of the GCC toolchain. The code is compiled as C++, so you can use classes. Virtual functions are possible; the vtables will be stored in the .data section and have the correct addresses. In fact, the Print base class uses virtual functions to adapt the various "print" method...
The Arduino software uses avr-gcc to compile sketches. The following limitations were sourced from the [avrlibc FAQ (Can I use C++ on the AVR?)](http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_cplusplus): **Supported** * Virtual functions * Constructors and destructors (including global ones) **Not supported...
Arduino C++ code: can you use virtual functions and exceptions?
[ "", "c++", "arduino", "virtual-functions", "firmware", "" ]
I have been wondering how to put all the stored procedures on a SQL 2000 under source control. We are using Subversion for all our normal source code, so it would be great if there were a solution to the problem using Subversion. Do you have any ideas? Update 16-02-2009: This is the vbs script i used to export all...
As other people have said, start off with each stored proc in a separated text file that is under source control. Write a script that deletes all you stored procedures then re-creates them from the text files (while logging/reporting any errors) – this script should be easy to run. Then every time you update from sourc...
Usually you track the changes to SQL scripts in source control. For example, you have a checkin for your base schema for your database. Then you keep adding new SQL files for changes to your schema. That way you can deploy to an exact version for testing purposes. Then you can use build automation to automatically test...
Source Control and stored procedures
[ "", "sql", "sql-server", "version-control", "stored-procedures", "" ]
I read the Java tutorials on Sun for JAR files, but I still can't find a solution for my problem. I need to use a class from a jar file called jtwitter.jar, I downloaded the file, and tried executing it (I found out yesterday that .jar files can be executed by double clicking on them) and Vista gave me an error saying ...
Not every jar file is executable. Now, you need to import the classes, which are there under the jar, in your java file. For example, ``` import org.xml.sax.SAXException; ``` If you are working on an IDE, then you should refer its documentation. Or at least specify which one you are using here in this thread. It wou...
Let's say we need to use the class `Classname` that is contained in the jar file `org.example.jar` And your source is in the file `mysource.java` Like this: ``` import org.example.Classname; public class mysource { public static void main(String[] argv) { ...... } } ``` First, as you see, in your code yo...
How to use classes from .jar files?
[ "", "java", "jar", "" ]
I'm working on an interface to allow our clients to update their DNS on their own. I have 2 questions: 1. What constitutes valid a valid host and target records? (A, CNAME, MX, TXT) i.e. if the user enters ........ for the host and target the DNS server won't like that. 2. Is there a regex I can use to sanitize user ...
Domain name *labels* can technically contain any octet value, but *usually* they only contain alphanumerics and the hyphen and underscore characters. This comes from recommendations in section 2.3.1 of [RFC 1035](http://www.ietf.org/rfc/rfc1035.txt): > The labels must follow the rules for > ARPANET host names. They m...
The answer used to be easy, but not anymore. You can use almost any Unicode characters, but they should go thru a normalization, and encoding process. See RFC 3490 (IDNA), RFC 3454 (Stringprep), RFC 3491 (Nameprep), RFC 3492 (Punycode) Or go with Wikipedia for the big picture (<http://en.wikipedia.org/wiki/Internati...
What are valid characters for a DNS Zone file and how can I sanitize user input?
[ "", "c#", "dns", "bind", "" ]
Every time I use Setup & Deployment to create a new Web Setup, and run it (after edit all the nice things in the properties), the output is always a copy of the Web Site project... How can I output a PreCompile version of the WebSite project? What I did was, publish the Web Site (so I get the precompiled version), ad...
I see you tried the standard Web Setup project from VS. Scott Gu's blog post takes you to this page: [Visual Studio 2008 Web Deployment Projects](http://www.microsoft.com/downloads/details.aspx?FamilyID=0aa30ae8-c73b-4bdd-bb1b-fe697256c459&DisplayLang=en) which is a plugin for Visual Studio that activates an addition...
I was searching for this solution from google for long days. What i did is i precompiled my website to one folder and added that folder as a new website to my solution(While adding it will give a warning message that it was already precompiled content. No probs). Now add this project output to the my setup project and ...
pre compile website in Setup & Deployment
[ "", "c#", "asp.net", "visual-studio-2008", "setup-deployment", "" ]
I often find I want to write code something like this in C#, but I am uncomfortable with the identifier names: ``` public class Car { private Engine engine; public Engine Engine { get { return engine; } set { engine = value; } } ...
In this case, I would name them exactly as they are in the example. This is because the naming is clear as to what data each element holds and/or will be used for. The only thing I would change for C#3 is to use an auto-property which would remove the local variable.
For private members I always prefix with an underscore: ``` private Engine engine; ``` becomes: ``` private Engine _engine; ``` Whenever I see `m_`, it makes my stomach churn.
How would you name these related Property, Class, Parameter and Field in .NET?
[ "", "c#", ".net", "" ]
My compiler (VC++ 6.0 sp6) has apparently gone insane. In certain pieces of code I'm seeing that '`bool mybool = true;`' evalutes to and assigns false, and vice versa for true. Changing the true/false keywords to 1/0 makes it work fine. The same code compiles elsewhere fine without changing the true/false keywords. Wh...
A preprocessor macro could certainly do it, although that would be pretty surprising. One way to check if that is the case would be ``` #ifdef true # error "true is defined as a macro" #endif #ifdef false # error "false is defined as a macro" #endif ``` Response to comments: Find a non-header file where you see th...
Buffer overflows and writing into uninitialized memory can also account for such behavior. For example, if you have an array and bool allocated in adjacent memory locations and accidentally write beyond the bounds of the array.
C++ 'true' and 'false' keywords suddenly not true or false in Visual C++ 6.0
[ "", "c++", "visual-c++", "" ]
I am getting a string hash like this: ``` string content = "a very long string"; int contentHash = content.GetHashCode(); ``` I am then storing the hash into a dictionary as key mapping to another ID. This is useful so I don't have to compare [big strings](http://dotnetperls.com/Content/Dictionary-String-Key.aspx) du...
Just to add some detail as to where the idea of a changing hashcode may have come from. As the other answers have rightly said the hashcode for a specific string will always be the same for a specific runtime version. There is no guarantee that a newer runtime might use a different algorithm perhaps for performance re...
Yes, it will be consistent since strings are immutable. However, I think you're misusing the dictionary. You should let the dictionary take the hash of the string for you by using the string as the key. Hashes are not guaranteed to be unique, so you may overwrite one key with another.
Can I be sure the built-in hash for a given string is always the same?
[ "", "c#", ".net", "string", "hash", "" ]
This might be a stupid question, but I can't for the life of me figure out how to select the row of a given index in a QListView. QAbstractItemView , QListView's parent has a setCurrentIndex(const QModelIndex &index). The problem is, I can't construct a QModelIndex with the row number I want since the row and column f...
You construct the QModelIndex by using the createIndex(int row, int column) function of the model you gave to the view. QModelIndexes should only be used once, and must be created by the factory in the model.
[This](http://doc.trolltech.com/4.4/model-view-selection.html) should help you get started ``` QModelIndex index = model->createIndex( row, column ); if ( index.isValid() ) model->selectionModel()->select( index, QItemSelectionModel::Select ); ```
Selecting an index in a QListView
[ "", "c++", "user-interface", "qt", "" ]
This is a follow up to a question I just posted. I'm wondering how you all handle member variables in javascript clases when using MyClass.prototype to define methods. If you define all of the methods in the constructor function: ``` function MyClass(){ this.myMethod = function(){} } ``` You can very nicely declare...
You should get over your aversion to using the `this` pointer to access member variables. Assign member variables in the constructor, and you can access them with prototype methods: ``` function Cat(){ this.legs = 4; this.temperament = 'Apathetic'; this.sound = 'Meow'; } Cat.prototype.speak = function(){...
The visiblity of object attributes varies according to how you declare them ``` function Cat( name ) { //private variable unique to each instance of Cat var privateName = 'Cat_'+Math.floor( Math.random() * 100 ); //public variable unique to each instance of Cat this.givenName = name; //this meth...
best approach to member variables in object-oriented javascript?
[ "", "javascript", "" ]
I frequently use HTML output in applications, up to now I've used some simple routines to build an HTML string. I want to try something different now: I want to serialize the data to XML, and provide some XSLT templates to generate the HTML for the webbrowser control. I get that to work statically (slowly digging thro...
Usually the way to go is to provide parameters to the transform at runtime and writing the transform so that its behavior is controlled by the parameters. Usually when I do this, I only pass in one parameter - an XML document - and make the templates query it to determine what they should do. So you'll see stuff like:...
[`XslCompiledTransform`](http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx) supports [parameters](http://msdn.microsoft.com/en-us/library/system.xml.xsl.xsltargumentlist.addparam.aspx), and also [extension objects](http://msdn.microsoft.com/en-us/library/system.xml.xsl.xsltargumentlist.ad...
"dynamic" XSLT to feed webbrowser control?
[ "", "c#", "xml", "xslt", "webbrowser-control", "" ]
I'm writing this question with reference to [this one](https://stackoverflow.com/questions/475888/will-this-lead-to-a-memory-leak-in-c) which I wrote yesterday. After a little documentation, it seems clear to me that what I wanted to do (and what I believed to be possible) is nearly impossible if not impossible at all....
The problem you are having is that the expression `a * b` creates a *temporary* object, and in C++, a temporary is not allowed to bind to a non-constant reference, which is what your `Matrix& operator=(Matrix& m)` takes. If you change it to: ``` Matrix& operator=(Matrix const& m); ``` The code should now compile. As ...
You should really read [Effective C++](https://rads.stackoverflow.com/amzn/click/com/0321334876) by Scott Meyers, it has great topics on that. As already said, the best signatures for `operator=` and `operator*` are ``` Matrix& operator=(Matrix const& m); Matrix operator*(Matrix const& m) const; ``` but I have to say...
Coding practice: return by value or by reference in Matrix multiplication?
[ "", "c++", "reference", "scope", "return", "" ]
I am starting a project from scratch using Intersystems Cache. I would like to setup a Continuous Integration Server for the project. Cache has unit test libraries, so the idea is to import source into a test database, build the source, run unit tests in the cache terminal, based on changes in the version control syste...
I'd recommend looking at [Hudson](http://hudson-ci.org/). It's insanely easy to try out as it is delivered as an executable jar. It also supports [plugins](http://hudson.gotdns.com/wiki/display/HUDSON/Extend+Hudson) so it may be better suited to extension and customization. There are also a good deal of very handy plug...
I have built a makeshift Continuous Integration Server in the following screencast: <http://www.ensemblisms.com/episodes/2>
Continuous Integration for Intersystems Cache solutions
[ "", "java", "continuous-integration", "intersystems-cache", "intersystems", "" ]
I just wonder if it is possible to send Meeting Requests to people without having Outlook installed on the Server and using COM Interop (which I want to avoid on a server at all costs). We have Exchange 2003 in a Windows 2003 Domain and all users are domain Users. I guess I can send 'round iCal/vCal or something, but ...
The way to send a meeting request to Outlook (and have it recognized) goes like this: * prepare an iCalendar file, be sure to set these additional properties, as Outlook needs them: + [`UID`](http://www.kanzaki.com/docs/ical/uid.html) + [`SEQUENCE`](http://www.kanzaki.com/docs/ical/sequence.html) + [`CREATED`](h...
See the DDay.iCal C# library on sourceforge: <http://sourceforge.net/projects/dday-ical/> Then read this codeproject article: <http://www.codeproject.com/Articles/17980/Adding-iCalendar-Support-to-Your-Program-Part-1> And read this: [Export event with C# to iCalendar and vCalendar format](https://stackoverflow....
Sending Outlook meeting requests without Outlook?
[ "", "c#", ".net", "outlook", "" ]
I wrote an application server (using python & twisted) and I want to start writing some tests. But I do not want to use Twisted's Trial due to time constraints and not having time to play with it now. So here is what I have in mind: write a small test client that connects to the app server and makes the necessary reque...
**"My question is: Is this a correct approach?"** It's what you chose. You made a lot of excuses, so I'm assuming that your pretty well fixed on this course. It's not the best, but you've already listed all your reasons for doing it (and then asked follow-up questions on this specific course of action). "correct" does...
You should use Trial. It really isn't very hard. Trial's documentation could stand to be improved, but if you know how to use the standard library unit test, the only difference is that instead of writing ``` import unittest ``` you should write ``` from twisted.trial import unittest ``` ... and then you can return...
unit testing for an application server
[ "", "python", "unit-testing", "twisted", "" ]
Let's say I have a database column 'grade' like this: ``` |grade| | 1| | 2| | 1| | 3| | 4| | 5| ``` Is there a non-trivial way in SQL to generate a histogram like this? ``` |2,1,1,1,1,0| ``` where 2 means the grade 1 occurs twice, the 1s mean grades {2..5} occur once and 0 means grade 6 does not o...
``` SELECT COUNT(grade) FROM table GROUP BY grade ORDER BY grade ``` Haven't verified it, but it should work.It will not, however, show count for 6s grade, since it's not present in the table at all...
If there are a lot of data points, you can also [group ranges together](https://web.archive.org/web/20180205094300/https://www.wagonhq.com/sql-tutorial/creating-a-histogram-sql "ARCHIVE of https://www.wagonhq.com/sql-tutorial/creating-a-histogram-sql") like this: ``` SELECT FLOOR(grade/5.00)*5 As Grade, COUNT(...
Generating a histogram from column values in a database
[ "", "sql", "sql-server", "histogram", "" ]
This is a poll of sorts about common concurrency problems in Java. An example might be the classic deadlock or race condition or perhaps EDT threading bugs in Swing. I'm interested both in a breadth of possible issues but also in what issues are most common. So, please leave one specific answer of a Java concurrency bu...
The most common concurrency problem I've seen, is not realizing that a field written by one thread is *not guaranteed* to be seen by a different thread. A common application of this: ``` class MyThread extends Thread { private boolean stop = false; public void run() { while(!stop) { doSomeWork(); ...
My **#1 most painful** concurrency problem ever occurred when **two different** open source libraries did something like this: ``` private static final String LOCK = "LOCK"; // use matching strings // in two different libraries public doSomestuff() { synchronized(LOCK)...
What is the most frequent concurrency issue you've encountered in Java?
[ "", "java", "multithreading", "concurrency", "" ]
I have a List<> of objects in C# and I need a way to return those objects that are considered duplicates within the list. I do not need the Distinct resultset, I need a list of those items that I will be deleting from my repository. For the sake of this example, lets say I have a list of "Car" types and I need to know...
I inadvertently coded this yesterday, when I was trying to write a "distinct by a projection". I included a ! when I shouldn't have, but this time it's just right: ``` public static IEnumerable<TSource> DuplicatesBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TK...
``` var duplicates = from car in cars group car by car.Color into grouped from car in grouped.Skip(1) select car; ``` This groups the cars by color and then skips the first result from each group, returning the remainder from each group flattened into a single sequenc...
C# 3.0: Need to return duplicates from a List<>
[ "", "c#", "linq", "lambda", "iequalitycomparer", "" ]
I would like to store an object **FOO** in a database. Lets say FOO contains three integers and a list of "*Fruits*". The list can have any length, the only thing I know is that the all the fruits allowed are stored in another table. Can I store the fruit list in a column?
In a normalized relational database, such a situation is unacceptable. You should have a junction table that stores one row for each distinct ID of the FOO object and the ID of the Fruit. Existence of such a row means the fruit is in that list for the FOO. ``` CREATE TABLE FOO ( id int primary key not null, int1 ...
If you're quite sure of what you're doing (ie. you won't need to look up the list's values, for example), you could also serialize your object, or just the list object, and store it in a binary column. Just character-separating the values may be fine too, and cheaper in terms of saving and loading, but be careful your...
How to store a list in a db column
[ "", "sql", "database", "" ]
I have create a getDBConnection method in my Java application. This returns a connection object, and hence I haven't closed this connection in this method itself. Now, I am invoking this method from various methods in my application at regular intervals, and closing them inside a try - finally block. I thought this sh...
Your code looks sane. That's how you're creating a new connection. Probably the error is where you close it. You should close it in a finally block. Some additional questions. 1) Are you sure those 50 conections come from this program ? Maybe there are some others comming from your same office. To confirm this you...
You could take a Singleton approach to the problem and only create a new Connection object if the current one is null: ``` If (connectionObject != null){ return connectionObject; }else { //create new connection object } ``` This will make sure that you only have one non-null connection at any time.
JDBC Connection Issue
[ "", "java", "jdbc", "connection", "" ]
I'm hoping to clear some things up with anonymous delegates and lambda expressions being used to create a method for event handlers in C#, for myself at least. Suppose we have an event that adds either an anonymous delegate or a lambda expression (for you lucky crowds that can use newer versions of .NET). ``` SomeCla...
If object X has an event handler whose *target* is object Y, then object X being alive means that object Y can't be garbage collected. It doesn't stop object X from being garbage collected. Normally when something is disposed, it will become garbage pretty soon anyway, which means you don't have a problem. The proble...
I think the problem is you seem to be proceeding from the assumption that having a delegate assigned to an object's event prevents it from being GCed. This as a simple statement is not true. With that said the perceived problem disappears. Initially in garbage collection everything is garbage. The GC runs through ev...
EventHandlers and Anonymous Delegates / Lambda Expressions
[ "", "c#", "events", "delegates", "lambda", "anonymous-methods", "" ]
I have a a C# (FFx 3.5) application that loads DLLs as plug-ins. These plug-ins are loaded in separate AppDomains (for lots of good reasons, and this architecture cannot change). This is all well and good. I now have a requirement to show a Dialog from one of those plug-ins. Bear in mind that I *cannot* return the dia...
Try using appdomain1's main form's BeginInvoke with a delegate that displays the form from appdomain2. So in Pseudocode: ``` Appdomain1: AppDomain2.DoSomething(myMainForm); AppDomain2: DoSomething(Form parent) { Form foolishForm = new Form(); parent.BeginInvoke(new Action( delegate { fooli...
We have a very similarly architected application that loads DLL files and plugins. Each DLL file is loaded in a separate [application domain](http://en.wikipedia.org/wiki/Application_Domain), which is created on a separate thread. We have a third-party control in a form that would not appear unless we call `System.Wind...
Message Pumps and AppDomains
[ "", "c#", "appdomain", "" ]
When I use file\_get\_contents and pass it as a parameter to another function, without assigning it to a variable, does that memory get released before the script execution finishes? For Example: ``` preg_match($pattern, file_get_contents('http://domain.tld/path/to/file.ext'), $matches); ``` Will the memory used by ...
The temporary string created to hold the file contents will be destroyed. Without delving into the sources to confirm, here's a couple of ways you can test that a temporary value created as a function parameter gets destroyed: ## Method 1: a class which reports its destruction This demonstrates lifetime by using a cl...
In your example the memory will be released when `$matches` goes out of scope. If you weren't storing the result of the match the memory would be released immediately
Does the memory used by file_get_contents() get released when it is not assigned to a variable?
[ "", "php", "memory-consumption", "" ]
I'm wondering how can I submit a form via Ajax (using prototype framework) and display the server response in a "result" div. The html looks like this : ``` <form id="myForm" action="/getResults"> [...] <input type="submit" value="submit" /> </form> <div id="result"></div> ``` I tried to attach a javascript f...
Check out Prototype API's pages on [`Form.Request`](http://www.prototypejs.org/api/form/request) and [`Event`](http://www.prototypejs.org/api/event) handling. Basically, if you have this: ``` <form id='myForm'> .... fields .... <input type='submit' value='Go'> </form> <div id='result'></div> ``` Your js would be, mo...
You need to return the value false from the ajax function, which blocks the standard form submit. ``` <form id="myForm" onsubmit="return myfunc()" action="/getResults"> function myfunc(){ ... do prototype ajax stuff... return false; ``` } Using onsubmit on the form also captures users who submit with the ente...
submit a form via Ajax using prototype and update a result div
[ "", "javascript", "ajax", "prototypejs", "form-submit", "" ]
How do I change directory to the directory with my Python script in? So far, I figured out I should use `os.chdir` and `sys.argv[0]`. I'm sure there is a better way then to write my own function to parse argv[0].
``` os.chdir(os.path.dirname(__file__)) ```
`os.chdir(os.path.dirname(os.path.abspath(__file__)))` should do it. `os.chdir(os.path.dirname(__file__))` would not work if the script is run from the directory in which it is present.
Change directory to the directory of a Python script
[ "", "python", "scripting", "directory", "" ]
In Yahoo or Google and in many websites when you fill up a form and if your form has any errors it gets redirected to the same page. Note that the data in the form remains as it is. I mean the data in the text fields remains the same. I tried ‹form action="(same page here)" method="post or get"›. It gets redirected to ...
Here is a modified version of what I use for *very* simple websites where I don't want/need an entire framework to get the job done. ``` function input($name, $options = array()) { if(!isset($options['type'])) $options['type'] = 'text'; $options['name'] = $name; if(isset($_POST[$name]) && $options['type'...
You need to do this yourself. When the page gets posted you'll have access to all the form values the user entered via $POST['...']. You can then re-populate the form fields with this data.
How do you post the contents of form to the page in which it is?
[ "", "php", "html", "" ]
Suppose I have the following (rather common) model Client invokes web service request -> request added to server queue -> server invokes 3rd party app via web service -> 3rd party app notifies server that event processing is finished -> server notifies client that request is completed What I am wondering about is the...
You can certainly do this via reflection: ``` MyClass o = new MyClass(); MethodInfo method = o.GetType().GetMethod("UnknownMethod", BindingFlags.Instance | BindingFlags.Public); MyRetValue retValue = (MyRetValue) method.Invoke(o, new object[] { "Arg1", 2, "Arg3" }); ```
To expand on Robert's answer you can do it with generics and stuff: ``` public TReturn DynamicInvoker<T, TReturn>(T obj, string methodName, param[] args){ MethodInfo method = obj.GetType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public); (TResult)method.Invoke(obj, args); } ``` If you wanted to m...
C# Calling a method I dont yet know the name of yet? Reflection?
[ "", "c#", "web-services", "" ]
We have to build Strings all the time for log output and so on. Over the JDK versions we have learned when to use `StringBuffer` (many appends, thread safe) and `StringBuilder` (many appends, non-thread-safe). What's the advice on using `String.format()`? Is it efficient, or are we forced to stick with concatenation f...
I wrote a small class to test which has the better performance of the two and + comes ahead of format. by a factor of 5 to 6. Try it your self ``` import java.io.*; import java.util.Date; public class StringTest{ public static void main( String[] args ){ int i = 0; long prev_time = System.currentTimeMill...
I took [hhafez](https://stackoverflow.com/a/513705/1845976)'s code and added a **memory test**: ``` private static void test() { Runtime runtime = Runtime.getRuntime(); long memory; ... memory = runtime.freeMemory(); // for loop code memory = memory-runtime.freeMemory(); ``` I run this separat...
Should I use Java's String.format() if performance is important?
[ "", "java", "string", "performance", "string-formatting", "micro-optimization", "" ]
How can I replace `\r\n` in an `std::string`?
Use this : ``` while ( str.find ("\r\n") != string::npos ) { str.erase ( str.find ("\r\n"), 2 ); } ``` more efficient form is : ``` string::size_type pos = 0; // Must initialize while ( ( pos = str.find ("\r\n",pos) ) != string::npos ) { str.erase ( pos, 2 ); } ```
don't reinvent the wheel, Boost String Algorithms is a header only library and I'm reasonably certain that it works everywhere. If you think the accepted answer code is better because its been provided and you don't need to look in docs, here. ``` #include <boost/algorithm/string.hpp> #include <string> #include <iostr...
Replace line breaks in a STL string
[ "", "c++", "stl", "" ]
I have two divs and two separate links that triggers slideDown and slideUp for the divs. When one of the divs are slided down and I click the other one, I hide the first div (slidingUp) and then open the other div (slidingDown) but, at the moment it's like while one div is sliding down, the other, also in the same tim...
``` $('#Div1').slideDown('fast', function(){ $('#Div2').slideUp('fast'); }); ``` Edit: Have you checked out the accordion plugin (if that's what you're trying to do)?
You should chain it like this ``` function animationStep1() { $('#yourDiv1').slideUp('normal', animationStep2); } function animationStep2() { $('#yourDiv2').slideDown('normal', animationStep3); } // etc ``` Of course you can spice this up with recursive functions, arrays holding animation queues, etc., accord...
Finish one animation then start the other one
[ "", "javascript", "jquery", "" ]
I am thinking is that a good idea to define exception with template. Defining different types of exception is a super verbose task. You have to inherit exception, there is nothing changed, just inherit. Like this.. ``` class FooException : public BaseException { public: ... }; class BarException : public BaseExce...
It's definitely possible and works fine, but i would avoid it. It obscures diagnostics. GCC will display the name of the exception type, with the usual template stuff included. I would take the few minutes to define the new exception class, personally. It's not like you would do it all the time.
It's an interesting idea, but apart from the drawbacks already pointed out, it would also not allow you to define an exception hierarchy: suppose that you want to define ``` class InvalidArgumentException {}; class NullPointerException : public InvalidArgumentException {}; ``` then a TemplatedException<NullPointerExc...
Is that a good idea to define exception with template?
[ "", "c++", "exception", "templates", "" ]
I have a C++ library app which talks to a C++ server and I am creating a vector of my custom class objects. But my Cpp/CLI console app(which interacts with native C++ ), throws a memory violation error when I try to return my custom class obj vector. Code Sample - In my native C++ class - ``` std::vector<a> GetStuff...
I'll assume that the native code is in a separately compiled unit, like a .dll. First thing the worry about is the native code using a different allocator (new/delete), you'll get that when it is compiled with /MT or linked to another version of the CRT. Next thing to worry about is STL iterator debugging. You should ...
Take a look at [this support article](http://support.microsoft.com/default.aspx?scid=kb;en-us;172396). I think what's happening is that your vector in CLI tries to access internal vector data from DLL and fails to do so because of different static variables. I guess the only good solution is to pass simple array throug...
Transferring vector of objects between C++ DLL and Cpp/CLI console project
[ "", "c++", "c++-cli", "interop", "" ]
i recently stumbled upon a seemingly weird behavior that Google completely failed to explain. ``` using Microsoft.VisualStudio.TestTools.UnitTesting; class TestClass { public override bool Equals(object obj) { return true; } } [TestMethod] public void TestMethod1() { TestClass t = new TestCla...
Your TestClass violates the contract of [`Object.Equals`](http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx). `Assert.AreEqual` is relying on that contract, quite reasonably. The docs state (in the list of requirements): * x.Equals(a null reference (Nothing in Visual Basic)) returns false.
When testing for nulls, do not use `Assert.AreEqual`. You have to use `Assert.IsNull()` for that.
C# UnitTest - Assert.AreEqual() does not call Equals if the argument is null
[ "", "c#", "visual-studio", "unit-testing", "equals", "" ]
I'm new to python, so please excuse what is probably a pretty dumb question. Basically, I have a single global variable, called \_debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses it. I hav...
There are more problems than just the leading underscore I'm afraid. When you call `my_function()`, it still won't have your `debug` variable in its namespace, unless you import it from `two.py`. Of course, doing that means you'll end up with cyclic dependencies (`one.py -> two.py -> one.py`), and you'll get `NameErr...
Names beginning with an underscore aren't imported with ``` from one import * ```
Confusion about global variables in python
[ "", "python", "global-variables", "python-import", "" ]
I've been learning C#, and I'm trying to understand lambdas. In this sample below, it prints out 10 ten times. ``` class Program { delegate void Action(); static void Main(string[] args) { List<Action> actions = new List<Action>(); for (int i = 0; i < 10; ++i ) actions.Add(()=>...
What the compiler is doing is pulling your lambda and any variables captured by the lambda into a compiler generated nested class. After compilation your example looks a lot like this: ``` class Program { delegate void Action(); static void Main(string[] args) { List<Action> ac...
The only solution I've been able to find is to make a local copy first: ``` for (int i = 0; i < 10; ++i) { int copy = i; actions.Add(() => Console.WriteLine(copy)); } ``` But I'm having trouble understanding why putting a copy inside the for-loop is any different than having the lambda capture `i`.
How to tell a lambda function to capture a copy instead of a reference in C#?
[ "", "c#", "loops", "lambda", "capture", "" ]
I know it is possible to set the current folder of the OpenFolderDialog to a special folder, like "Program Files" or Desktop? But where do I find this?
Look at the System.Environment class, e.g: ``` string programFiles = System.Environment.GetFolderPath( System.Environment.SpecialFolder.ProgramFiles); ``` Update: I'm not sure if this is part of the question, but to open the folder selection dialog, you then use this code: ``` using System.Windows.Forms; //.....
Have you tried setting the folder to `System.Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)`? This should do the trick.
Set OpenFolderDialog to a special folder
[ "", "c#", ".net", "file", "directory", "" ]
In JavaScript, there are two values which basically say 'I don't exist' - `undefined` and `null`. A property to which a programmer has not assigned anything will be `undefined`, but in order for a property to become `null`, `null` must be explicitly assigned to it. I once thought that there was a need for `null` beca...
The question isn't really "why is there a null value in JS" - there is a null value of some sort in most languages and it is generally considered very useful. The question is, "why is there an *undefined* value in JS". Major places where it is used: 1. when you declare `var x;` but don't assign to it, `x` holds undef...
Best described [here](http://saladwithsteve.com/2008/02/javascript-undefined-vs-null.html), but in summary: undefined is the lack of a type and value, and null is the lack of a value. Furthermore, if you're doing simple '==' comparisons, you're right, they come out the same. But try ===, which compares both type and ...
Why is there a `null` value in JavaScript?
[ "", "javascript", "null", "language-features", "undefined", "" ]
i have an input element, and i want bind both change and keypress event with the input, but event handling code is same for both the events. is there any short way of doing this instead of writing the same code twice. well, i could write a method, but wanted to see if there is any easier way of doing this ``` $("#inpt...
You can use the jQuery on method. ``` $("#inpt").on( "change keypress", function () { code }); ```
You can save the function and bind it to both: ``` var fn = function(){ /*some code*/ }; $("#inpt").change(fn).keypress(fn); ```
attaching same event handling code to multiple events in jquery
[ "", "javascript", "jquery", "" ]
Specifically (taking a deep breath): How would you go about finding all the XML name spaces within a C#/.NET `XmlDocument` for which there are no applicable schemas in the instance's `XmlSchemaSet` (`Schemas` property)? My XPath magic is lacking the sophistication to do something like this, but I will keep looking in ...
You need to get a list of all the distinct namespaces in the document, and then compare that with the distinct namespaces in the schema set. But namespace declaration names are typically not exposed in the XPath document model. But given a node you can get its namespace: ``` // Match every element and attribute in th...
The easiest way I've ever found to retrieve all of the namespaces from a given XmlDocument is to XPath through all the nodes finding unique Prefix and NamespaceURI values. I've got a helper routine that I use to return these unique values in an XmlNamespaceManager to make life simpler when I'm dealing with complex Xml...
How can one find unknown XML namespaces in a document?
[ "", "c#", ".net", "xsd", "schema", "xml-namespaces", "" ]
Is there a general way to implement part of an application with JavaScript and supplying a persistent connection to a server? I need the server to be able to push data to the client, regardless of the client being behind a firewall. Thanks in advance
See [Comet](http://en.wikipedia.org/wiki/Comet_%28programming%29) - it's like ajax, but it holds a connection open so the server can push information to the client. Note that compliant browsers will only hold 2 connections (note: [most modern browsers no longer comply](https://stackoverflow.com/questions/5751515/offic...
You should look into Comet: <http://ajaxian.com/archives/comet-a-new-approach-to-ajax-applications>
Persistent connection with client
[ "", "javascript", "connection", "persistence", "" ]
In attempting to use scipy's quad method to integrate a gaussian (lets say there's a gaussian method named gauss), I was having problems passing needed parameters to gauss and leaving quad to do the integration over the correct variable. Does anyone have a good example of how to use quad w/ a multidimensional function?...
Okay, you appear to be pretty confused about several things. Let's start at the beginning: you mentioned a "multidimensional function", but then go on to discuss the usual one-variable Gaussian curve. This is *not* a multidimensional function: when you integrate it, you only integrate one variable (x). The distinction ...
scipy ships with the "error function", aka Gaussian integral: ``` import scipy.special help(scipy.special.erf) ```
Best way to write a Python function that integrates a gaussian?
[ "", "python", "scipy", "gaussian", "integral", "" ]
I have two tables with the same columns ``` tbl_source (ID, Title) tbl_dest (ID, Title) ``` I want to update tbl\_dest titles from the tbl\_source where the ids in dest and source match. However, I don't want to update the dest title if the source title is null (or blank). I've got this: ``` UPDATE tbl_dest SET...
Use an inner join... ``` Update tbl_dest Set tbl_dest.Title = tbl_source.Title From tbl_dest inner join tbl_source on tbl_dest.ID = tbl_source.ID Where tbl_source.Title is not null and tbl_source.Title <> '' ```
It's setting the value to null because the subquery is returning null, and you're not filtering records in your update clause. Try something like this instead: ``` UPDATE tbl_dest SET tbl_dest.Title = (SELECT title FROM tbl_source WHERE tbl_source.id = tbl_dest.id) WHERE EXISTS (SELECT 1 FROM tbl...
Updating a DB table excluding NULLs
[ "", "sql", "sql-server-2005", "sql-update", "" ]
I'm currently developing a web application in ASP.Net with SQL Server and I would like to have some sort of public API so that my users can get their data and manipulate it at their own will. I've never done something like this, can you recomend some guidelines for me to follow?
You are going to want to look into web services. [Here is a good article that shows you how to create RESTful WCF services.](http://www.developer.com/net/article.php/3695436) Uising RESTful services will allow your users to invoke API methods in your service with nice clean URLs.
WCF is the way to go- you can use SOAP / REST services - since you are planning a public API using REST is the right way to go - the following links from MSDN (starter kit and lab) will get you started <http://msdn.microsoft.com/en-us/netframework/cc950529.aspx> <http://code.msdn.microsoft.com/wcfrestlabs>
How to design a public API in ASP.Net?
[ "", "c#", "asp.net", "api", "" ]
Using standard mysql functions is there a way to write a query that will return a list of days between two dates. eg given 2009-01-01 and 2009-01-13 it would return a one column table with the values: ``` 2009-01-01 2009-01-02 2009-01-03 2009-01-04 2009-01-05 2009-01-06 2009-01-07 2009-01-08 2009-01-09 ...
I would use this stored procedure to generate the intervals you need into the temp table named **time\_intervals**, then JOIN and aggregate your data table with the temp **time\_intervals** table. The procedure can generate intervals of all the different types you see specified in it: ``` call make_intervals('2009-01...
For MSSQL you can use this. It is VERY quick. You can wrap this up in a table valued function or stored proc and parse in the start and end dates as variables. ``` DECLARE @startDate DATETIME DECLARE @endDate DATETIME SET @startDate = '2011-01-01' SET @endDate = '2011-01-31'; WITH dates(Date) AS ( SELECT @star...
Get a list of dates between two dates
[ "", "mysql", "sql", "date", "gaps-and-islands", "" ]
I have a SQL query that is supposed to pull out a record and concat each to a string, then output that string. The important part of the query is below. ``` DECLARE @counter int; SET @counter = 1; DECLARE @tempID varchar(50); SET @tempID = ''; DECLARE @tempCat varchar(255); SET @tempCat = ''; DECLARE @tempCatString...
Looks like it should work but for somereason it seems to think @tempCatString is null which is why you are always getting a null value as nullconcatenated to anything else is still null. Suggest you try with `COALESCE()` on each of the variables to set them to " " if they are null.
this would be more efficient.... ``` select @tempCatString = @tempCatString + Coalesce(Description,'') + '<br/>' from Categories... select @fn ``` also look at concat\_null\_yields\_null as an option to fix your concatenation issue, although I would avoid that route
T-SQL While Loop and concatenation
[ "", "sql", "sql-server", "while-loop", "string-concatenation", "" ]
Is there a Windows standard way to do things such as "start fan", "decrease speed" or the like, from C/C++? I have a suspicion it might be ACPI, but I am a frail mortal and cannot read that kind of documentation. Edit: e.g. Windows 7 lets you select in your power plan options such as "passive cooling" (only when thin...
I am at the moment working on a project that, among other things, controls the computer fans. Basically, the fans are controlled by the superIO chip of your computer. We access the chip directly using port-mapped IO, and from there we can get to the logical fan device. Using port-mapped IO requires the code to run in k...
If you want something real quick to just lower fans to a level where you know things won't overheat, there's the speedfan program to do so. Figuring out how to configure it in the early versions to automatically lower fans to 50% on computer startup was so painful that my first approach was to simply byte-patch it to s...
Programmatically access CPU fan on a laptop? (Windows)
[ "", "c++", "windows", "acpi", "" ]
I'm trying to implement some basic linear algebra operations and one of these operations is the inversion of a triangular (upper and/or lower) matrix. Is there an easy and stable algorithm to do that? Thank you.
Yes, use [back substitution](http://en.wikipedia.org/wiki/Triangular_matrix#Forward_and_back_substitution). A standard algorithm to invert a matrix is to find its LU decomposition (decomposition into a lower-triangular and an upper-triangular matrix), use back subsitution on the triangular pieces, and then combine the ...
Don't invert it if you can. It's one of the basic commandments of numerical linear algebra. It is much faster and numerically stabler to keep the matrix L itself in memory and compute ``` inv(L)b ``` with back-substitution whenever you need to do something else with inv(L). Note that the customary algorithm for inv...
Is there around a straightforward way to invert a triangular (upper or lower) matrix?
[ "", "c++", "math", "matrix", "linear-algebra", "triangular", "" ]
I'm working on a WCF service that will be communicating over net.tcp to n instances of a client app (that is being developed by another programmer in my office). At the moment I am using net.tcp without any security as I felt setting this up at this stage wasn't necessary, at least not until we are closer to rolling o...
While your overall design should consider security from the very beginning, I don't think it's a good idea to couple your components to any particular security strategy. You may very well want to use some of your components in a non-secure manner or across a different protocol which offers different security options. ...
Security should be thought about from the start, and not added on at the end. Develop a plan for your security, and implement it as you go, rather then at the end. Reference: Microsoft .NET: Architecting Applications for the Enterprise <http://www.amazon.com/Microsoft>®-NET-Architecting-Applications-PRO-Developer/dp...
Logic first, WCF security later?
[ "", "c#", "xml", "wcf", "security", "wcf-binding", "" ]
When I'm inside a destructor is it possible that some other thread will start executing object's member function? How to deal with this situation?
C++ has no intrinsic protection against using an object after it's been deleting - forget about race conditions - another thread could use your object after it's been completely deleted. Either: 1. Make sure only one place in the code owns the object, and it's responsible for deleting when no-one is using th...
You shouldn't be destroying an object unless you are sure that nothing else will be trying to use it - ideally nothing else has a reference to it. You will need to look more closely at when you call delete.
Destructor vs member function race
[ "", "c++", "multithreading", "destructor", "" ]
For instance in C# or Java, you always have a main() method used to get your program running. What do you name the class that it is in? Some ideas I would use would just be "Program" or the name of the program itself. What would be considered conventional in this case?
Visual Studio creates "Program.cs" these days, which seems pretty reasonable. Another self-documenting name I rather like is "EntryPoint".
I use either Main or Main
In an OO language, what do you name your class that contains the Main method?
[ "", "c#", "oop", "naming-conventions", "" ]
Does anyone have any experience that indicates what kind of performance hit a developer could expect by choosing to use an ORM (in Django, RoR, SQLAlechemy, etc) over SQL and hand-designed databases? I imagine there are complicating issues, including whether specifying a database within the constraints of an ORM increa...
My advice is not to worry about this until you need to - don't optimise prematurely. An ORM can provide many benefits to development speed, code readability and can remove a lot of code repetition. I would recommend using one if it will make your application easier to develop. As you progress through the development u...
Performance has always been an after thought in most DAL Layer development / architecture. I think its about time we start questioning the performance of these ORM tools, for the so-called ease of development they promise: The 2 biggest areas of performance issues in ORMs are: 1. Inability to write Optimum SQL. You h...
ORM performance cost
[ "", "sql", "database", "performance", "orm", "frameworks", "" ]
Is there any material about how to use `#include` correctly? I didn't find any C/C++ text book that explains this usage in detail. In formal project, I always get confused in dealing with it.
* Check Large-Scale C++ Software Design from John Lakos if you have the money. * Google C++ coding guidelines also have some OK stuff. * Check Sutter Herb materials online (blog) as well. Basically you need to understand where include headers are NOT required, eg. forward declaration. Also try to make sure that includ...
The big one that always tripped me up was this: This searches in the header path: ``` #include <stdio.h> ``` This searches in your local directory: ``` #include "myfile.h" ``` Second thing you should do with EVERY header is this: myfilename.h: ``` #ifndef MYFILENAME_H #define MYFILENAME_H //put code here #endif ...
How to use #include directive correctly?
[ "", "c++", "c", "" ]
I need to make multiple divs move from right to left across the screen and stop when it gets to the edge. I have been playing with jQuery lately, and it seem like what I want can be done using that. Does anyone have or know where I can find an example of this?
You will want to check out the jQuery animate() feature. The standard way of doing this is positioning an element absolutely and then animating the "left" or "right" CSS property. An equally popular way is to increase/decrease the left or right margin. Now, having said this, you need to be aware of severe performance ...
In jQuery 1.2 and newer you no longer have to position the element absolutely; you can use normal relative positioning and use += or -= to add to or subtract from properties, e.g. ``` $("#startAnimation").click(function(){ $(".toBeAnimated").animate({ marginLeft: "+=250px", }, 1000 ); }); ``` And to ...
How can I use jQuery to move a div across the screen
[ "", "javascript", "jquery", "" ]
Does anyone know why std::queue, std::stack, and std::priority\_queue don't provide a `clear()` member function? I have to fake one like this: ``` std::queue<int> q; // time passes... q = std::queue<int>(); // equivalent to clear() ``` IIRC, `clear()` is provided by everything that could serve as the underlying cont...
Well, I think this is because `clear` was not considered a valid operation on a queue, a priority\_queue or a stack (by the way, deque is not and adaptor but a container). > The only reason to use the container > adaptor queue instead of the container > deque is to make it clear that you are > performing only queue op...
Deque has clear(). See, e.g., <http://www.cplusplus.com/reference/stl/deque/clear.html>. However, queue does not. But why would you choose queue over deque, anyway? > The only reason to use the container > adaptor queue instead of the container > deque is to make it clear that you are > performing only queue operatio...
Why don't the standard C++ container adaptors provide a clear function?
[ "", "c++", "stl", "standards", "" ]
I'm trying to compile a simple program, with ``` #include <gtkmm.h> ``` The path to `gtkmm.h` is `/usr/include/gtkmm-2.4/gtkmm.h`. g++ doesn't see this file unless I specifically tell it `-I /usr/include/gtkmm-2.4`. My question is, how can I have g++ automatically look recursively through all the directories in `/us...
In this case, the correct thing to do is to use `pkg-config` in your `Makefile` or buildscripts: ``` # Makefile ifeq ($(shell pkg-config --modversion gtkmm-2.4),) $(error Package gtkmm-2.4 needed to compile) endif CXXFLAGS += `pkg-config --cflags gtkmm-2.4` LDLIBS += `pkg-config --libs gtkmm-2.4` BINS = program pr...
I guess you are not using a makefile? The only thing that could be annoying is having to type the long -I option *each time* you compile your program. A makefile makes it a lot easier. For example, you could modify the *hello world* makefile from [wikipedia](http://en.wikipedia.org/wiki/Make_(software)) to something l...
g++ include all /usr/include recursively
[ "", "c++", "g++", "" ]
I need to check a double value for infinity in a C++ app on Linux. On most platforms this works by comparing with `std::numeric_limits<double>::infinity()`. However, on some old platforms (RedHat 9 for example, with gcc 3.2.2) this is not available, and `std::numeric_limits<double>::has_infinity` is false there. What ...
Ok, I have now resorted to using the `INFINITY` and `NAN` macros on that particular machine - seems to work fine. They come from `math.h`.
If you're using IEEE 754 arithmetic, as you almost certainly are, infinities are well defined values and have defined outcomes for all arithmetic operations. In particular, ``` infinity - infinity = NaN ``` Positive and negative infinity and `NaN` values are the only values for which this is true. NaNs are special "n...
What's the recommended workaround if numeric_limits<double>::has_infinity is false?
[ "", "c++", "linux", "double", "limit", "infinity", "" ]
I am using sqlite with python. When i insert into table A i need to feed it an ID from table B. So what i wanted to do is insert default data into B, grab the id (which is auto increment) and use it in table A. Whats the best way receive the key from the table i just inserted into?
As Christian said, `sqlite3_last_insert_rowid()` is what you want... but that's the C level API, and you're using the Python DB-API bindings for SQLite. It looks like the cursor method `lastrowid` will do what you want [(search for 'lastrowid' in the documentation for more information)](http://docs.python.org/library/...
Check out [sqlite3\_last\_insert\_rowid()](http://www.sqlite.org/c3ref/last_insert_rowid.html) -- it's probably what you're looking for: > Each entry in an SQLite table has a > unique 64-bit signed integer key > called the "rowid". The rowid is > always available as an undeclared > column named ROWID, OID, or \_ROWID\...
creating blank field and receving the INTEGER PRIMARY KEY with sqlite, python
[ "", "python", "sqlite", "" ]
I'm working on a program that will tell what level a programmer is at beginner, intermediate, or expert based on 32 subjects from a test in Code Complete 2nd Edition. I'm using 32 check boxes and one method to tell which ones are clicked. The problem is that when I check to see if the check boxes checked property is eq...
I'm not sure what checkBoxVariant is exacty but... I think the problem is that checkBoxVariant is just 1 of the 32 CheckBoxes. I'm assuming you wired all 32 CheckChanged events to the checkBoxVariant\_CheckedChanged method. What it should look like is: ``` // If checkbox is checked then increment base score, // othe...
if ((baseScore >= 0) || (baseScore <= 14)) Be careful - this will always evaluate to true. You may have intended to use &&.
Programming Skill Tester (Problem)
[ "", "c#", "winforms", "" ]
I am trying to develop an Online editor (like FCKEditor/etc) but I have no idea how they work. I know that the WYSIWYG ones have Javascript and IFrames, but how do they actually work? I'm especially curious about having a real-time preview of what's being typed into the editor.
RTE are usually (always?) implemented using an iframe. The document object which is available inside that iframe must have the property [designMode set to on](https://developer.mozilla.org/en/Rich-Text_Editing_in_Mozilla). After this point all you have to do in order to implement basic functionality like bold, italic, ...
[FCKEditor](http://www.fckeditor.net/download) is open source and the source code is freely available. The code for [the editor](https://blog.stackoverflow.com/2009/01/updated-wmd-editor/) used on Stackoverflow [is also available](http://github.com/derobins/wmd/tree/master) It might be worth spending some time readin...
How do online text editors work?
[ "", "javascript", "editor", "wysiwyg", "fckeditor", "" ]
Oh, 2 things: 1) It is a console application. 2 ) I know it is in danish, but it doesn't really matter, its just an example of asking for some input. The text and variables does not matter. Alright, consider this simple input: It could be any sort of input question really. ``` Console.WriteLine("Hvad er dit kundenumm...
Use [Int16.TryParse](http://msdn.microsoft.com/en-us/library/system.int16.tryparse.aspx) and the equivalents for other numeric types. All of these return a Boolean result to indicate success or failure for parsing, and take an `out` parameter which is set to the result of the parsing (or 0 in case of failure). In your ...
You can use the TryParse pattern: ``` string s; // for "is not valid" message short val; // final value while(!short.TryParse(s=Console.ReadLine(), out val)) { Console.WriteLine(s + " is not valid..."); } ```
Best way to verify readline input in C#?
[ "", "c#", "readline", "verify", "" ]
I am working on a DAL that is getting a DataReader Asynchronously. I would like to write a single method for transforming the DataReader into a DataSet. It needs to handle different schema so that this one method will handle all of my fetch needs. P.S. I am populating the SQLDataReader Asynchronously, please don't gi...
Try [DataSet.Load()](http://msdn.microsoft.com/en-us/library/5fd1ahe2.aspx). It has several overloads taking an IDataReader.
[DataTable.load()](http://msdn.microsoft.com/en-us/library/system.data.datatable.load.aspx) can be used for a generic approach. ``` do { var table = new DataTable(); table.Load(reader); dataset.Tables.Add(table); } while(!reader.IsClosed); ```
Best method for Populating DataSet from a SQLDataReader
[ "", "sql", "dataset", "sqldatareader", "" ]
So, the question is: I get some notifications I don't want to get. But I don't know for what file/dir I got them. Is there a way to know why given notification was fired? If you think about ReadDirectoryChangesW, please include a meaningful code sample.
If you would like Windows to tell you what specific file or subdirectory changed, you will need to use [ReadDirectoryChangesW](http://msdn.microsoft.com/en-us/library/aa365465(VS.85).aspx). The asynchronous mode is fairly simple if you use a completion routine. On the other hand, you will probably get better performan...
~pseudocode ``` HANDLE handles[MAX_HANDLES]; std::string dir_array[MAX_HANDLES]; for i from 0 to MAX_HANDLES: h[i] = FindFirstChangeNotification(dir_array[i]...); nCount = MAX_HANDLES; ret = WaitForMultipleObjects(handles, nCount ...); // check if ret returns something between WAIT_OBJECT_0 and WAIT_OBJECT_0+nCo...
How to debug file change notifications obtained by FindFirstChangeNotification?
[ "", "c++", "debugging", "winapi", "notifications", "" ]
as explained before, I'm currently working on a small linear algebra library to use in a personal project. Matrices are implemented as C++ vectors and element assignment ( a(i,j) = v; ) is delegated to the assignment to the vector's elements. For my project I'll need to solve tons of square equation systems and, in ord...
``` template<class T> class matrix { public: class accessor { public: accessor(T& dest, matrix& parent) : dest(dest), parent(parent) { } operator T const& () const { return dest; } accessor& operator=(T const& t) { dest = t; parent.invalidate_cache(); return *this; } private: ...
If I understand correctly you need to check during the execution of your code whether a matrix has changed or not. Well, vectors don't support such functionality. However, what you can do is write a Matrix class of your own, add such functionality to it and use it instead of vectors. An example implementation could b...
Caching policies and techniques for matrices
[ "", "c++", "caching", "" ]
In Visual C++ , when I build a dll , the output files are .dll and .lib. Is the name of the dll built into the .lib file . The reasson I ask this question is : When I built my exe by importing this dll and run the exe , the exe tries to locate the dll to load it in the process address space . As we just specify the ...
The LIB file is turned into an import table in the EXE. This *does* contain the name of the DLL. You can see this if you run `dumpbin /all MyDLL.lib`. Note that `dumpbin MyDll.lib` by itself doesn't show anything useful: you should use `/all`. This shows all of the sections defined in the .LIB file. You can ignore an...
Yes, the lib contains the name of the DLL. Functionally, the import library implements the `LoadLibrary` and `GetProcAdress` calls, and makes the exported functions available as if they were linked statically. The search path is the same as documented for [LoadLibrary](http://msdn.microsoft.com/en-us/library/ms684175...
When building a DLL file, does the generated LIB file contain the DLL name?
[ "", "c++", "winapi", "linker", "" ]
I'd like to be able to use php search an array (or better yet, a column of a mysql table) for a particular string. However, my goal is for it to return the string it finds and the number of matching characters (in the right order) or some other way to see how reasonable the search results are, so then I can make use of...
More searching led me to the Levenshtein distance and then to similar\_text, which proved to be the best way to do this. ``` similar_text("input string", "match against this", $pct_accuracy); ``` compares the strings and then saves the accuracy as a variable. The Levenshtein distance determines how many delete, inser...
You should check out [full text searching](http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html) in MySQL. Also check out Zend's port of the Apache Lucene project, [Zend\_Search\_Lucene](http://framework.zend.com/manual/en/zend.search.lucene.html).
PHP/mysql array search algorithm
[ "", "php", "mysql", "match", "" ]
I am looking at building a client server application in C# using winforms or WPF. The client application must be a local application because it has to interact with specialised hardware. The architecture I'm looking for is the client connects to a server port using TCP/IP. The client will then make requests to the ser...
WCF supports [duplex messaging](https://web.archive.org/web/20120417170915/http://geekswithblogs.net:80/claeyskurt/archive/2007/09/05/115169.aspx) which should accomplish what you need. See also: [http://msdn.microsoft.com/en-us/library/cc645027(VS.95).aspx](https://learn.microsoft.com/en-us/previous-versions/windows/...
Try reading [this article by Juval Lowy](http://msdn.microsoft.com/en-gb/magazine/cc163537.aspx) which is an excellent discussion of the issues in WCF messaging. He offers an alternative to duplexing which is his pub-sub framework. I'm going to have to recommend you buy his WCF book as well. He is one of the best techn...
Two way client server network communication
[ "", "c#", "wcf", "networking", "" ]
What is the linq equivalent of the following statement ? ``` IF NOT EXISTS(SELECT UserName FROM Users WHERE UserName='michael') BEGIN INSERT INTO Users (UserName) values ('michael'); END ``` also can you suggest any sql-to-linq converters? I am currently using LINQPad which does a great job in terms of writing linq c...
It can't be done in LINQ2SQL with a single statement as the LINQ syntax and extension methods don't support inserts. The following (assuming a datacontext named `db`) should do the trick. ``` if (!db.Users.Any( u => u.UserName == "michael" )) { db.Users.InsertOnSubmit( new User { UserName = "michael" } ); ...
Extension method that implements tvanfosson's solution: ``` /// <summary> /// Method that provides the T-SQL EXISTS call for any IQueryable (thus extending Linq). /// </summary> /// <remarks>Returns whether or not the predicate conditions exists at least one time.</remarks> public static bool Exists<TSource>...
if exists statement in sql to linq
[ "", "sql", "sql-server", "linq", "" ]
I am working with a set of what is essentially Attribute/Value pairs (there's actually quite a bit more to this, but I'm simplifying for the sake of this question). Effectively you can think of the tables as such: Entities (EntityID,AttributeName,AttributeValue) PK=EntityID,AttributeName Targets (TargetID,Attrib...
Okay, I think after several tries and edits, this solution finally works: ``` SELECT e1.EntityID, t1.TargetID FROM Entities e1 JOIN Entities e2 ON (e1.EntityID = e2.EntityID) CROSS JOIN Targets t1 LEFT OUTER JOIN Targets t2 ON (t1.TargetID = t2.TargetID AND e2.AttributeName = t2.AttributeName AND e2.Attr...
I like these kind of questions but I think it is not unreasonable to hope that the OP provides at least create scripts for the table(s) and maybe even some sample data. I like to hear who agrees and who disagrees.
Querying based on a set of Named Attributes/Values
[ "", "sql", "database", "oracle", "sql-match-all", "" ]
How do I iterate between 0 and 1 by a step of 0.1? This says that the step argument cannot be zero: ``` for i in range(0, 1, 0.1): print(i) ```
Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result. Use the [`linspace`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html) function from the [NumPy](http:/...
[`range()`](https://docs.python.org/3/library/functions.html#func-range) can only do integers, not floating point. Use a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) instead to obtain a list of steps: ``` [x * 0.1 for x in range(0, 10)] ``` More generally, a [gener...
How do I use a decimal step value for range()?
[ "", "python", "floating-point", "range", "" ]
I tried to execute the `DESCRIBE` command via a database link, but this was the return message: ``` DESCRIBE <table>@<database>; ERROR: ------------------------------------ ERROR: object <table> does not exist 1 rows selected ``` A `SELECT` on this table works well. **Does Oracle pe...
You could do something with the [all\_tab\_columns](http://download.oracle.com/docs/cd/B28359_01/server.111/b28320/statviews_2091.htm) table to get some table information. ``` select column_name, data_type from all_tab_columns where table_name = 'TABLE_NAME'; ```
I think DESCRIBE is a SQL\*Plus feature. See [here](http://www.ss64.com/ora/desc.html).
DESCRIBE via database link?
[ "", "sql", "oracle", "" ]
I'm creating a class named `TetraQueue` that inherits `System.Collections.Generic.Queue` class overriding the `Dequeue` method, here is the code: ``` public class TetraQueue : Queue<Tetrablock> { public override Tetrablock Dequeue() { return base.Dequeue(); } } ``` But when I try to compile this I ge...
Unfortunately the `Dequeue` method is not virtual so you can't override it.
Two ways to know whether or not a method is virtual: * Type in "override" in Visual Studio - it will offer you all the methods you're allowed to override. * [View the documentation](http://msdn.microsoft.com/en-us/library/1c8bzx97.aspx) - Dequeue doesn't say it's virtual, so you can't override it. EDIT: Others have s...
How do I override an generic method?(C#)
[ "", "c#", ".net", "collections", "" ]
I am writing a Wordpress plugin. I want to perform a redirect (after creating DB records from POST data, etc...) to other ADMIN page. Neither header("Location: ...) nor wp\_redirect() work - i get Warning: Cannot modify header information - headers already sent by which comes from obvious reason. How do I properly...
On your form action, add 'noheader=true' to the action URL. This will prevent the headers for the admin area from being outputted before your redirect. For example: ``` <form name="post" action="<?php echo admin_url('admin.php?page=your-admin-page&noheader=true'); ?>" method="post" id="post"> ```
If you still want to redirect from your plugin admin page to another admin page while using WP add\_page\* functions then, after processing your request, you can just echo something like this: ``` <script type="text/javascript"> window.location = '/whatever_page.php'; </script> ``` This just renders a javascript base...
How to redirect to different admin page in Wordpress?
[ "", "php", "redirect", "wordpress", "" ]
Well, I guess this day had to come. My client's website has been compromised and blacklisted by Google. When you load the main page this javascript gets automatically added to the bottom of the document: ``` <script type="text/javascript">var str='google-analytics.com';var str2='6b756c6b61726e696f6f37312e636f6d';str4...
A rogue HTTP Module (in IIS), or whatever the equivalent is for apache could prepend, append, or perhaps even modify content for any HTTP request, even for static files. This would suggest that the server itself has been compromised. EDIT: If you let us know what type of web server you're using, we'll be able to make ...
Are you serving any content from a SQL database? It's possible that the compromise was a SQL injection attack and your site content in the database has been replaced/amended with this script/tag.
client's website was attacked, eeek!
[ "", "javascript", "security", "" ]
How do I initiate a Windows XP user Log Off from a C# app? The action of my app should produce the same result as clicking "Log Off" in XP start menu -- it's fine if the system asks for a confirmation. Is there a .Net or an unmanaged API for this?
You could P/Invoke ExitWindowsEx: > <http://www.pinvoke.net/default.aspx/user32/ExitWindowsEx.html> Pulling it all together: ``` using System.Runtime.InteropServices; class Class1 { [DllImport("user32.dll")] static extern bool ExitWindowsEx(uint uFlags, uint dwReason); [STAThread] static void Main(s...
Try calling the "ExitWindowsEx" API function with the constant "EWX\_LOGOFF" or 0. API Guide tells me that the second parameter is ignored. For instance, ``` //The import using System.Runtime.InteropServices; // The declaration [DllImport("user32.dll")] public static extern int ExitWindowsEx(int uFlags, int dwReserve...
Log off user from Win XP programmatically in C#
[ "", "c#", ".net", "windows", "logoff", "" ]
How to print the following code to a .txt file ``` y = '10.1.1.' # /24 network, for x in range(255): x += 1 print y + str(x) # not happy that it's in string, but how to print it into a.txt ``` There's copy paste, but would rather try something more interesting.
``` f = open('myfile.txt', 'w') for x in range(255): ip = "10.1.1.%s\n" % str(x) f.write(ip) f.close() ```
scriptname.py >> output.txt
Outputting to a text file
[ "", "python", "text", "" ]
This has always confused me. It seems like this would be nicer: ``` ["Hello", "world"].join("-") ``` Than this: ``` "-".join(["Hello", "world"]) ``` Is there a specific reason it is like this?
It's because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the "joiner" *must be* strings. For example: ``` '_'.join(['welcome', 'to', 'stack', 'overflow']) '_'.join(('welcome', 'to', 'stack', 'overflow')) ``` ``` 'welcome_to_stack_overflow' ``` Using something other than strings wi...
This was discussed in the [String methods... finally](http://mail.python.org/pipermail/python-dev/1999-June/095366.html "String methods... finally") thread in the Python-Dev achive, and was accepted by Guido. This thread began in Jun 1999, and `str.join` was included in Python 1.6 which was released in Sep 2000 (and su...
Why is it string.join(list) instead of list.join(string)?
[ "", "python", "string", "list", "" ]
Often I add an `Empty` method to my C++ objects to clear the internal state using code similar to the following. ``` class Foo { private: int n_; std::string str_; public: Foo() : n_(1234), str_("Hello, world!") { } void Empty() { *this = Foo(); } }; ``` This seems to be bette...
I'd let the constructor call my function instead: ``` class Foo { private: int n_; std::string str_; public: Foo() { Reset(); } void Reset() { n_ = 1234; str_ = "Hello, world!"; } }; ``` Yes, you're unnecessarily initializing the string as an empty string first...
Potential problems? How do you know that \*this really is a Foo?
Emptying a C++ object
[ "", "c++", "construction", "" ]
I can't figure out how I can implement an Icon View in the WPF ListView (a view similar to the Windows Explorer). Searching on google I only found informations about implementing the GridView but no clues about the Icon View. I'm not talking about `System.Windows.Form.ListView` but `System.Windows.Controls.ListView`. ...
Same as Tanveer Badar's answer, but with a WrapPanel instead of a UniformGrid. Set the following in your listbox: ``` ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" ``` to force the WrapPanel to wrap.
**EDIT** Appears i misunderstood what you meant with Explorer view...i have mine set to Details... ;) I'll leave my answer up here in case anyone makes the same mistake as i... --- There is no such thing as an Icon View in WPF, you'll have to implement it yourself, but you dont have to do everything from scratch. Yo...
WPF: ListView with icons view?
[ "", "c#", "wpf", "listview", "" ]
How can I have a WinForms program do some **specific thing** whenever a certain time-based condition is met? I was thinking I could do something with two threads, where one thread runs the normal program, and the other thread merely loops through checking if the time-based condition is true yet or not, and when the co...
I think you should use a [Timer](http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx) set to an inteligent interval to check if your time-based condition is met. It depends what your time-based condition is. Is it a special time or an interval after which you want to do something special? If it's t...
You could add a **System.Windows.Forms.Timer** control to your Form (see the Components category in the toolbox). Then set the timer's interval to some value (e.g. 1000) and add a handler for its Tick event. This handler will then be called once every 1000 milliseconds. In the handler you can then check if the condit...
How can I have a WinForms program do some **specific thing** whenever a certain time-based condition is met?
[ "", "c#", ".net", "" ]
Does anyone have any good resources for refining my skills in developing class diagrams? Would like any strong tutorials in UML 2.0 ideally, but searches seem to be returning poor results. Also currently revising for a final year exam and really want to try and get my teeth into a practice paper with a model answer, I...
* Online UML Guide from StackOverFlow (No more available) * [Practical UML: A Hands-On Introduction for Developers](http://dn.codegear.com/article/31863) * Unified Modeling Language (UML) Tutorial (No more available) * [UML Tutorial and Introduction](http://www.cragsystems.co.uk/ITMUML/)
[Martin Fowler Wrote a book](https://rads.stackoverflow.com/amzn/click/com/0321193687). The latest edition was published for UML2...
UML Class Diagram Resources
[ "", "java", "oop", "resources", "uml", "class-design", "" ]
What kinds of activities will trigger reflow of web page with DOM? It seems there are different points of view. According to <http://www.nczonline.net/blog/2009/02/03/speed-up-your-javascript-part-4/>, it happens * When you add or remove a DOM node. * When you apply a style dynamically (such as element.style.width="1...
Both articles are correct. One can safely assume that whenever you're doing something that could reasonably require the dimensions of elements in the DOM be calculated that you will trigger reflow. In addition, as far as I can tell, both articles say the same thing. The first article says reflow happens when: > When...
Look at the "Rendering triggered by Property Read Access" section of [Understanding Internet Explorer Rendering Behaviour](https://web.archive.org/web/20121120093321/http://blog.dynatrace.com:80/2009/12/12/understanding-internet-explorer-rendering-behaviour/), where the following code in IE will cause rendering activit...
When does reflow happen in a DOM environment?
[ "", "javascript", "performance", "dom", "reflow", "" ]
I'm looking for an algorithm, or at least theory of operation on how you would find similar text in two or more different strings... Much like the question posed here: [Algorithm to find articles with similar text](https://stackoverflow.com/questions/246961/algorithm-to-find-similar-text), the difference being that my...
I can't mark two answers here, so I'm going to answer and mark my own. The Levenshtein distance appears to be the correct method in most cases for this. But, it is worth mentioning [`j_random_hackers`](https://stackoverflow.com/users/47984/jrandomhacker) answer as well. I have used an implementation of LZMA to test his...
Levenshtein distance will not completely work, because you want to allow rearrangements. I think your best bet is going to be to find best rearrangement with levenstein distance as cost for each word. To find the cost of rearrangement, kinda like the [pancake sorting problem](http://mathworld.wolfram.com/PancakeSortin...
Similar String algorithm
[ "", "c++", "c", "algorithm", "string", "" ]
I was looking over [this code](http://www.ibm.com/developerworks/library/j-math1/index.html?ca=dgr-btw03JavaPart1&S_Tact=105AGX59&S_cmp=GRsitebtw03#hypotenuse) to calculate `math.sqrt` in Java. Why did they use hex values in some of the loops and normal values for variables? What benefits are there to use hex?
Because hex corresponds much more closely to bits that decimal numbers. Each hex digit corresponds to 4 bits (a nibble). So, once you've learned the bitmask associated with each hex digit (0-F), you can do something like "I want a mask for the low order byte": ``` 0xff ``` or, "I want a mask for the bottom 31 bits": ...
They probably used hex values because the numbers are easier to remember in hex. For example, 0x7fffffff is the same as 2147483647, but is a lot easier to remember.
Why use hex values instead of normal base 10 numbers?
[ "", "java", "c", "hex", "math.sqrt", "" ]
Let's say I've got a control and I want to prevent it from being edited. Setting the Enabled property of the control to False will work but the control appearance will change accordingly, usually to a difficult to read black over gray font. When readability is still important, this is a real problem. For a TextBox, t...
There is an argument that interfering with standard Windows behaviour is confusing for the user, but that aside I have seen this done before, although more commonly in C++. You can subclass the control and handle paint messages yourself. When the control's enabled just delegate the drawing to the base class. When the c...
Some controls can be set to ReadOnly which leaves them enabled, but unable to be changed. This may be what you're looking for. That said you're probably going to be a world of hurt when your users start coming in confused because it looks like they should be able to edit the controls, but they can't. There's a reason ...
How would you disable .net Winforms Controls without changing their appearance?
[ "", "c#", ".net", "winforms", "" ]
How do you think is really necessary to provide `IFormatProvider` in method `String.Format(string, object)` ? Is it better to write full variant ``` String.Format(CultureInfo.CurrentCulture, "String is {0}", str); ``` or just ``` String.Format("String is {0}", str); ``` ?
In general, you will want to use InvariantCulture if the string you are generating is to be persisted in a way that is independent of the current user's culture (e.g. in the registry, or in a file). You will want to use CurrentCulture for strings that are to be presented in the UI to the current user (forms, reports)....
If you do not specify the `IFormatProvider` (or equivalently pass `null`) most argument types will eventually fall through to being formatted according to `CultureInfo.CurrentCulture`. Where it gets interesting is that you can specify a custom `IFormatProvider` that can get first crack at formatting the arguments, or o...
Is CultureInfo.CurrentCulture really necessary in String.Format()?
[ "", "c#", ".net", "culture", "string.format", "" ]
I have a bunch of scripts - some in perl and some in bash - which are used for: * Creating a database (tables, indexes, constraints, views) * Parsing spreadsheets and loading the data into the database * Getting info about a bunch of files and loading that into the database. These scripts are used in conjunctio...
The trouble is, your Gut reaction might be right, but that doesn't mean your manager is necessarily wrong - he probably has very good reasons for wanting it all done in java. Not least, if you fall under a bus, finding a replacement who knows java, perl and bash is going to be a lot harder than finding someone who know...
It depends. I've found that text processing in Java can take up to 8 or 9 times the amount of code as in Perl. If these scripts need to be tightly integrated into the application then I would agree with your manager but if there just background tasks I'd look into using ActiveState on windows and rewriting the bash scr...
Does it make sense to rewrite Perl and shell scripts in java?
[ "", "java", "perl", "shell", "" ]
On e of my current requirements is to take in an Excel spreadsheet that the user updates about once a week and be able to query that document for certain fields. As of right now, I run through and push all the Excel (2007) data into an xml file (just once when they upload the file, then I just use the xml) that then h...
For something that is done only once per week I don't see the need to perform any optimizations. Instead you should focus on what is maintainable and understandable both for you and whoever will maintain the solution in the future. Use whatever solution you find most natural :-)
As I understand it the performance side of things stands like this for accessing Excel data. Fastest to Slowest 1. Custom 3rd party vendor software using C++ directly on the Excel file type. 2. OleDbConnection method using a schema file if necessary for data types, treats Excel as a flatfile db. 3. Linq 2 XML me...
Speed difference between Linq to XML and Excel with a OledbConnection?
[ "", "c#", "xml", "linq", "excel", "linq-to-xml", "" ]
What's a jQuery like and/or best practices way of getting the original target of an event in jQuery (or in browser javascript in general). I've been using something like this ``` $('body').bind('click', function(e){ //depending on the browser, either srcElement or //originalTarget will be populated w...
You can do it in one line with `var originalElement = e.srcElement || e.originalTarget;` but it ain't pretty JQuery-like ;-) [Edit: But according to <http://docs.jquery.com/Events/jQuery.Event#event.target> `event.target` might do...]
I believe e.target is what you require ``` $('body').bind('click', function(e){ e.target // the original target e.target.id // the id of the original target }); ``` If you go to the [jQuery in Action website](http://www.manning.com/bibeaul...
Best way to get the Original Target
[ "", "javascript", "jquery", "events", "dom", "delegates", "" ]
I want to create a product catalog that allows for intricate details on each of the product types in the catalog. The product types have vastly different data associated with them; some with only generic data, some with a few extra fields of data, some with many fields that are specific to that product type. I need to ...
Use a Sharepoint-style UserData table, that has a set of string columns, a set of int columns, etc. and a Type column. Then you have a list of types table that specifies the schema for each type - its properties, and the specific columns they map to in the UserData table. With things like Azure and other utility comp...
I think you need to go with a data model like -- **Product Table** * ProductId (PK) * ProductName * Details **Property Table** * PropertyId (PK) * ProductId (FK) * ParentPropertyId (FK - Self referenced to categorize properties) * PropertyName * PropertyValue * PropertyValueTypeId **Property Value Lookup Table** ...
Define Generic Data Model for Custom Product Types
[ "", "sql", "sql-server", "database", "database-design", "data-modeling", "" ]
Given an absolute URI/URL, I want to get a URI/URL which doesn't contain the leaf portion. For example: given <http://foo.com/bar/baz.html>, I should get <http://foo.com/bar/>. The code which I could come up with seems a bit lengthy, so I'm wondering if there is a better way. ``` static string GetParentUriString(Uri ...
This is the shortest I can come up with: ``` static string GetParentUriString(Uri uri) { return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length); } ``` If you want to use the Last() method, you will have to include System.Linq.
Did you try this? Seems simple enough. ``` Uri parent = new Uri(uri, ".."); ```
Getting the parent name of a URI/URL from absolute name C#
[ "", "c#", "uri", "" ]
Is it possible to get a list of the user defined functions in JavaScript? I'm currently using this, but it returns functions which aren't user defined: ``` var functionNames = []; for (var f in window) { if (window.hasOwnProperty(f) && typeof window[f] === 'function') { functionNames.push(f); } } ```
I'm assuming you want to filter out native functions. In Firefox, `Function.toString()` returns the function body, which for native functions, will be in the form: ``` function addEventListener() { [native code] } ``` You could match the pattern `/\[native code\]/` in your loop and omit the functions that match...
As Chetan Sastry suggested in his answer, you can check for the existance of `[native code]` inside the stringified function: ``` Object.keys(window).filter(function(x) { if (!(window[x] instanceof Function)) return false; return !/\[native code\]/.test(window[x].toString()) ? true : false; }); ``` Or simply:...
List of global user defined functions in JavaScript?
[ "", "javascript", "function", "" ]
I am trying to read data off of a Windows serial port through Java. I have the javax.comm libraries and am able to get some data but not correct data. When I read the port into a byte array and convert it to text I get a series of characters but no real text string. I have tried to specify the byte array as being both ...
I can't tell from your code, but it looks like you're using `java.io.InputStream` to read the object. You should use either `java.io.BufferedReader` or `java.io.InputSreamReader`. There are many ways to do this, but this is what we use: ``` javax.comm.SerialPort port = ...{initialize your serial port} BufferedReader ...
It's likely that the connected device doesn't use a text protocol. Many devices use a binary message format that may have text embedded in it, but represents other information with more compact codes. Please edit your question and provide more information, such as the device that you're communicating with through the ...
How do I read text from a serial port?
[ "", "java", "string", "serial-port", "arrays", "" ]