Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I want to create a c# application with multiple windows that are all transparent with some text on. The tricky part is making these forms sit on top of the desktop but under the desktop icons. Is this possible?
Just making the window transparent is very straight forward: ``` this.BackColor = Color.Fuchsia; this.TransparencyKey = Color.Fuchsia; ``` You can do something like this to make it so you can still interact with the desktop or anything else under your window: ``` public const int WM_NCHITTEST = 0x84; public const in...
Thanks for the tips Jeff. Its still not quite what I'm after. I would effectively like the window to appear as if it was part of the desktop so icons could sit on top of my form. Maybe there is a different way to do it. Can I actually draw text and graphics directly on to the desktop?
Transparent form on the desktop
[ "", "c#", "winforms", "window", "desktop", "" ]
In order to perform a case-sensitive search/replace on a table in a SQL Server 2000/2005 database, you must use the correct collation. How do you determine whether the default collation for a database is case-sensitive, and if it isn't, how to perform a case-sensitive search/replace?
``` SELECT testColumn FROM testTable WHERE testColumn COLLATE Latin1_General_CS_AS = 'example' SELECT testColumn FROM testTable WHERE testColumn COLLATE Latin1_General_CS_AS = 'EXAMPLE' SELECT testColumn FROM testTable WHERE testColumn COLLATE Latin1_General_CS_AS = 'eXaMpLe' ``` Don't assume the de...
If you have **different cases** of the same word **in the same field**, and only want to **replace specific cases**, then you can use collation in your `REPLACE` function: ``` UPDATE tableName SET fieldName = REPLACE( REPLACE( fieldName COLLATE Latin1_General_CS_AS, 'camelCase' COL...
How do I perform a case-sensitive search and replace in SQL 2000/2005?
[ "", "sql", "sql-server-2005", "sql-server-2000", "collation", "" ]
In cake 1.2 there is a feature that allows the developer to no have to create models, but rather have cake do the detective work at run time and create the model for you. This process happens each time and is neat but in my case very hazardous. I read about this somewhere and now I'm experiencing the bad side of this. ...
**Cake 1.2** It's a hack and it's ugly cus you need to edit core cake files but this is how i do it: \cake\libs\class\_registry.php : line 127ish ``` if (App::import($type, $plugin . $class)) { ${$class} =& new $class($options); } elseif ($type === 'Model') { /* Print out whatever debug info we have then exit...
There's always the possibility to actually create the model file and set var $useTable = false. If this is not what you're asking for and the model and its associations actually do exist, but Cake seems to be unable to find them, you'll have to triple check the names of all models and their class names in both the ac...
Disable Cakephp's Auto Model "feature"
[ "", "php", "cakephp", "model", "cakephp-1.2", "" ]
How would I design and organize tests for the concrete methods of an abstract class? Specifically in .NET.
You have to create a subclass that implements the abstract methods (with empty methods), but none of the concrete ones. This subclass should be for testing only (it should never go into your production code). Just ignore the overridden abstract methods in your unit tests and concentrate on the concrete methods.
Use Rhino Mocks, it can generate implementations of the abstract class at runtime and you can call the non-abstract methods.
Testing Abstract Class Concrete Methods
[ "", "c#", ".net", "unit-testing", "" ]
If I have a `std::vector` or `std::map` variable, and I want to see the contents, it's a big pain to see the nth element while debugging. Is there a plugin, or some trick to making it easier to watch STL container variables while debugging `(VS2003/2005/2008)`?
For vectors, this [thread](http://social.msdn.microsoft.com/forums/en-US/vsdebug/thread/c09f4fe4-4783-4dbb-8d36-85489fa2a4ae) on the msdn forums has a code snippet for setting a watch on a vector index that might help.
If you want to watch more than one element at the same time, you can append a comma and the number of elements as so: `(v._Myfirst)[startIndex], count` However, note that count must be a constant, it cannot be the result of another expression.
Inspecting STL containers in Visual Studio debugging
[ "", "c++", "visual-studio", "debugging", "stl", "" ]
I'm having a problem with an application hanging and giving me the default "Please tell Microsoft about this problem" popup, instead of the "unhandled exception" dialog in the application. In the application code, the Application.ThreadException and AppDomain.CurrentDomain.UnhandledException are both redirected to a m...
Just shooting in the dark here - is it possible that the ArgumentOutOfRangeException is actually thrown from your exception *handler*? Additionally, you didn't say what type of application is in question -- Application.ThreadException only affects WinForms threads, so if this isn't a GUI application it's useless. (See...
Have you checked whether the `ArgumentOutOfRangeException` is thrown from your handler itself? May be worthwhile doing a simple write to the event log or trace at the entry of your exception handler and confirm you're actually hitting it. ***Edit:*** Information to writing to the event log can be found at: <http://su...
Exception getting past Application.ThreadException and AppDomain.CurrentDomain.UnhandledException
[ "", "c#", "exception", "" ]
Do you know any grid control compatible with .NET and Mono? DataGridView seems to be quite buggy on Mono, and GTK# controls depends on GTK+ so you need to install it in windows machines where, usually, it's not present.
You might want to try out the preview of Mono 2.0. DataGridView is vastly better in this version, though there are still several places where it is still lacking. <http://mono.ximian.com/monobuild/preview/download-preview/>
I tried mono 1.9.1 (Mono 2.0 beta) and had some problems with sorting, generated columns, and some nasty exceptions.
Grid controls compatible with .NET and Mono?
[ "", "c#", "datagrid", "controls", "mono", "" ]
Here's my issue: I need to close a process, already running, from a C# program. The problem is that the process now runs as an icon (minimized to taskbar), and unless the user opens it at least once (which will never happen on unattended machines), it'll never have a main window. The other requirement that I have is t...
Here are some answers and clarifications: **rpetrich**: Tried your method before and the problem is, I don't know the window name, it differs from user to user, version to version - just the exe name remains constant. All I have is the process name. And as you can see in the code above the MainWindowHandle of the proc...
This should work: ``` [DllImport("user32.dll", CharSet=CharSet.Auto)] private static extern IntPtr FindWindow(string className, string windowName); [DllImport("user32.dll", CharSet=CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); private const int WM_CLOSE =...
Closing a minimized/iconized process from C#
[ "", "c#", "winapi", "process", "kill", "" ]
I use to run ``` $s =~ s/[^[:print:]]//g; ``` on Perl to get rid of non printable characters. In Python there's no POSIX regex classes, and I can't write [:print:] having it mean what I want. I know of no way in Python to detect if a character is printable or not. What would you do? EDIT: It has to support Unicode...
Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The *unicodedata* module is quite helpful for this, especially the *unicodedata.category()* function. See [Unicode Charact...
As far as I know, the most pythonic/efficient method would be: ``` import string filtered_string = filter(lambda x: x in string.printable, myStr) ```
Stripping non printable characters from a string in python
[ "", "python", "string", "non-printable", "" ]
I've been working on this for a few days now, and I've found several solutions but none of them incredibly simple or lightweight. The problem is basically this: We have a cluster of 10 machines, each of which is running the same software on a multithreaded ESB platform. I can deal with concurrency issues between thread...
you might want to consider using [Hazelcast](http://www.hazelcast.com) distributed locks. Super lite and easy. ``` java.util.concurrent.locks.Lock lock = Hazelcast.getLock ("mymonitor"); lock.lock (); try { // do your stuff }finally { lock.unlock(); } ``` Hazelcast - Distributed Queue, Map, Set, List, Lock
We use Terracotta, so I would like to vote for that. I've been following Hazelcast and it looks like another promising technology, but can't vote for it since I've not used it, and knowing that it uses a P2P based system at its heard, I really would not trust it for large scaling needs. But I have also heard of Zooke...
Distributed Concurrency Control
[ "", "java", "concurrency", "load-balancing", "scaling", "terracotta", "" ]
Is there a portable, not patent-restricted way to play compressed sound files in C# / .Net? I want to play short "jingle" sounds on various events occuring in the program. [System.Media.SoundPlayer](http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx) can handle only WAV, but those are typically to b...
I finally revisited this topic, and, using help from [BrokenGlass on writing WAVE header](https://stackoverflow.com/a/7152153/3205), updated csvorbis. I've added an [OggDecodeStream](https://github.com/mono/csvorbis/blob/master/OggDecoder/OggDecodeStream.cs) that can be passed to `System.Media.SoundPlayer` to simply pl...
> I neither want to distribute any > binaries with my application nor > depend on P/Invoke, as the project > should run at least on Windows and > Linux. I'm fine with bundling .Net > assemblies as long as they are > license-compatible with GPL. Unfortunatly its going to be impossible to avoid distributing binaries, or...
How can I play compressed sound files in C# in a portable way?
[ "", "c#", ".net", "mono", "audio", "oggvorbis", "" ]
It's [shown](http://www.codeproject.com/KB/cs/csharpcasts.aspx) that 'as' casting is much faster than prefix casting, but what about 'is' reflection? How bad is it? As you can imagine, searching for 'is' on Google isn't terribly effective.
There are a few options: 1. The **classic cast**: `Foo foo = (Foo)bar` 2. The **`as` cast operator**: `Foo foo = bar as Foo` 3. The **`is` test**: `bool is = bar is Foo` --- 1. The **classic cast** needs to check if `bar` can be safely cast to `Foo` (quick), and then actually do it (slower), or throw an exception (r...
The way I learned it is that this: ``` if (obj is Foo) { Foo f = (Foo)obj; f.doSomething(); } ``` is slower than this: ``` Foo f = obj as Foo; if (f != null) { f.doSomething(); } ``` Is it slow enough to matter? Probably not, but it's such a simple thing to pay attention for, that you might as well do it.
What are the performance characteristics of 'is' reflection in C#?
[ "", "c#", "reflection", "" ]
I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type? For example: I get back: ``` &#x01ce; ``` which represents an "ǎ" with a tone mark. In binary, this is represented as th...
The standard lib’s very own HTMLParser has an undocumented function unescape() which does exactly what you think it does: up to Python 3.4: ``` import HTMLParser h = HTMLParser.HTMLParser() h.unescape('&copy; 2010') # u'\xa9 2010' h.unescape('&#169; 2010') # u'\xa9 2010' ``` Python 3.4+: ``` import html html.unesca...
Python has the [htmlentitydefs](https://docs.python.org/2/library/htmllib.html#module-htmlentitydefs) module, but this doesn't include a function to unescape HTML entities. Python developer Fredrik Lundh (author of elementtree, among other things) has such a function [on his website](http://effbot.org/zone/re-sub.htm#...
Convert XML/HTML Entities into Unicode String in Python
[ "", "python", "html", "entities", "" ]
I have a legacy C++ module that offers encryption/decryption using the openssl library (DES encryption). I'm trying to translate that code into java, and I don't want to rely on a DLL, JNI, etc... C++ code looks like: ``` des_string_to_key(reinterpret_cast<const char *>(key1), &initkey); des_string_to_key(reinterpret_...
I'm not an OpenSSL expert, but I'd guess the C++ code is using DES in CBC mode thus needing an IV (that's what the initKey probably is, and that's why you think you need two keys). If I'm right, you need to change your Java code to use DES in CBC mode too, then the Java code too will require an encryption key and an IV...
Also, keep in mind that you really shouldn't use sun.misc.\* classes in your code. This could break in other VMs as these are not public APIs. Apache Commons Codecs (among others) have implementations of Base64 that don't bear this problem. I'm not really sure why single DES would ever use multiple keys. Even if you w...
Using openssl encryption with Java
[ "", "java", "encryption", "openssl", "" ]
Working on a project at the moment and we have to implement soft deletion for the majority of users (user roles). We decided to add an `is_deleted='0'` field on each table in the database and set it to `'1'` if particular user roles hit a delete button on a specific record. For future maintenance now, each `SELECT` qu...
You could perform all of your queries against a view that contains the `WHERE IS_DELETED='0'` clause.
I would lean towards a `deleted_at` column that contains the **datetime of when the deletion took place**. Then you get a little bit of free metadata about the deletion. For your `SELECT` just get rows `WHERE deleted_at IS NULL`
What is the best way to implement soft deletion?
[ "", "sql", "database", "database-design", "backup", "" ]
I create a new Button object but did not specify the `command` option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created?
Though [Eli Courtwright's](https://stackoverflow.com/questions/68327/change-command-method-for-tkinter-button-in-python#68455) program will work fine¹, what you really seem to want though is just a way to reconfigure after instantiation any attribute which you could have set when you instantiated². How you do so is by ...
Sure; just use the `bind` method to specify the callback after the button has been created. I've just written and tested the example below. You can find a nice tutorial on doing this at <http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm> ``` from Tkinter import Tk, Button root = Tk() butt...
Change command Method for Tkinter Button in Python
[ "", "python", "user-interface", "tkinter", "" ]
I'm getting a random unreproducible Error when initializing a `JSplitPane` in with JDK 1.5.0\_08. Note that this does not occur every time, but about 80% of the time: ``` Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.KeyStroke at java.util.TreeMap.compare(TreeMap.java:1093) a...
After doing some searching in the [Java Bug Database](https://bugs.java.com/bugdatabase/), this looks like this might be a JDK bug that was only fixed in JDK 6. See [JDK-6434148 : ClassCastException thrown while running SwingSet2 demo](https://bugs.java.com/bugdatabase/view_bug?bug_id=6434148).
Same exception had got thrown when i had upgraded java verion and db visualizer dint support jre7. and since Support for Java 7 was introduced in DbVisualizer 8.0 for Windows and Linux/UNIX. Support for Java 7 on Mac OS X was introduced in DbVisualizer 9.1. So Solution that worked for me : **Windows/Unix/Linux:** In ...
Getting java.lang.ClassCastException: javax.swing.KeyStroke when creating a JSplitPane
[ "", "java", "swing", "java-5", "jsplitpane", "" ]
What's the best way for determining whether the user's browser can view PDF files? Ideally, it shouldn't matter on the browser or the operating system. Is there a specific way of doing it in ASP.NET, or would the answer be just JavaScript?
Neither, none, don't try. Re [dawnerd](https://stackoverflow.com/questions/76179/how-to-determine-if-the-users-browser-can-view-pdf-files#76220): Plug-in detection is not the right answer. I do not have a PDF plugin installed in my browser (Firefox on Ubuntu), yet I am able to view PDF files using the operating system...
A quick google search [found this](http://www.oreillynet.com//cs/user/view/cs_msg/9920). Useful for all kinds of plugins.
How to determine if the user's browser can view PDF files
[ "", "asp.net", "javascript", "pdf", "browser", "" ]
I want to do this: ``` e.className = t; ``` Where t is the name of a style I have defined in a stylesheet.
If `e` is a reference to a DOM element and you have a class like this: `.t {color:green;}` then you want reference the class name as a string: ``` e.className = 't'; ```
Yes, that works (with the class name as a string, as jonah mentioned). Also, you can set style attributes directly on an object, using the [DOM Level 2 Style](http://www.w3.org/TR/DOM-Level-2-Style/) interface. e.g., ``` button.style.fontFamily = "Verdana, Arial, sans-serif"; ``` where `button` is (presumably) a butt...
Can an element's CSS class be set via JavaScript?
[ "", "javascript", "css", "" ]
I have a Cocoa app that uses a WebView to display an HTML interface. How would I go about calling an Objective-C method from a Javascript function within the HTML interface?
This is documented at [developer.apple.com](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DisplayWebContent/Tasks/JavaScriptFromObjC.html).
Being rather green, Apple's documentation is pretty unusable for me, so I made a proof of concept of calling Objective C methods from javascript and vice versa in Cocoa, though the latter was much easier. First make sure you have your webview as the setFrameLoadDelegate: ``` [testWinWebView setFrameLoadDelegate:self]...
How to call an Objective-C method from Javascript in a Cocoa/WebKit app?
[ "", "javascript", "objective-c", "cocoa", "webkit", "" ]
first question here. I'm developing a program in C# (.NET 3.5) that displays files in a listview. I'd like to have the "large icon" view display the icon that Windows Explorer uses for that filetype, otherwise I'll have to use some existing code like this: ``` private int getFileTypeIconIndex(string fileName) ...
You might find the use of [Icon.ExtractAssociatedIcon](http://msdn.microsoft.com/en-us/library/system.drawing.icon.extractassociatedicon.aspx) a much simpler (an managed) approach than using SHGetFileInfo. But watch out: two files with the same extension may have different icons.
The file icons are held in the registry. It's a little convoluted but it works something like * Take the file extension and lookup the registry entry for it, for example .DOC Get the default value for that registry setting, "Word.Document.8" * Now lookup that value in the registry. * Look at the default va...
How can I get the filetype icon that Windows Explorer shows?
[ "", "c#", "winforms", "" ]
I'm writing a C parser using PLY, and recently ran into a problem. This code: ``` typedef int my_type; my_type x; ``` Is correct C code, because my\_type is defined as a type previously to being used as such. I handle it by filling a type symbol table in the parser that gets used by the lexer to differentiate between...
With [some help](http://groups.google.com/group/ply-hack/tree/browse_frm/thread/cf31e8334801eabd/b9cdf4a6682635c1?rnum=1&_done=%2Fgroup%2Fply-hack%2Fbrowse_frm%2Fthread%2Fcf31e8334801eabd%3F#doc_5c415da045e77a6e) from Dave Beazley (PLY's creator), my problem was solved. The idea is to use special sub-rules and do the ...
Not sure why you're doing that level of analysis in your lexer. Lexical analysis should probably be used to separate the input stream into lexical tokens (number, line-change, keyword and so on). It's the parsing phase that should be doing that level of analysis, including table lookups for typedefs and such. That's ...
PLY: Token shifting problem in C parser
[ "", "python", "parsing", "yacc", "ply", "" ]
When I enter an object into the DB with Linq-to-SQL can I get the id that I just inserted without making another db call? I am assuming this is pretty easy, I just don't know how.
After you commit your object into the db the object receives a value in its ID field. So: ``` myObject.Field1 = "value"; // Db is the datacontext db.MyObjects.InsertOnSubmit(myObject); db.SubmitChanges(); // You can retrieve the id from the object int id = myObject.ID; ```
When inserting the generated ID is saved into the instance of the object being saved (see below): ``` protected void btnInsertProductCategory_Click(object sender, EventArgs e) { ProductCategory productCategory = new ProductCategory(); productCategory.Name = “Sample Category”; productCategory.ModifiedDate = DateT...
Can I return the 'id' field after a LINQ insert?
[ "", "c#", ".net", "linq", "linq-to-sql", "" ]
I have a text file on my local machine that is generated by a daily Python script run in cron. I would like to add a bit of code to have that file sent securely to my server over SSH.
You can call the [`scp`](https://en.wikipedia.org/wiki/Secure_copy) bash command (it copies files over [SSH](https://en.wikipedia.org/wiki/Secure_Shell)) with [`subprocess.run`](https://docs.python.org/library/subprocess.html#subprocess.run): ``` import subprocess subprocess.run(["scp", FILE, "USER@SERVER:PATH"]) #e.g...
To do this in Python (i.e. not wrapping scp through subprocess.Popen or similar) with the [Paramiko](https://github.com/paramiko/paramiko) library, you would do something like this: ``` import os import paramiko ssh = paramiko.SSHClient() ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")...
How to copy a file to a remote server in Python using SCP or SSH?
[ "", "python", "ssh", "automation", "scp", "" ]
Here's a problem I've been trying to solve at work. I'm not a database expert, so that perhaps this is a bit sophomoric. All apologies. I have a given database D, which has been duplicated on another machine (in a perhaps dubious manner), resulting in database D'. It is my task to check that database D and D' are in f...
My first reaction is to suggest duplicating to the other machine again in a non-dubious manner. If that is not an option, perhaps some of the tools available from [Red Gate](http://www.red-gate.com/products/index.htm) could do what you need. (I am in no way affliated with Red Gate, just remember Joel mentioning how g...
Here is the solution. The example data is from the ReportServer database that comes with SSRS 2008 R2, but you can use it on any dataset: ``` SELECT s.name, s.type FROM ( SELECT s1.name, s1.type FROM syscolumns s1 WHERE object_name(s1.id) = 'executionlog2' UNION ALL SELECT s2.name, s2.type F...
Implement symmetric difference in SQL Server?
[ "", "sql", "sql-server", "" ]
I just installed Ubuntu 8.04 and Eclipse. I made a very simple Hello World program in order to ensure that everything is running smoothly. When I attempted to use the Scanner class for acquiring some user input I got a very odd error. My code: ``` import java.util.Scanner; class Test { public static void main (...
The Scanner class is new in Java 5. I do not know what Hardy's default Java environment is, but it is not Sun's and therefore may be outdated. I recommend installing the package sun-java6-jdk to get the most up-to-date version, then telling Eclipse to use it.
It could also be that although you are have JDK 1.5 or higher, the project has some specific settings set that tell it to compile as 1.4. You can test this via Project >> Properties >> Java Compiler and ensure the "Compiler Compliance Level" is set to 1.5 or higher.
Scanner cannot be resolved to a type
[ "", "java", "eclipse", "ubuntu", "" ]
I want to port data from one server's database to another server's database. The databases are both on a different mssql 2005 server. Replication is probably not an option since the destination database is generated from scratch on a [time interval] basis. Preferebly I would do something like ``` insert * from db1/ta...
I think what you want to do is create a linked server as per [this webarchive snapshot of msdn article from 2015](http://web.archive.org/web/20150628090613/https://msdn.microsoft.com/en-us/library/aa213778(SQL.80).aspx) or [this article from learn.microsoft.com](https://learn.microsoft.com/en-us/sql/relational-database...
You can use Open Data Source Like this : ``` EXEC sp_configure 'show advanced options', 1 GO RECONFIGURE GO EXEC sp_configure 'Ad Hoc Distributed Queries', 1 GO RECONFIGURE GO SELECT * FROM OPENDATASOURCE('SQLOLEDB', 'Data Source=<Ip Of Your Server>; User ID=<SQL User Name...
Cross-server SQL
[ "", "sql", "sql-server", "t-sql", "linked-server", "cross-server", "" ]
Okay, I've seen but haven't programmed in C# before. You can assume I'm competent in C++, and advanced in C (for what good that'll do me). I understand inheritance, polymorphism, etc so OO concepts aren't going to be a huge problem. Let's say I've been given a task to prototype a quick and dirty program that won't be ...
It sounds like for this app, you could use [Microsoft Dynamic Data](http://www.asp.net/dynamicdata/) or [Castle Active Record](http://www.castleproject.org/activerecord/index.html), and have the application working a few minutes after you finished the database. These tools connect to a database and generate forms for i...
If you're programming in C#, Visual Studio comes with an added install for SQL Server Express. If you're looking to get something up quick and dirty, it would pretty easy to leverage that database in building your app.
Quick C# prototype program with simple DB
[ "", "c#", "database", "prototype", "" ]
Greetings. I'm looking for a way to parse a number of XML files in a particular directory with ASP.NET (C#). I'd like to be able to return content from particular elements, but before that, need to find those that have a certain value between an element. Example XML file 1: ``` <file> <title>Title 1</title> ...
If you are using .Net 3.5, this is extremely easy with LINQ: ``` //get the files XElement xe1 = XElement.Load(string_file_path_1); XElement xe2 = XElement.Load(string_file_path_2); //Give me all XML that has a filter of 'filter'. var filter_elements1 = from p in xe1.Descendants("filter") select p; var filter_elements...
You might want to create your own iterator class that iterate over those files. Say, make a XMLContentEnumerator : IEnumerable. that would iterate over files in a specific directory and parse its content, and then you would be able to make a normal LINQ filtering query such as: ``` var xc = new XMLContentEnumerator(@...
Parse multiple XML files with ASP.NET (C#) and return those with particular element
[ "", "c#", "asp.net", "xml", "" ]
Does anybody have experience of a decent J2SE (preferably at least Java JDK 1.5-level) Java Virtual Machine for Windows Mobile 6? If you know of any CLDC VMs, I'm also interested because even that would be better than what we [currently have](http://www.nsicom.com/Default.aspx?tabid=138) for the platform.
Yes, I've tried doing things with Java on Windows Mobile. I tried really hard. The best advise I can give you is: Stop right now, and start using .NET Compact Framework. Anyway, the two 'good' JVMs for WM are [IBM-J9](http://www-01.ibm.com/software/wireless/weme/) and NSICom Creme, which still are both terribile to wo...
Honestly I searched a while and there no decent JVM for windows mobile. The best bet I think is this : <http://www2s.biglobe.ne.jp/~dat/java/project/jvm/index_en.html> but it's JDK 1.3 compliant the last time I checked.
Windows Mobile 6 J2SE-scale JVM implementation
[ "", "windows-mobile", "java-me", "java", "" ]
I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year: ``` for (int month = 0...
Based on [marked23's](https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#76437) suggestion: ``` public Date getLastFriday( int month, int year ) { Calendar cal = Calendar.getInstance(); cal.set( year, month + 1, 1 ); cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % ...
Let Calendar.class do its magic for you ;) ``` pCal.set(GregorianCalendar.DAY_OF_WEEK,Calendar.FRIDAY); pCal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1); ```
Get Last Friday of Month in Java
[ "", "java", "date", "calendar", "" ]
As the title says, how can I find the current operating system in python?
I usually use [`sys.platform`](https://docs.python.org/3/library/sys.html#sys.platform) to get the platform. `sys.platform` will distinguish between linux, other unixes, and OS X, while `os.name` is "`posix`" for all of them. For much more detailed information, use the [platform module](https://docs.python.org/3/libra...
If you want user readable data but still detailed, you can use [platform.platform()](http://docs.python.org/library/platform.html#platform.platform) ``` >>> import platform >>> platform.platform() 'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne' ``` `platform` also has some other useful methods: ``` >>> platf...
How can I find the current OS in Python?
[ "", "python", "cross-platform", "platform-specific", "" ]
I'd like to implement a simple class (in Java) that would allow me to register and deregister strings, and on the basis of the current set of strings auto-complete a given string. So, the interface would be: * void add(String) * void remove(String) * String complete(String) What's the best way to do this in terms of ...
you should consider to use a PATRICIA trie for the data structure. Search for 'patricia trie' on google and you'll find a lot of information...
The datastructure you are after is called a Ternary Search Tree. There's a great JavaWorld example at www.javaworld.com/javaworld/jw-02-2001/jw-0216-ternary.html
How to implement a simple auto-complete functionality?
[ "", "java", "autocomplete", "" ]
What experience have you had with introducing a Ribbon style control to legacy MFC applications? I know it exists in the new VC2008 Feature Pack, but changing compilers from VC2005 is a big deal for our source base and integration to our environment, Intel FORTRAN, ClearCase, many 3rd libraries. There are quiet a few...
In my projects I'm using the MFC Feature Pack in Visual Studio 2008, which is based on code from [BCGSoft](http://www.bcgsoft.com). Their BCGControlBar Library Professional Edition includes a ribbon control and is compatible with Visual Studio 2005. I'm not aware of any open source ribbon control libraries for C++, th...
We use [Codejock](http://www.codejock.com/). It's not cheap, but I guess I've come to find that good controls usually are :-). They are fairly responsive in the tech support department (although we haven't had need to use that recently). We are buidling a whole suite of tools using these controls and have always had wh...
Whats the best Ribbon UI control to retro fit to a legacy MFC application build with VC2005?
[ "", "c++", "user-interface", "mfc", "ribbon", "stingray", "" ]
How do you stop the designer from auto generating code that sets the value for public properties on a user control?
Use the DesignerSerializationVisibilityAttribute on the properties that you want to hide from the designer serialization and set the parameter to Hidden. ``` [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string Name { get; set; } ```
Add the following attributes to the property in your control: ``` [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] ```
How do you stop the Designer generating code for public properties on a User Control?
[ "", "c#", "winforms", "" ]
I have a database with names in it such as John Doe etc. Unfortunately some of these names contain quotes like Keiran O'Keefe. Now when I try and search for such names as follows: ``` SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe' ``` I (understandably) get an error. How do I prevent this error from occurring. I am us...
The escape character is ', so you would need to replace the quote with two quotes. For example, `SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe'` becomes `SELECT * FROM PEOPLE WHERE SURNAME='O''Keefe'` That said, it's probably incorrect to do this yourself. Your language may have a function to escape strings for use ...
Oracle 10 solution is ``` SELECT * FROM PEOPLE WHERE SURNAME=q'{O'Keefe}' ```
How do I deal with quotes ' in SQL
[ "", "sql", "oracle", "" ]
So, I have willfully kept myself a Java n00b until recently, and my first real exposure brought about a minor shock: Java does not have C# style properties! Ok, I can live with that. However, I can also swear that I have seen property getter/setter code in Java in one codebase, but I cannot remember where. How was tha...
There is a "standard" pattern for getters and setters in Java, called [Bean properties](http://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html). Basically any method starting with `get`, taking no arguments and returning a value, is a property getter for a property named as the rest of the method name...
I am surprised that no one mentioned [project lombok](http://projectlombok.org/) Yes, currently there are no properties in java. There are some other missing features as well. But luckily we have [project lombok](http://projectlombok.org/) that is trying to improve the situation. It is also getting more and more pop...
(no) Properties in Java?
[ "", "java", "getter-setter", "" ]
First off: I'm using a rather obscure implementation of javascript embedded as a scripting engine for Adobe InDesign CS3. This implementation sometimes diverges from "standard" javascript, hence my problem. I'm using [John Resig's jsdiff library](http://ejohn.org/projects/javascript-diff-algorithm/) ([source here](htt...
You might be "asking the wrong question" (as Raymond Chen would say); rather than trying to avoid using the vanilla objects, try changing the way the associative array members are named. The way I'd try to approach this: instead of there being an array member ns["reflect"], change the way that jsdiff builds the arrays...
If the JS implementation you're using supports the hasOwnProperty method for objects, you can use it to test whether a property has explicitly been set for an object or the property is inherited from its prototype. Example: ``` if(object.hasOwnProperty('testProperty')){ // do something } ```
What is a javascript hash table implementation that avoids object namespace collisions?
[ "", "javascript", "hash", "diff", "adobe-indesign", "" ]
How can I change the width of a textarea form element if I used ModelForm to create it? Here is my product class: ``` class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product ``` And the templa...
**The easiest way for your use case is to use CSS**. It's a language meant for defining presentation. Look at the code generated by form, take note of the ids for fields that interest you, and change appearance of these fields through CSS. Example for `long_desc` field in your ProductForm (when your form does not have...
Excellent answer by zuber, but I believe there's an error in the example code for the third approach. The constructor should be: ``` def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor self.fields['long_desc'].widget.attrs['cols'] = 10 sel...
Change the width of form elements created with ModelForm in Django
[ "", "python", "html", "django", "django-forms", "django-templates", "" ]
I would like to call Perl script files from my c++ program. I am not sure that the people I will distribute to will have Perl installed. Basically I'm looking for a .lib file that I can use that has an Apache like distribution license.
You can embed perl into your app. * [Perl Embedding](http://www.linuxjournal.com/article/2901) by John Quillan * [C++ wrapper around Perl C API](http://xaxxon.slackworks.com/ep/)
I'm [currently](http://news.perlfoundation.org/2008/08/2008q3_grant_proposal_libperl.html) writing a library for embedding Perl in C++, but it's not finished yet. In any case I would recommend against using the EP library. Not only has it not been maintained for years, but is also has some severe architectural deficien...
How can I embed Perl inside a C++ application?
[ "", "c++", "perl", "" ]
I have two webapplication, one is a simple authenticationsite which can authenticate the logged in user and **redirects** him then to another site. Therefore I have to pass ther userId (GUID) to the second application. Currently this is done via the URL but i would like to hide this id. Has anybody an idea how to do ...
Pass the GUID through a **session**, best way. <http://www.w3schools.com/ASP/asp_sessions.asp> OR, since it's 2 different servers, pass the information by POST method: <http://www.w3schools.com/aspnet/aspnet_forms.asp> The other possibility is to store the session state in a database on the local server, and remote...
This sounds like a tricky situation. There are however several options you can use but it all depends on what your application does. Let's call WebApp1 your authenticate site, and WebApp2 your distination site once authenticated. Can WebApp2 not call WebApp1 behind the scenes? (Services) THe problem with passing thi...
Hiding a queryString in an ASP.NET Webapplication
[ "", "c#", "asp.net", "web-services", "" ]
I am new to all the anonymous features and need some help. I have gotten the following to work: ``` public void FakeSaveWithMessage(Transaction t) { t.Message = "I drink goats blood"; } public delegate void FakeSave(Transaction t); public void SampleTestFunction() { Expect.Call(delegate { _dao.Save(t); }).Do...
That's a well known error message. Check the link below for a more detailed discussion. <http://staceyw1.wordpress.com/2007/12/22/they-are-anonymous-methods-not-anonymous-delegates/> Basically you just need to put a cast in front of your anonymous delegate (your lambda expression). In case the link ever goes down, h...
What Mark said. The problem is that Do takes a Delegate parameter. The compiler can't convert the anonymous methods to Delegate, only a "delegate type" i.e. a concrete type derived from Delegate. If that Do function had took Action<>, Action<,> ... etc. overloads, you wouldn't need the cast.
Convert this delegate to an anonymous method or lambda
[ "", "c#", ".net-3.5", "delegates", "lambda", "anonymous-methods", "" ]
I'm attempting to use TinyXML to read and save from memory, instead of only reading and saving files to disk. It seems that the documnent's parse function can load a char \*. But then I need to save the document to a char \* when I'm done with it. Does anyone know about this? Edit: The printing & streaming functions ...
I'm not familiar with TinyXML, but from the documentation it seems that by using operator << to a C++ stream (so you can use [C++ string streams](http://www.cppreference.com/wiki/io/sstream/start)) or a [TiXMLPrinter class](http://www.grinninglizard.com/tinyxmldocs/classTiXmlPrinter.html) you can get an STL string with...
Here's some sample code I am using, adapted from the [TiXMLPrinter](http://www.grinninglizard.com/tinyxmldocs/classTiXmlPrinter.html) documentation: ``` TiXmlDocument doc; // populate document here ... TiXmlPrinter printer; printer.SetIndent( " " ); doc.Accept( &printer ); std::string xmltext = printer.CStr(); ``...
TinyXML: Save document to char * or string
[ "", "c++", "tinyxml", "" ]
Is there a way (without installing any libraries) of validating XML using a custom DTD in PHP?
Take a look at [PHP's DOM](https://www.php.net/dom), especially [DOMDocument::schemaValidate](https://www.php.net/manual/en/domdocument.schemavalidate.php) and [DOMDocument::validate](https://www.php.net/manual/en/domdocument.validate.php). The example for DOMDocument::validate is fairly simple: ``` <?php $dom = new ...
If you have the dtd in a string, you can validate against it by using a [data wrapper](http://php.net/manual/en/wrappers.data.php) for the dtd: ``` $xml = '<?xml version="1.0"?> <!DOCTYPE note SYSTEM "note.dtd"> <note> <to>Tove</to> <from>Jani</from> <heading>Reminde...
Validate XML using a custom DTD in PHP
[ "", "php", "xml", "validation", "dtd", "" ]
I have a table with a "Date" column. Each Date may appear multiple times. How do I select only the dates that appear < k number of times?
``` select dates from table t group by dates having count(dates) < k ; ``` Hopefully, it works for ORACLE. HTH
``` SELECT * FROM [MyTable] WHERE [Date] IN ( SELECT [Date] FROM [MyTable] GROUP By [Date] HAVING COUNT(*) < @Max ) ``` See @[SQLMenace] 's response also. It's very similar to this, but depending on your database his JOIN will probably run faster, assuming the optimizer doesn't make the difference m...
SQL Query Help: Selecting Rows That Appear A Certain Number Of Times
[ "", "sql", "date", "select", "" ]
I have done a bit of research into this and it seems that the only way to sort a data bound combo box is to sort the data source itself (a DataTable in a DataSet in this case). If that is the case then the question becomes what is the best way to sort a DataTable? The combo box bindings are set in the designer initia...
If you're using a DataTable, you can use the (DataTable.DefaultView) [DataView.Sort](http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx) property. For greater flexibility you can use the [BindingSource](http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx) component. Bindi...
You can actually sort the [default view](http://msdn.microsoft.com/en-us/library/system.data.datatable.defaultview.aspx) on a DataTable: ``` myDataTable.DefaultView.Sort = "Field1, Field2 DESC"; ``` That'll sort any rows you retrieve directly from the DataTable.
What is the best way to sort a data bound combo box?
[ "", "c#", "data-binding", "" ]
I wanted to "emulate" a popular flash game, Chrontron, in C++ and needed some help getting started. (NOTE: Not for release, just practicing for myself) ``` Basics: Player has a time machine. On each iteration of using the time machine, a parallel state is created, co-existing with a previous state. One of the states m...
What you should do is first to read and understand the "fixed time-step" game loop (Here's a good explanation: <http://www.gaffer.org/game-physics/fix-your-timestep>). Then what you do is to keep a list of list of pairs of frame counter and action. STL example: ``` std::list<std::list<std::pair<unsigned long, Action>...
This sounds very similar to [Braid](http://braid-game.com). You really don't want parallel processing for this - parallel programming is **hard**, and for something like this, performance should not be an issue. Since the game state vector will grow very quickly (probably on the order of several kilobytes per second, ...
Making a game in C++ using parallel processing
[ "", "c++", "opengl", "graphics", "directx", "sdl", "" ]
Any recommended practices for cleaning up "header spaghetti" which is causing extremely slow compilation times (Linux/Unix)? Is there any equvalent to "#pragma once" with GCC? (found conflicting messages regarding this) Thanks.
Assuming you're familiar with "include guards" (#ifdef at the begining of the header..), an additional way of speeding up build time is by using external include guards. It was discussed in "[Large Scale C++ Software Design](http://vig.pearsoned.com/store/product/1,1207,store-15080_isbn-0201633620,00.html)". The idea i...
If you want to do a complete cleanup and have the time to do it then the best solution is to delete all the #includes in all the files (except for obvious ones e.g. abc.h in abc.cpp) and then compile the project. Add the necessary forward declaration or header to fix the first error and then repeat until you comple cle...
Cleaning up Legacy Code "header spaghetti"
[ "", "c++", "legacy-code", "" ]
Is there a way to read a module's configuration ini file? For example I installed php-eaccelerator (<http://eaccelerator.net>) and it put a `eaccelerator.ini` file in `/etc/php.d`. My PHP installation wont read this `.ini` file because the `--with-config-file-scan-dir` option wasn't used when compiling PHP. Is there a...
This is just a wild guess, but try to add all the directives from eaccelerator.ini to php.ini. First create a `<?php phpinfo(); ?>` and check where it's located. For example, try this: ``` [eAccelerator] extension="eaccelerator.so" eaccelerator.shm_size="32" eaccelerator.cache_dir="/tmp" eaccelerator.enable="1" eacce...
The standard way in this instance is to copy the relevant .ini lines to the bottom of the php.ini file. There is no 'include "file.ini"' functionality in the php.ini file itself. You can't do it at run time either, since the extension has already been initialised by then.
PHP parse configuration ini files
[ "", "php", "apache", "" ]
Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?" So it's easy to get the underlying type from a nullable type, but how do I get the nullable version of a .NET type? So I have ``` typeof(int) typeof(DateTime) System.Type t = something; ``` and I want ``` int? ...
Here is the code I use: ``` Type GetNullableType(Type type) { // Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper if type is already nullable. type = Nullable.GetUnderlyingType(type) ?? type; // avoid type becoming null if (type.IsValueType) return typeof(Nullable<>).MakeGenericTy...
I have a couple of methods I've written in my utility library that I've heavily relied on. The first is a method that converts any Type to its corresponding Nullable<Type> form: ``` /// <summary> /// [ <c>public static Type GetNullableType(Type TypeToConvert)</c> ] /// <para></para> /// Convert any Typ...
How do I convert a System.Type to its nullable version?
[ "", "c#", ".net", "" ]
Is it possible to use .htaccess to process all six digit URLs by sending them to a script, but handle every other invalid URL as an error 404? For example: ``` http://mywebsite.com/132483 ``` would be sent to: ``` http://mywebsite.com/scriptname.php?no=132483 ``` but ``` http://mywebsite.com/132483a or http://myw...
``` <IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^([0-9]{6})$ scriptname.php?no=$1 [L] </IfModule> ``` To preserve the clean URL ``` http://mywebsite.com/132483 ``` while serving scriptname.php use only [L]. Using [R=301] will redirect you to your scriptname.php?no=xxx You may find this useful <http://...
In your htaccess file, put the following ``` RewriteEngine On RewriteRule ^([0-9]{6})$ /scriptname.php?no=$1 [L] ``` The first line turns the mod\_rewrite engine on. The () brackets put the contents into $1 - successive () would populate $2, $3... and so on. The [0-9]{6} says look for a string precisely 6 characters ...
Is it possible to use .htaccess to send six digit number URLs to a script but handle all other invalid URLs as 404s?
[ "", "php", ".htaccess", "redirect", "" ]
I have two threads, one updating an int and one reading it. This is a statistic value where the order of the reads and writes is irrelevant. My question is, do I need to synchronize access to this multi-byte value anyway? Or, put another way, can part of the write be complete and get interrupted, and then the read hap...
At first one might think that reads and writes of the native machine size are atomic but there are a number of issues to deal with including cache coherency between processors/cores. Use atomic operations like Interlocked\* on Windows and the equivalent on Linux. C++0x will have an "atomic" template to wrap these in a ...
Boy, what a question. The answer to which is: > Yes, no, hmmm, well, it depends It all comes down to the architecture of the system. On an IA32 a correctly aligned address will be an atomic operation. Unaligned writes might be atomic, it depends on the caching system in use. If the memory lies within a single L1 cach...
Are C++ Reads and Writes of an int Atomic?
[ "", "c++", "multithreading", "synchronization", "atomic", "" ]
I am working through the book Learning WCF by Michele Bustamante, and trying to do it using Visual Studio C# Express 2008. The instructions say to use WCF project and item templates, which are not included with VS C# Express. There *are* templates for these types included with Visual Studio Web Developer Express, and I...
If you have both Visual Web Developer (VWD) 2008 and Visual C# (VC#) 2008 installed you can copy templates between them. The VWD template files live in (by default): ``` C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress ``` The VC# templates live in: ``` C:\Program Files\Microsoft Visual Studio 9.0...
If you are a student you could get the full Visual Studio 2008 from [DreamSpark](http://dreamspark.com) for free.
How to add WCF templates to Visual Studio Express?
[ "", "c#", "visual-studio", "visual-studio-2008", "wcf", "visual-studio-express", "" ]
I maintain an old PC-only application written in Delphi 7. Although Delphi has served me very well in the past I now only use it for this one application and find my skills with the language diminishing. Its syntax is too different from my 'day job' languages of Java/Ruby so it takes me longer to get into the groove of...
I am not aware of any automated tools for making that conversion. Personally I would suggest you stick with Delphi, maybe just upgrade to a new version. I have seen a couple code DOM's that attempt to convert from Delphi to C#, but that doesn't address the library issue. CodeGear (formally Borland) has a tool for [goi...
There has been a scientific report of a successfull transformation of a 1.5 million line Delphi Project to C# by John Brant. He wrote a Delphi parser, a C# generator and lots of transformation rules on the AST. Gradually extending the set of rules, doing a daily build, lots of unit tests, and some rewriting of difficul...
What tools exist to convert a Delphi 7 application to C# and the .Net framework?
[ "", "c#", "delphi", "migration", "" ]
Is there an easy way to convert a string from csv format into a string[] or list? I can guarantee that there are no commas in the data.
``` string[] splitString = origString.Split(','); ``` *(Following comment not added by original answerer)* **Please keep in mind that this answer addresses the SPECIFIC case where there are guaranteed to be NO commas in the data.**
String.Split is just not going to cut it, but a Regex.Split may - Try this one: ``` using System.Text.RegularExpressions; string[] line; line = Regex.Split( input, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))"); ``` Where 'input' is the csv line. This will handle quoted delimiters, and should give you back an array of st...
asp.net Convert CSV string to string[]
[ "", "c#", "string", "csv", "" ]
What is the reason browsers do not correctly recognize: ``` <script src="foobar.js" /> <!-- self-closing script element --> ``` Only this is recognized: ``` <script src="foobar.js"></script> ``` Does this break the concept of XHTML support? Note: This statement is correct at least for all IE (6-8 beta 2).
The non-normative appendix ‘HTML Compatibility Guidelines’ of the XHTML 1 specification says: [С.3. Element Minimization and Empty Element Content](http://www.w3.org/TR/xhtml1/#C_3) > Given an empty instance of an element whose content model is not `EMPTY` (for example, an empty title or paragraph) do not use the min...
To add to what Brad and squadette have said, the self-closing XML syntax `<script />` actually **is** correct XML, but for it to work in practice, your web server also needs to send your documents as properly formed XML with an XML mimetype like `application/xhtml+xml` in the HTTP Content-Type header (and *not* as `tex...
Why don't self-closing script elements work?
[ "", "javascript", "html", "internet-explorer", "xhtml", "" ]
When I am working in .NET 2.0 projects with the newest version of ReSharper (4.1) I am getting warnings about using the var keyword and lambadas etc.. Any idea how I can disable this only for .NET 2.0 projects?
Indeed, you can use C# 3.0 compiler features when targeting .NET 2.0, except extension methods and default LINQ implementations, which are located in newer assemblies. But if you need to co-operate with VS2005 users, you can open Properties view for a given project (not Project Properties, but Edit \ Properties Window,...
You can actually use var in 2.0 projects. It's syntactical sugar and the compiler works with it. Check out this for more info. <http://weblogs.asp.net/shahar/archive/2008/01/23/use-c-3-features-from-c-2-and-net-2-0-code.aspx>
ReSharper giving C# 3.0 Code Inspection Warnings to .NET 2.0 Projects
[ "", "c#", ".net", "visual-studio", "asp.net-2.0", "resharper", "" ]
In Python specifically, how do variables get shared between threads? Although I have used `threading.Thread` before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage t...
In Python, everything is shared, except for function-local variables (because each function call gets its own set of locals, and threads are always separate function calls.) And even then, only the variables themselves (the names that refer to objects) are local to the function; objects themselves are always global, an...
Consider the following code: ``` #/usr/bin/env python from time import sleep from random import random from threading import Thread, local data = local() def bar(): print("I'm called from", data.v) def foo(): bar() class T(Thread): def run(self): sleep(random()) data.v = self.getName()...
What is "thread local storage" in Python, and why do I need it?
[ "", "python", "multithreading", "thread-local", "" ]
I'm trying to automate a gdb session using the `--command` flag. I'm trying to set a breakpoint on a function in a shared library (the Unix equivalent of a DLL) . My cmds.gdb looks like this: ``` set args /home/shlomi/conf/bugs/kde/font-break.txt b IA__FcFontMatch r ``` However, I'm getting the following: ``` shlomi...
Replying to myself, I'd like to give the answer that someone gave me on IRC: ``` (gdb) apropos pending actions -- Specify the actions to be taken at a tracepoint set breakpoint -- Breakpoint specific settings set breakpoint pending -- Set debugger's behavior regarding pending breakpoints show breakpoint -- Breakpoint ...
OT: In terminal it would look like this to debug Caja in one line: ``` gdb -ex "set breakpoint pending on" -ex "break gdk_x_error" -ex run --args caja --sync ```
How to set breakpoints on future shared libraries with a command flag
[ "", "c++", "c", "linux", "unix", "gdb", "" ]
Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: `__myPrivateMethod()`. How, then, can one explain this ``` >>>> class MyClass: ... def myPublicMethod(self): ... print 'public method' ... def __myPrivateMet...
The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside. For example: ``` >>> class Foo(object): ... def __init__(self): ... self.__baz = 42 ... def foo(self)...
When I first came from Java to Python I **hated** this. It scared me to death. Today it might just be the one thing **I love most** about Python. I love being on a platform, where people trust each other and don't feel like they need to build impenetrable walls around their code. In strongly encapsulated languages, i...
Why are Python's 'private' methods not actually private?
[ "", "python", "encapsulation", "information-hiding", "" ]
I am looking for a better solution than what we currently have to deal with **unexpected production errors**, without reinventing the wheel. A larger number of our products are WinForm and WPF applications that are installed at remote sites. Inevitably unexpected errors occur, from NullReferenceExceptions to 'General ...
I'd suggest Jeff Atwood's article on [User Friendly Exception Handling](http://www.codeproject.com/KB/exception/ExceptionHandling.aspx), which does most of what you ask already (Application Info, Screenshot, Exception Details, OS, Logging to text files and Emailing), and contains the source code so you add the extra st...
You can attach to the unhandled exception event and log it/hit a webservice/etc. ``` [STAThread] static void Main() { Application.ThreadException += new ThreadExceptionEventHandler(OnUnhandledException); Application.Run(new FormStartUp()); } static void OnUnhandledException(object sender, ThreadExceptionEvent...
What is the best way to collect/report unexpected errors in .NET Window Applications?
[ "", "c#", ".net", "error-handling", "reporting", "" ]
Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build\_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.
Here is the [Requests](http://docs.python-requests.org/en/latest/) way: ``` import requests r = requests.get('http://github.com', allow_redirects=False) print(r.status_code, r.headers['Location']) ```
[Dive Into Python](https://linux.die.net/diveintopython/html/http_web_services/redirects.html) has a good chapter on handling redirects with urllib2. Another solution is [httplib](https://docs.python.org/2/library/httplib.html). ``` >>> import httplib >>> conn = httplib.HTTPConnection("www.bogosoft.com") >>> conn.requ...
Is there an easy way to request a URL in python and NOT follow redirects?
[ "", "python", "http", "redirect", "" ]
I've got C# code that accesses MySQL through ODBC. It creates a transaction, does a few thousand insert commands, and then commits. Now my question is how many "round trips", so to speak, happen against the DB server? I mean, does it simply transmit every insert command to the DB server, or does it cache/buffer them a...
MySQL has an extended SQL style that can be used, where mass inserts are put in several at a time: ``` INSERT INTO `table` (`id`, `event`) VALUES (1, 94263), (2, 75015), (3, 75015); ``` I will usually collect a few hundred insert-parts into a string before running the SQL query itself. This will reduce the overhead ...
There is no limit on the number of rows per se; The limit is on the number of bytes transferred to the server. You could build the bulk insert up to the number of bytes specified in 'max allowed packet'. If I wanted to use the least amount of inserts I would try that.
MySQL transaction with thousands of Inserts - how many "round trips" does it take?
[ "", "sql", "mysql", "database", "" ]
I have C# winforms application that needs to start an external exe from time to time, but I do not wish to start another process if one is already running, but rather switch to it. So how in C# would I so this in the example below? ``` using System.Diagnostics; ... Process foo = new Process(); foo.StartInfo.FileNa...
This should do it for ya. [Check Processes](http://www.dreamincode.net/code/snippet1541.htm) ``` //Namespaces we need to use using System.Diagnostics; public bool IsProcessOpen(string name) { //here we're going to get a list of all running processes on //the computer foreach (Process clsProcess in Proces...
You can use LINQ as well, ``` var processExists = Process.GetProcesses().Any(p => p.ProcessName.Contains("<your process name>")); ```
How do I find out if a process is already running using c#?
[ "", "c#", "winforms", "external-process", "" ]
I'm considering Altova MapForce (or something similar) to produce either XSLT and/or a Java or C# class to do the translation. Today, we pull data right out of the database and manually build an XML string that we post to a webservice. Should it be db -> (internal)XML -> XSLT -> (External)XML? What do you folks do out...
I would use one of the out-of-the-box XML serialization classes to do your internal XML generation, and then use XSLT to transform to the external XML. You might generate a schema as well to enforce that the translation code (whatever will drive your XSLT translation) continues to get the XML it is expecting for transl...
ya, I think you're heading down the right path with MapForce. If you don't want to write code to preform the actual transformation, MapForce can do that for you also. THis may be better long term b/c it's less code to maintain. Steer clear of more expensive options (e.g. BizTalk) unless you really need to B2B integrat...
Mapping internal data elements to external vendors' XML schema
[ "", "c#", "xml", "xslt", "mapping", "coldfusion", "" ]
We just started running in to an odd problem with a FileSystemWatcher where the call to Dispose() appears to be hanging. This is code that has been working without any problems for a while but we just upgraded to .NET3.5 SP1 so I'm trying to find out if anyone else has seen this behavior. Here is the code that creates ...
Just a thought... Any chance there's a deadlock issue here? You're calling TreeView.Invoke, which is a blocking call. If a filesystem change happens just as you're clicking whatever button causes the FileSystemWatcher.Dispose() call, your FileWatcherFileChanged method will get called on a background thread and call Tr...
Scott, we've occasionally seen issues with control.Invoke in .NET 2. Try switching to control.BeginInvoke and see if that helps. Doing that will allow the FileSystemWatcher thread to return immediately. I suspect your issue is somehow that the control.Invoke is blocking, thus causing the FileSystemWatcher to freeze up...
FileSystemWatcher Dispose call hangs
[ "", "c#", ".net", "winforms", "filesystemwatcher", "" ]
A coworker has been struggling with this problem. The desired result is an installable plugin for Notes that will add a button emails with attachments that will let users save the attachment to a document management system. Finding documentation on doing this for Notes has been an uphill battle to say the least. Wri...
Both Lotus Notes 8+ and Lotus Symphony use the IBM Lotus Expeditor Toolkit. If you get the Lotus Symphony SDK [here](http://symphony.lotus.com/software/lotus/symphony/developers.nsf/home). Their are one or two examples dealing with adding button's to the symphony toolbar. They should translate almost identically to ...
I had to do this once in Notes for a plugin I was developing. What I ended up doing was editing the Notes template in the designer, and then writing some LotusScript behind it that called a .NET class via a DLL. So when you clicked the button, it triggered the event in the LotusScript, and then called the DLL, and pass...
How do you add a button to the email message window toolbar in Lotus Notes 8.5+?
[ "", "java", "eclipse", "lotus-notes", "" ]
Given the following JSON Date representation: ``` "\/Date(1221644506800-0700)\/" ``` How do you deserialize this into it's JavaScript Date-type form? I've tried using MS AJAX JavaScrioptSerializer as shown below: ``` Sys.Serialization.JavaScriptSerializer.deserialize("\/Date(1221644506800-0700)\/") ``` However, al...
Provided you know the string is definitely a date I prefer to do this : ``` new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10)) ```
Bertrand LeRoy, who worked on ASP.NET Atlas/AJAX, [described the design of the JavaScriptSerializer DateTime output](http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx) and revealed the origin of the mysterious leading and trailing forward slashes. He made this recommendation: > run a simple search f...
Deserializing Client-Side AJAX JSON Dates
[ "", "c#", "asp.net", "json", "ajax", "date", "" ]
I have the following code: ``` string prefix = "OLD:"; Func<string, string> prependAction = (x => prefix + x); prefix = "NEW:"; Console.WriteLine(prependAction("brownie")); ``` Because the compiler replaces the prefix variable with a closure "NEW:brownie" is printed to the console. Is there an easy way to prevent th...
I see the underlying problem now. It is deeper than I first thought. Basically the solution is to modify the expression tree before serializing it, by replacing all subtrees that do not depend on the parameters with constant nodes. This is apparently called "funcletization". There is an explanation of it [here](http://...
Just make another closure... Say, something like: ``` var prepend = "OLD:"; Func<string, Func<string, string>> makePrepender = x => y => (x + y); Func<string, string> oldPrepend = makePrepender(prepend); prepend = "NEW:"; Console.WriteLine(oldPrepend("Brownie")); ``` Havn't tested it yet as I don't have access to...
Prevent .NET from "lifting" local variables
[ "", "c#", ".net", "lambda", "" ]
I want to recreate the stickiness and snapping of windows, like it is implemented in Winamp. The basic premise is, when you drag a window and it comes close to another one, it will snap to it and will stick. When you move it the two will move together. I need it for a MDI application.
You could read this article and try to adopt it for your program: [Sticky Windows - How to make your (top-level) forms to stick one to the other or to the screen](http://www.codeproject.com/KB/cs/stickywindows.aspx) The class presented in the article inherits from *System.Windows.Forms.NativeWindow*, thus no inherita...
I have created a [magnet forms component](https://github.com/edoreshef/magnet-winforms) that also supports joint move of "glued" forms. I hope it helps. Disclaimer: I don't know how well will it works with MDI projects.
Anyone familiar with a good "sticky windows" library for Winforms?
[ "", "c#", ".net", "winforms", "user-interface", "" ]
I need to write a function that receives a property as a parameter and execute its getter. If I needed to pass a function/delegate I would have used: ``` delegate RET FunctionDelegate<T, RET>(T t); void func<T, RET>(FunctionDelegate function, T param, ...) { ... return function.Invoke(param); } ``` Is there...
You can use reflection, you can get a MethodInfo object for the get/set accessors and call it's Invoke method. The code example assumes you have both a get and set accessors and you really have to add error handling if you want to use this in production code: For example to get the value of property Foo of object obj...
You can also write something like: ``` static void Method<T, U>(this T obj, Expression<Func<T, U>> property) { var memberExpression = property.Body as MemberExpression; //getter U code = (U)obj.GetType().GetProperty(memberExpression.Member.Name).GetValue(obj, null); ...
How to pass a generic property as a parameter to a function?
[ "", "c#", "generics", "" ]
Earlier today a question was asked regarding [input validation strategies in web apps](https://stackoverflow.com/questions/110458/what-percentage-of-my-time-will-be-spent-in-user-input-verfication-during-web-d). The top answer, at time of writing, suggests in `PHP` just using `htmlspecialchars` and `mysql_real_escape_...
When it comes to database queries, always try and use prepared parameterised queries. The `mysqli` and `PDO` libraries support this. This is infinitely safer than using escaping functions such as `mysql_real_escape_string`. Yes, `mysql_real_escape_string` is effectively just a string escaping function. It is not a mag...
In addition to Cheekysoft's excellent answer: * Yes, they will keep you safe, but only if they're used absolutely correctly. Use them incorrectly and you will still be vulnerable, and may have other problems (for example data corruption) * Please use parameterised queries instead (as stated above). You can use them th...
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
[ "", "php", "security", "xss", "sql-injection", "" ]
Spring DA helps in writing DAOs. When using iBATIS as the persistence framework, and extending SqlMapClientDaoSupport, a SqlMapClient mock should be set for the DAO, but I can't do it. SqlMapClientTemplate is not an interface and EasyMock cannot creates a mock for it.
DAO and unit tests do not get along well ! That does not make sense to mock anything in a component that does not hold any business logic and is focused on database access. You should try instead to write an integration test. Take a look at the spring reference documentation, chapter 8.3 : <http://static.springframewor...
This exact reason is why I don't extend from `SqlMapClientDaoSupport`. Instead, I inject a dependency to the `SqlMapClientTemplate` (typed as the interface `SqlMapClientOperations`). Here's a Spring 2.5 example: ``` @Component public class MyDaoImpl implements MyDao { @Autowired public SqlMapClientOperations ...
How to unit test a DAO that is extending SqlMapClientDaoSupport
[ "", "java", "spring", "ibatis", "easymock", "" ]
List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers. Say, I have a 2D list: ``` li = [[0,1,2],[3,4,5],[6,7,8]] ``` I would like to merge this either into one long list ``` li2 = [0,1,2,3,4,5,6,7,8] ``` or into a string with separators: ``` s ...
Like so: ``` [ item for innerlist in outerlist for item in innerlist ] ``` Turning that directly into a string with separators: ``` ','.join(str(item) for innerlist in outerlist for item in innerlist) ``` Yes, the order of 'for innerlist in outerlist' and 'for item in innerlist' is correct. Even though the "body" o...
Try that: ``` li=[[0,1,2],[3,4,5],[6,7,8]] li2 = [ y for x in li for y in x] ``` You can read it like this: Give me the list of every ys. The ys come from the xs. The xs come from li. To map that in a string: ``` ','.join(map(str,li2)) ```
How do I merge a 2D array in Python into one string with List Comprehension?
[ "", "python", "list-comprehension", "" ]
``` class Tag(models.Model): name = models.CharField(maxlength=100) class Blog(models.Model): name = models.CharField(maxlength=100) tags = models.ManyToManyField(Tag) ``` Simple models just to ask my question. I wonder how can i query blogs using tags in two different ways. * Blog entries that are tagged wi...
You could use Q objects for #1: ``` # Blogs who have either hockey or django tags. from django.db.models import Q Blog.objects.filter( Q(tags__name__iexact='hockey') | Q(tags__name__iexact='django') ) ``` Unions and intersections, I believe, are a bit outside the scope of the Django ORM, but its possible to to th...
I've tested these out with Django 1.0: The "or" queries: ``` Blog.objects.filter(tags__name__in=['tag1', 'tag2']).distinct() ``` or you could use the Q class: ``` Blog.objects.filter(Q(tags__name='tag1') | Q(tags__name='tag2')).distinct() ``` The "and" query: ``` Blog.objects.filter(tags__name='tag1').filter(tags...
Union and Intersect in Django
[ "", "python", "django", "django-models", "django-views", "tagging", "" ]
I want the search box on my web page to display the word "Search" in gray italics. When the box receives focus, it should look just like an empty text box. If there is already text in it, it should display the text normally (black, non-italics). This will help me avoid clutter by removing the label. BTW, this is an on...
Another option, if you're happy to have this feature only for newer browsers, is to use the support offered by HTML 5's **placeholder** attribute: ``` <input name="email" placeholder="Email Address"> ``` In the absence of any styles, in Chrome this looks like: [![enter image description here](https://i.stack.imgur.c...
That is known as a textbox watermark, and it is done via JavaScript. * <http://naspinski.net/post/Text-Input-Watermarks-using-Javascript-(IE-Compatible).aspx> or if you use jQuery, a much better approach: * <http://digitalbush.com/projects/watermark-input-plugin/> * or [code.google.com/p/jquery-watermark](http://cod...
How do I make an HTML text box show a hint when empty?
[ "", "javascript", "html", "" ]
I want to add a *column* to an existing legacy *database* and write a *procedure* by which I can assign each record a different value. Something like adding a *column* and autogenerate the data for it. Like, if I add a new *column* called "ID" (number) I want to then initialize a unique value to each of the records. S...
This will depend on the database but for SQL Server, this could be achieved as follows: ``` alter table Example add NewColumn int identity(1,1) ```
It would help if you posted what SQL database you're using. For MySQL you probably want auto\_increment: ``` ALTER TABLE tableName ADD id MEDIUMINT NOT NULL AUTO_INCREMENT KEY ``` Not sure if this applies the values retroactively though. If it doesn't you should just be able to iterate over your values with a stored ...
Add a column to existing table and uniquely number them on MS SQL Server
[ "", "sql", "sql-server", "" ]
I understand the main function of the lock key word from MSDN > lock Statement (C# Reference) > > The lock keyword marks a statement > block as a critical section by > obtaining the mutual-exclusion lock > for a given object, executing a > statement, and then releasing the > lock. When should the lock be used? For i...
> When should the lock be used? A lock should be used to protect shared resources in multithreaded code. Not for anything else. > But is it necessary when the application does not spin off any other threads? Absolutely not. It's just a time waster. However do be sure that you're not implicitly using system threads. ...
All the answers here seem right: locks' usefulness is to block threads from acessing locked code concurrently. However, there are many subtleties in this field, one of which is that locked blocks of code are automatically marked as **critical regions** by the Common Language Runtime. The effect of code being marked as...
lock keyword in C#
[ "", "c#", "multithreading", "design-patterns", "locking", "" ]
I have Java and Flash client applications. What is the best way for the two to communicate without special Flash-specific servers such as BlazeDS or Red5? I am looking for a light client-only solution.
Well, you can make http requests from flash to any url... so if your java server has a point where it can listen to incoming requests and process XML or JSON, your flash client can just make the request to that url. BlazeDS and Red5 just aim to make it simpler by handling the translation for you making it possible to c...
Are they running in a browser (applet and SWF), or are they standalone apps? If they're running in a browser then you can use javascript. Both Flash and Java are can access javascript. It's fragile, but it works. If they're running as actual applications then you can have Java open a socket connection on some port. T...
Communicating between Java and Flash without a Flash-specific server
[ "", "java", "flash", "" ]
I have an action like this: ``` public class News : System.Web.Mvc.Controller { public ActionResult Archive(int year) { / *** / } } ``` With a route like this: ``` routes.MapRoute( "News-Archive", "News.mvc/Archive/{year}", ...
You have a couple problems, I think. First, your route doesn't have a default value for "year", so the URL "/News.mvc/Archive" is actually not valid for routing purposes. Second, you're expect form values to show up as route parameters, but that's not how HTML works. If you use a plain form with a select and a submit...
I think I've worked out why - the route includes {year} so the generated routes always will too.. If anyone can confirm this?
ASP.NET MVC Preview 4 - Stop Url.RouteUrl() etc. using existing parameters
[ "", "c#", "asp.net-mvc", "forms", "routes", "" ]
The first language I learnt was PHP, but I have more recently picked up Python. As these are all 'high-level' languages, I have found them a bit difficult to pick up. I also tried to learn Objective-C but I gave up. So, what language should I learn to bridge between Python to C
It's not clear why you need a bridge language. Why don't you start working with C directly? C is a very simple language itself. I think that hardest part for C learner is pointers and everything else related to memory management. Also C lang is oriented on structured programming, so you will need to learn how to implem...
The best place to start learning C is the book "The C Programming Language" by Kernighan and Ritchie. You will recognise a lot of things from PHP, and you will be surprised how much PHP (and Perl, Python etc) do for you. Oh and you also will need a C compiler, but i guess you knew that.
What language should I learn as a bridge to C (and derivatives)
[ "", "python", "c", "" ]
Is there any **simple algorithm** to determine the likeliness of 2 names representing the same person? I'm not asking for something of the level that Custom department might be using. Just a simple algorithm that would tell me if 'James T. Clark' is most likely the same name as 'J. Thomas Clark' or 'James Clerk'. If ...
I've faced similar problem and tried to use Levenstein distance first, but it did not work well for me. I came up with an algorithm that gives you "similarity" value between two strings (higher value means more similar strings, "1" for identical strings). This value is not very meaningful by itself (if not "1", always ...
Sounds like you're looking for a phonetic-based algorithms, such as [soundex](http://en.wikipedia.org/wiki/Soundex), [NYSIIS](http://en.wikipedia.org/wiki/New_York_State_Identification_and_Intelligence_System), or [double metaphone](http://en.wikipedia.org/wiki/Double_Metaphone). The first actually *is* what several go...
Comparing names
[ "", "c#", "string", "comparison", "" ]
In what order are the following parameters tested (in C++)? ``` if (a || b && c) { } ``` I've just seen this code in our application and I hate it, I want to add some brackets to just clarify the ordering. But I don't want to add the brackets until I know I'm adding them in the right place. ***Edit: Accepted Answer ...
From [here](http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm): ``` a || (b && c) ``` This is the default precedence.
[<http://www.cppreference.com/wiki/operator_precedence]> (Found by googling "C++ operator precedence") That page tells us that &&, in group 13, has higher precedence than || in group 14, so the expression is equivalent to a || (b && c). Unfortunately, the wikipedia article [<http://en.wikipedia.org/wiki/Operators_in_...
C++ Binary operators order of precedence
[ "", "c++", "binary-operators", "" ]
We're living in a golden age of databases, with numerous high quality commercial and free databases. This is great, but the downside is there's not a simple obvious choice for someone who needs a database for his next project. * What are the constraints/criteria you use for selecting a database? * How well do the vari...
I would think first on what the system requirements are for data access, data security, scalability, performance, disconnected scenarios, data transformation, data sizing. On the other side, consider also the experience and background of developers, operators, platform administrators. You should also think on what co...
My selection criteria (mainly programming centric): * Maintenance: How are updates/hotfixes installed? * Transaction control: How it is implemented * Are Stored Procedures supported? * Can you use exception handling in Stored Procedures? * Costs * As a benefit: Can you use recursion on Stored Procedures? (E.g. in SQL ...
How to select an SQL database?
[ "", "sql", "database", "" ]
Since our switch from Visual Studio 6 to Visual Studio 2008, we've been using the MFC90.dll and msvc[pr]90.dlls along with the manifest files in a private side-by-side configuration so as to not worry about versions or installing them to the system. Pre-SP1, this was working fine (and still works fine on our developer...
I have battled this problem myself last week and consider myself somewhat of an expert now ;) I'm 99% sure that not all dlls and static libraries were recompiled with the SP1 version. You need to put ``` #define _BIND_TO_CURRENT_MFC_VERSION 1 #define _BIND_TO_CURRENT_CRT_VERSION 1 ``` into *every* project you're usi...
To understand the problem, I think it is important to realize that there are **four version numbers involved**: * (A) The version of the VC header files to which the .exe is compiled. * (B) The version of the manifest file that is embedded in the resources section of that .exe. By default, this manifest file is automa...
App does not run with VS 2008 SP1 DLLs, previous version works with RTM versions
[ "", "c++", "visual-studio-2008", "mfc", "" ]
There's something very unsatisfactory about this code: ``` /* Given a command string in which the first 8 characters are the command name padded on the right with whitespace, construct the appropriate kind of Command object. */ public class CommandFactory { public Command getCommand(String cmd) { cmdNam...
Your map of strings to commands I think is good. You could even factor out the string command name to the constructor (i.e. shouldn't StartCommand know that its command is "START"?) If you could do this, instantiation of your command objects is much simpler: ``` Class c = commandMap.get(cmdName); if (c != null) re...
How about the following code: ``` public enum CommandFactory { START { @Override Command create(String cmd) { return new StartCommand(cmd); } }, END { @Override Command create(String cmd) { return new EndCommand(cmd); } }; abs...
Refactoring Java factory method
[ "", "java", "factory", "" ]
I wrote a simple web service in C# using SharpDevelop (which I just got and I love). The client wanted it in VB, and fortunately there's a Convert To VB.NET feature. It's great. Translated all the code, and it builds. (I've been a "Notepad" guy for a long time, so I may seem a little old-fashioned.) But I get this er...
In VB.NET, namespace declarations are relative to the default namespace of the project. So if the default namespace for the project is set to X.Y, everithyng between `Namespace Z` and `End Namespace` will be in the X.Y.Z namespace. In C# you have to provide the full namespace name, regardless of the default namespace o...
The problem may be cause by VB.NET & C# projects using different naming conventions for project assemblies and how the project namespace is used. At least that's were I would start looking.
"Could not load type" in web service converted to VB.NET
[ "", "c#", "vb.net", "web-services", "translation", "sharpdevelop", "" ]
I have an internal enterprise app that currently consumes 10 different web services. They're consumed via old style "Web References" instead of using WCF. The problem I'm having is trying to work with the other teams in the company who are authoring the services I'm consuming. I found I needed to capture the exact SOA...
This seems to be a common question, as I just asked it and was told to look [here](https://stackoverflow.com/questions/300674/getting-raw-soap-data-from-a-web-reference-client-running-in-aspnet). You don't have to edit the generated `Reference.cs`. You can reference the extension in your application's `app.config`.
Is this a webapp? Place your SoapExtension code in a HTTPModule, and inject the SOAP envelope into the HTTPOutput stream. That way, when in debug mode, I picture something like a collapsible div on the top of the page that lists all SOAP communication for that page.
Soap logging in .net
[ "", "c#", "web-services", "soap", "" ]
I am writing a program to simulate the actual polling data companies like Gallup or Rasmussen publish daily: *[www.gallup.com](http://www.gallup.com)* and *[www.rassmussenreports.com](http://www.rassmussenreports.com)* I'm using a brute force method, where the computer generates some random daily polling data and then...
Would something like this work? ``` from random import randint mcworks = [] for n in xrange(NUM_ITERATIONS): mctest = [randint(0, 100) for i in xrange(5)] if sum(mctest[:3])/3 == mcavg[2]: mcworks.append(mctest) # mcavg is real data ``` In the end, you are left with a list of valid `mctest` list...
Are you talking about doing this? ``` >>> a = [ ['a', 'b'], ['c', 'd'] ] >>> a[1] ['c', 'd'] >>> a[1][1] 'd' ```
Storing multiple arrays in Python
[ "", "python", "arrays", "" ]
I have an AST derived from the ANTLR Parser Generator for Java. What I want to do is somehow construct a control flow graph of the source code, where each statement or expression is a unique Node. I understand there must be some recursiveness to this identification, I was wondering what you would suggest as the best op...
Usually CFGs are computed on a lower-level representation (e.g. JVM bytecode). Someone did [a thesis](http://www.ssw.uni-linz.ac.at/General/Staff/TW/Wuerthinger06Bachelor.pdf) on such things a few years ago. There might be a helpful way described in there for how to get at that representation. Since your source and ta...
Producing a full control flow graph that really takes into account all the language issues is harder than it looks. Not only do you have to identify what appears to be the "basic blocks", but you have to identify function calls (sort of easy, but identifying the *target* might be harder), where behind-the-scenes operat...
Get Control flow graph from Abstract Syntax Tree
[ "", "java", "parsing", "abstract-syntax-tree", "control-flow", "" ]
I'm wandering myself what component is the best for displaying fast search results in swing. I want to create something like this, make a text field where user can enter some text, during his entering I'll improve in back end fast search on database, and I want to show data bellow the text box, and he will be able to b...
Are you looking for something like an AutoComplete component for Java Swing? [SwingX](https://swingx.dev.java.net/) has such a component. See [here](http://javadesktop.org/swinglabs/build/weekly/latest/swingx-HEAD/javadoc/org/jdesktop/swingx/autocomplete/AutoCompleteDecorator.html) for the JavaDoc. It has a lot of uti...
I strongly, strongly recommend that you take a look at [Glazed Lists](http://publicobject.com/glazedlists/) - this is one of the finer open source Java libraries out there, and it makes the bulk of what you are asking about super easy.
Fast search in java swing applications?
[ "", "java", "swing", "search", "" ]
Using the method `Application.Restart()` in C# should restart the current application: but it seems that this is not always working. Is there a reason for this Issue, can somebody tell me, why it doesn't work all the time?
There could be a lot of reasons for this. It's not that the method doesn't work; rather, many times programmers forget that they've put something in their code that would stop the application from automatically shutting down, or starting up. Two examples: * The Closing event on a form can stop an app's shutdown * If y...
In my case (NO single-instance), where ``` Application.Restart(); ``` didn't work, ``` System.Diagnostics.Process.Start(Application.ExecutablePath); Application.Exit(); ``` did the job!
Why is Application.Restart() not reliable?
[ "", "c#", ".net", "" ]
I've been doing code review (mostly using tools like FindBugs) of one of our pet projects and FindBugs marked following code as erroneous (pseudocode): ``` Connection conn = dataSource.getConnection(); try{ PreparedStatement stmt = conn.prepareStatement(); //initialize the statement stmt.execute(); Re...
One problem with ONLY closing the connection and not the result set, is that if your connection management code is using connection pooling, the `connection.close()` would just put the connection back in the pool. Additionally, some database have a cursor resource on the server that will not be freed properly unless it...
I've had problems with unclosed ResultSets in Oracle, even though the connection was closed. The error I got was ``` "ORA-01000: maximum open cursors exceeded" ``` So: Always close your ResultSet!
ResultSet not closed when connection closed?
[ "", "java", "jdbc", "findbugs", "" ]
I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the e...
EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters. To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply [serialize the two arrays to JSON](https://github.com/douglascrockford/JSON-js/blob/master/json2.js)...
As serialization doesn't work generally (only when the order of properties matches: `JSON.stringify({a:1,b:2}) !== JSON.stringify({b:2,a:1})`) you have to check the count of properties and compare each property as well: ``` const objectsEqual = (o1, o2) => Object.keys(o1).length === Object.keys(o2).length ...
Comparing Arrays of Objects in JavaScript
[ "", "javascript", "arrays", "comparison", "array-of-dict", "" ]
My JavaScript is pretty nominal, so when I saw this construction, I was kind of baffled: ``` var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); shareProxiesPref.disabled = proxyTypePref.value != 1; ``` Isn't it better to do an if on `proxyTypePref.value`, and then declare the var in...
It depends on the context of this code. If it's running on page load, then it would be better to put this code in an if block. But, if this is part of a validation function, and the field switches between enabled and disabled throughout the life of the page, then this code sort of makes sense. It's important to remem...
> (Incidentally, I also found this form very hard to read in comparison to the normal usage. Not necessarily, although that was my first thought, too. A code should always emphasize its function, especially if it has side effects. If the writer's intention was to emphasize the assignment to `sharedProxiesPref.disabled...
Javascript: declaring a variable before the conditional result?
[ "", "javascript", "" ]
I'm looking for something that will show me the size of each folder within my main folder recursively. This is a [LAMP](http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29) server with a CGI-Bin so most any PHP script should work or anything that will work in the CGI-Bin. My hosting company does not provide an in...
Strange, I came up on Google with [many relevant results](http://www.google.com.au/search?hl=en&q=php+directory+size&btnG=Google+Search&meta=) and [this one](http://www.go4expert.com/forums/showthread.php?t=290) is probably the most complete. > The function "getDirectorySize" will > ignore link/shorcuts to > files/dir...
If you have shell access you can run the command ``` $ du -h ``` or perhaps use this, if PHP is configured to allow execution: ``` <?php $d = escapeshellcmd(dirname(__FILE__)); echo nl2br(`du -h $d`) ?> ```
Get the Directory sizes on a Remote Host with a PHP script
[ "", "php", "hosting", "cgi", "" ]
I have some domain logic implemented in a number of POJOs. I want to write a Swing user interface to allow the user to initiate and see the results of various domain actions. What's the best pattern/framework/library for communications between the UI and the domain? This boils down into: * the UI being able to conver...
Definitely MVC - something like this [example](http://www.leepoint.net/notes-java/GUI/structure/40mvc.html) which clearly splits things out. The problem with the Swing examples is that they seem to show the MVC all working within the swing stuff, which does not seem right to me
**MVC** is fantastic for an individual widget, however it gets a little unruly when you have `pages` and `forms` with lots of widgets. One thing that might be worth looking into (and I'm not endorsing it, I haven't actually used it, just implemented something very similar for myself) is the [Beans Binding Framework (J...
Best way for a Swing GUI to communicate with domain logic?
[ "", "java", "user-interface", "swing", "" ]
Is there any way to create C# 3.0 anonymous object via Reflection at runtime in .NET 3.5? I'd like to support them in my serialization scheme, so I need a way to manipulate them programmatically. *edited later to clarify the use case* An extra constraint is that I will be running all of it inside a Silverlight app, s...
Here is another way, seems more direct. ``` object anon = Activator.CreateInstance(existingObject.GetType()); ```
Yes, there is. From memory: ``` public static T create<T>(T t) { return Activator.CreateInstance<T>(); } object anon = create(existingAnonymousType); ```
Create anonymous object by Reflection in C#
[ "", "c#", "silverlight", "reflection", "anonymous-objects", "" ]
When a customer logs in to my site, I need to know their account id and their menu id. This lets me know what data they can see on a page and what menu they get. I don't want to have to read this data over and over. Should I store this in a session variable or customize the membership user and membership provider to co...
As already suggested, the profile system is super easy. <http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx>
If you're going to use the profile provider, make sure to check out the "Optimize ASP.NET 2.0 Profile Provider" section of this article if you're running a high-traffic site: <http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx>
Where is the best place to store user related data in asp.net?
[ "", "c#", "asp.net", "" ]
``` public static IList<T> LoadObjectListAll<T>() { ISession session = CheckForExistingSession(); var cfg = new NHibernate.Cfg.Configuration().Configure(); var returnList = session.CreateCriteria(typeof(T)); var list = returnList.List(); var castList = list.Cast<typeof(T)>(); return castList; } ...
`T` is not a type nor a `System.Type`. `T` is a type parameter. `typeof(T)` returns the type of `T`. The `typeof` operator does not act on an object, it returns the `Type` object of a type. <http://msdn.microsoft.com/en-us/library/58918ffs.aspx> @John is correct in answering your direct question. But the NHibernate co...
I think ``` var castList = list.Cast<typeof(T)>(); ``` should be ``` var castList = list.Cast<T>(); ``` > @Jon Limjap The most glaring error I can see is > that an `IList` is definitely different from an `IList<T>`. An `IList` is non-generic > (e.g., `ArrayList`). The original question was already using an `IList<...
IList.Cast<typeof(T)>() returns error, syntax looks ok
[ "", "c#", ".net", "nhibernate", ".net-3.5", "syntax", "" ]