Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have the following file: ``` <html> <head> <title></title> <link rel="css" type="text/css" href="/empty.css" title="css" /> <script type="text/javascript" src="/Prototype"></script> <script type="text/javascript"> function load_content() { var d = new Date(); new Ajax.PeriodicalUpdater('content', '/DOC?'+d.getTi...
Rather than changing the sheet in a single link, try using alternate style sheets. See this link on using alternate style sheets: <http://www.alistapart.com/articles/alternate/>
The best way to include files via javascript is to insert a new dom element. ``` var a = document.createElement('link'); a.href="inset.css"; a.rel="stylesheet"; document.getElementsByTagName("head")[0].appendChild(a); ``` However, obviously the problem you're going to run into though is that firefox and ie will not r...
Dynamically changing stylesheet path not working in IE and Firefox
[ "", "javascript", "css", "ajax", "" ]
I understand passing in a function to another function as a callback and having it execute, but I'm not understanding the best implementation to do that. I'm looking for a very basic example, like this: ``` var myCallBackExample = { myFirstFunction : function( param1, param2, callback ) { // Do something w...
You can just say ``` callback(); ``` Alternately you can use the `call` method if you want to adjust the value of `this` within the callback. ``` callback.call( newValueForThis); ``` Inside the function `this` would be whatever `newValueForThis` is.
You should check if the callback exists, and is an executable function: ``` if (callback && typeof(callback) === "function") { // execute the callback, passing parameters as necessary callback(); } ``` A lot of libraries (jQuery, dojo, etc.) use a similar pattern for their asynchronous functions, as well as n...
Getting a better understanding of callback functions in JavaScript
[ "", "javascript", "function", "callback", "" ]
I have a VB5 (non .net) project that I would like to upgrade to a c# project. Has anyone have any suggestions on methods or free tools that are avalible to help me with this. Thanks Brad
You are better off with a straight rewrite.
What I would suggest is first convert the project to VB6. It'll be much easier to go forward from there. There are a number of tools to help you do this. There is [VBMigration Partner](http://www.vbmigration.com/) and there is [vbto](http://www.vbto.net/). I've not tried either so YMMV. If costs are a constraint you c...
How do I convert VB5 project to a c# project
[ "", "c#", "vb6-migration", "vb5", "" ]
Is there any condition where finally might not run in java? Thanks.
from the [Sun Tutorials](http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html) > Note: If the JVM exits while the try > or catch code is being executed, then > the finally block may not execute. > Likewise, if the thread executing the > try or catch code is interrupted or > killed, the finally bloc...
[System.exit](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#exit(int)) shuts down the Virtual Machine. > Terminates the currently running Java > Virtual Machine. The argument serves > as a status code; by convention, a > nonzero status code indicates abnormal > termination. > > This method calls the `e...
Does a finally block always run?
[ "", "java", "finally", "" ]
I've just started playing with Guice, and a use-case I can think of is that in a test I just want to override a single binding. I think I'd like to use the rest of the production level bindings to ensure everything is setup correctly and to avoid duplication. So imagine I have the following Module ``` public class Pr...
This might not be the answer you're looking for, but if you're writing unit tests, you probably shouldn't be using an injector and rather be injecting mock or fake objects by hand. On the other hand, if you really want to replace a single binding, you could use `Modules.override(..)`: ``` public class ProductionModul...
Why not to use inheritance? You can override your specific bindings in `overrideMe` method, leaving shared implementations in `configure` method. ``` public class DevModule implements Module { public void configure(Binder binder) { binder.bind(InterfaceA.class).to(TestDevImplA.class); overrideMe(bi...
Overriding Binding in Guice
[ "", "java", "unit-testing", "guice", "" ]
So I'm trying to build a script that automagically prepends valid column names with its appropriate table prefix (e.g. "t." or "r.") ``` $t_columns = array('id', 'name', 'label'); $r_columns = array('related_value'); ``` INPUT: ``` id > 1 AND (name = 'Hello' OR label IN ('World', 'Planet name AND label')) AND (relat...
This can be done in a lot of ways, and also using regex. I'd personally use an array approach. First of all, I'd define the mangling table this way: ``` $table = array( 'id' => 't.id', 'name' => 't.name', 'label' => 't.label', 'related_value' => 'r.related_value' ); ``` This will make a lot easier the...
After a few seconds' thinking, here's how I'd tackle it: Walk through the string, char by char, looking for single quotes, but skipping over escaped characters. The stuff between two unescaped single quotes (i.e. the strings) would be replaced with an unique token, and put into an associative array, with that token as...
PHP/RegEx - Logic for prepending table names
[ "", "php", "regex", "logic", "" ]
I'm trying to write a C# program, where when a user enters some data into a text box and clicks on a "save" button, the information is stored in some sort of file that when the program is opened the next time around, the information is automatically loaded in. I'm using Visual C# express. What's the best way to do thi...
Make your user data serializable by adding the keyword: ``` [Serializable] ``` above your data structure. When you load the dialog box, load your serialized structure from disk, and when you leave the dialog, save the data structure. From a style standpoint, you should probably not have the dialog box change data un...
[Sql Compact Edition](http://www.microsoft.com/Sqlserver/2005/en/us/compact.aspx) would hide the data from being easily accessible (and its free). You can also password protect a CE database. A SQL CE database is contained completely in an .SDF file, like Access, so you can copy the .sdf file around and not have to wor...
C# Storage of User Entered Data
[ "", "c#", "data-storage", "" ]
I've been programming opengl using glut as my window handler, lately i've been thinking if there are any advantages to switching to an alternate window handler such as wxWidgets or qt. Are there any major differences at all or is it just a matter of taste? Since glut provides some additional functions for opengl-progr...
I can only speak from experiential of using QT: Once you have the basic structure set up then it is a simple case of doing what you have always done: for example, the project I am working on at the moment has an open gl widget embedded in the window. This widget has functions such as initializeGL, resize...paintGL et...
You need to move from glut as soon as you want more complex controls and dialogs etc. QT has an excellent [openGL widget](http://doc.trolltech.com/4.4/qglwidget.html) there is also an interesting article in the newsletter about [drawing controls ontop of GL](http://doc.trolltech.com/qq/qq26-openglcanvas.html) to give ...
window handlers for opengl
[ "", "c++", "opengl", "graphics", "3d", "glut", "" ]
The [Java documentation](https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html) says: > it is not possible for two invocations of synchronized methods on the same object to interleave. What does this mean for a static method? Since a static method has no associated object, will the synchronized ...
> Since a static method has no associated object, *will the synchronized keyword lock on the class, instead of the object?* Yes. :)
Just to add a little detail to Oscar's (pleasingly succinct!) answer, the relevant section on the Java Language Specification is [8.4.3.6, 'synchronized Methods'](http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.3.6): > A synchronized method acquires a monitor ([§17.1](https://docs.oracle.com/javase...
Java synchronized static methods: lock on object or class
[ "", "java", "class", "static", "methods", "synchronized", "" ]
Currently, we're using the following version numbering scheme for our C# winforms project: "Major Release"."Minor Release"."Iteration Number"."Build Number within that Iteration" We wanted to be able to identify the iteration number and the build number within that iteration just by looking at the version number. In...
I track the agile projects' iteration, not the software projects' iteration. If a late starter side project joins after another project it will therefore init with the current agile project iteration, and there will be no misalignment. It should not be possible for a technical project outside of the agile project's do...
Personally, I think that the release versioning I've liked the best is to do away with the whole `major.minor` stuff altogether. I think that this is only really feasible for internal applications, but for that, it makes life a lot easier. Typically, if you're developing internally facing applications, I've noticed th...
How do you do version numbering in an agile project?
[ "", "c#", "agile", "versioning", "" ]
I want to cancel this operation if the user selects a specific item because I don't want to force the user to open the dropdown again. Can this be done?
Why are you putting that item into the drop down list if you will not allow the user to select it? Can you modify your design to provide a more useful user interface?
Maybe you could just use [ListBox](http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.aspx) control? Preventing combobox closing is imho a bad UI design idea...
Cancel ComboBox dropdown closing
[ "", "c#", "winforms", "combobox", "" ]
I did the following to upper case the first letter in each word but it's only working on the first word. Could someone explain why? ``` static void Main(string[] args) { string s = "how u doin the dnt know about medri sho min shan ma baref shu"; string a = tocap(s); Console.WriteLine(a); } public static s...
I guess you'll get this better if you understand actually what you're doing: ``` public static string tocap(string s) { // This says: "if s length is 1 then returned converted in upper case" // for instance if s = "a" it will return "A". So far the function is ok. if (s.Length == 1) re...
Since no professor would accept this solution, I feel fine letting anyone googling this know that you can just use [ToTitleCase](http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx)
Why is only the first word capitalizing when using the tocap() function?
[ "", "c#", "string", "" ]
How would I go about programmatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?
From python, if you have [appscript](http://appscript.sourceforge.net/) installed (`sudo easy_install appscript`), you can simply do ``` from appscript import app, mactypes app('Finder').desktop_picture.set(mactypes.File('/your/filename.jpg')) ``` Otherwise, this applescript will change the desktop background ``` te...
If you are doing this for the current user, you can run, from a shell: ``` defaults write com.apple.desktop Background '{default = {ImageFilePath = "/Library/Desktop Pictures/Black & White/Lightning.jpg"; };}' ``` Or, as root, for another user: ``` /usr/bin/defaults write /Users/joeuser/Library/Preferences/com.apple...
How can I programmatically change the background in Mac OS X?
[ "", "python", "image", "macos", "" ]
Some loading routines in my program takes to long to complete. I want a quick small snippet for checking how long a function took to execute. By small I mean "preferably without 3rd party libraries". Maybe something as simple as taking the system time? ``` start = current_system_time() load_something() delta = curren...
Your answer: Yes Caveat: That **WON'T** work in multihtreaded code or multiple core machines, you need a robust wall-clock timer. So I recommend you use omp's wallclock. OMP is included with VC and GCC, and most compilers and its a standard you don't need to worry about disappearing ``` #include <omp.h> // Starting ...
``` #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) namespace win32 { #include <windows.h> } class timer { win32::LARGE_INTEGER start_time_; public: timer() { QueryPerformanceCounter( &start_time_ ); } void restart() { QueryPerformanceCounter( &start_time_ ); } double elapsed() const...
Looking for benchmarking code snippet (c++)
[ "", "c++", "windows", "time", "benchmarking", "" ]
I need to remove a highly referenced table in a SQL Server database. How can I get a list of all the foreign key constraints I will need to remove in order to drop the table? (SQL answers preferable over clicking about in the GUI of the management studio.)
Not sure why no one suggested but I use `sp_fkeys` to query foreign keys for a given table: ``` EXEC sp_fkeys 'TableName' ``` You can also specify the schema: ``` EXEC sp_fkeys @pktable_name = 'TableName', @pktable_owner = 'dbo' ``` Without specifying the schema, the [docs](https://learn.microsoft.com/en-us/sql/rel...
This gives you: * The FK itself itself * Schema that the FK belongs to * The "*referencing table*" or the table that has the FK * The "*referencing column*" or the column inside referencing table that points to the FK * The "*referenced table*" or the table that has the key column that your FK is pointing to * The "*r...
How can I list all foreign keys referencing a given table in SQL Server?
[ "", "sql", "sql-server", "t-sql", "" ]
I'm adding some encryption methods to a class library (C# 2.0) and would like to know the best place to put the pass phrase, salt value and initialisation vector required. Is it a really bad idea just to hard-code these into the DLL, or should I be be encoding them and storing them somewhere else? Thanks. **Edit:** F...
If you're using public key encryption, then you'll want to freely distribute the public key (most likely) and keep access to the private key highly restricted (only on storage media that you know are secure). Either way, it is typical to store keys as base64-encoded strings in XML files. The RSACryptoServiceProvider cl...
If you hard-code you initialisation vector and key into the DLL, then you really may as well forgo encryption altogether. If you could tell us a bit more about the reason you're using encryption here and how the data needs to be accessed precisely, perhaps I can suggest how you can make it secure. EDIT: You'll probabl...
Best way to 'hide' pass phrases, init vectors etc.. for encryption in a class library
[ "", "c#", "security", "dll", "encryption", "" ]
Imagine I am doing something like this: ``` void *p = malloc (1000); *((char*)p) = some_opcode; *((char*)p+1) = another_opcode; // for the sake of the example: the opcodes are ok .... etc... ``` How can I define a function pointer to call p as if it was a function? (i'm using VC++ 2008 express). Thanks
A comment wasn't enough space. Joe\_Muc is correct. You should not stuff code into memory obtained by `malloc` or `new`. You will run into problems if you change the page properties of pages that Windows allocates. This isn't a problem becuase using VirtualAlloc() and the related WIn32 APIs is every easy: call [Virtua...
Actually, malloc probably won't cut it. On Windows you probably need to call something like [VirtualAlloc](<http://msdn.microsoft.com/en-us/library/aa366887(VS.85).aspx)> in order to get an executable page of memory. Starting small: ``` void main(void) { char* p = (char*)VirtualAlloc(NULL, 4096, MEM_COMMIT, PAGE_...
calling code stored in the heap from vc++
[ "", "c++", "pointers", "assembly", "function-pointers", "opcode", "" ]
Well I tried to figure out is this possible in any way. Here is code: ``` a=function(text) { var b=text; if (!arguments.callee.prototype.get) arguments.callee.prototype.get=function() { return b; } else alert('already created!'); } var c=new a("test"); // creates prototype inst...
JavaScript traditionally did not provide a mechanism for property hiding ('private members'). As JavaScript is lexically scoped, you could always simulate this on a per-object level by using the constructor function as a closure over your 'private members' and defining your methods in the constructor, but this won't w...
With modern browsers adopting some ES6 technologies, you can use `WeakMap` to get around the GUID problem. This works in IE11 and above: ``` // Scope private vars inside an IIFE var Foo = (function() { // Store all the Foos, and garbage-collect them automatically var fooMap = new WeakMap(); var Foo = fun...
Javascript private member on prototype
[ "", "javascript", "prototype", "private", "" ]
How does the code looks that would create an object of class: ``` string myClass = "MyClass"; ``` Of the above type, and then call ``` string myMethod = "MyMethod"; ``` On that object?
* Use [`Type.GetType(string)`](http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx) to get the type object. * Use [`Activator.CreateInstance(Type)`](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx) to create an instance. * Use [`Type.GetMethod(string)`](http://msdn.microsoft.co...
I've created a library which simplifies dynamic object creation and invocation using .NET you can download the library and the code in google code: [Late Binding Helper](http://code.google.com/p/latebindinghelper/) In the project you will find a [Wiki page with the usage](http://code.google.com/p/latebindinghelper/wiki...
How to do dynamic object creation and method invocation in .NET 3.5
[ "", "c#", ".net", "dynamic", "clr", "invocation", "" ]
I have a forum on a website I master, which gets a daily dose of pron spam. Currently I delete the spam and block the IP. But this does not work very well. The list of blocked IP's is growing quickly, but so is the number of spam posts in the forum. The forum is entirely my own code. It is built in PHP and MySQL. Wha...
In a guestbook app I wrote, I implemented two features which prevent most of the spam: * Don't allow POST as the first request in a session * Require a valid HTTP Refer(r)er when posting
One way that I know which works is to use JavaScript before submitting the form. For example, to change the method from GET to POST. ;) Spambots are lousy at executing JavaScript. Of course, this also means that non-Javascript people will not be able to use your site... if you care about them that is. ;) (Note: I don't...
How do I protect my forum against spam?
[ "", "php", "mysql", "forum", "spam-prevention", "" ]
I have a console application that contains quite a lot of threads. There are threads that monitor certain conditions and terminate the program if they are true. This termination can happen at any time. I need an event that can be triggered when the program is closing so that I can cleanup all of the other threads and ...
I am not sure where I found the code on the web, but I found it now in one of my old projects. This will allow you to do cleanup code in your console, e.g. when it is abruptly closed or due to a shutdown... ``` [DllImport("Kernel32")] private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add); p...
Full working example, works with ctrl-c, closing the windows with X and kill: ``` using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace TestTrapCtrlC { public class Program { static bool exitSystem = fa...
Capture console exit C#
[ "", "c#", ".net", "events", "console", "exit", "" ]
Is there a way to use the DPAPI (Data Protection Application Programming Interface) on Windows XP with Python? I would prefer to use an existing module if there is one that can do it. Unfortunately I haven't been able to find a way with Google or Stack Overflow. **EDIT:** I've taken the example code pointed to by "dF...
I have been using `CryptProtectData` and `CryptUnprotectData` through ctypes, with the code from <http://article.gmane.org/gmane.comp.python.ctypes/420> and it has been working well.
Also, pywin32 implements CryptProtectData and CryptUnprotectData in the win32crypt module.
Using DPAPI with Python?
[ "", "python", "windows", "security", "encryption", "dpapi", "" ]
From some old c++ code im trying to use a com dll, it works fine when the dll is registered, but it crahses if the dll isnt registered. // Initialize COM. HRESULT hr = CoInitialize(NULL); IGetTestPtr ptest(\_\_uuidof(tester)); *"Use method from the dll"* // Uninitialize COM. CoUninitialize(); Is it anyway to check...
Calling CreateInstance on your object will return an HRESULT that can be tested for success: ``` IGetTestPtr p = null; HRESULT hRes = p.CreateInstance( __uuidof(tester) ); bool bSuccess = SUCCEEDED(hRes); ``` This assumes you've created an interface wrapper around your type library using Visual Studio, where COM Sma...
If the COM class is not registered then CoCreateInstance will return REGDB\_E\_CLASSNOTREG. You should check for general success or failure by using the SUCCEEDED() or FAILED() macros. You also need to create the object properly - see MDSN for an [introduction to COM](http://msdn.microsoft.com/en-us/library/ms680573(VS...
How to prevent crashing if com dll isnt registered
[ "", "c++", "com", "" ]
I'm trying to create a DataGridTableStyle object so that I can control the column widths of a DataGrid. I've created a BindingSource object bound to a List. Actually it's bound to an anonymous type list created though Linq in the following manner (variable names changed for clarity of what I'm doing): ``` List<myType>...
I've found the way to make this work. I'll break it out into sections... --- ``` List<myType> myList = new List<myType>(someCapacity); . ...populate the list with query from database... . ``` --- ``` DataGridTableStyle myDataGridTableStyle = new DatGridtTableStyle(); DataGridTextBoxColumn colA = new DataGridTextBox...
Just to add to the collection of answers already on this page.... I was just frustrated with this same issue trying to develop my fist application using windows forms and compact framework (For Windows Mobile 6.5). What I found out, through Marc Gravell's comment above is that indeed is possible to get the run time M...
How do you get the proper mapping name from a binding source bound to a List<T>, or an anonymous type, to use on a DataGridTableStyle?
[ "", "c#", "datagrid", "compact-framework", "bindingsource", "datagridtablestyle", "" ]
One of the biggest annoyances I find in Python is the inability of the `re` module to save its state without explicitly doing it in a match object. Often, one needs to parse lines and if they comply a certain regex take out values from them by the same regex. I would like to write code like this: ``` if re.match('foo ...
Trying out some ideas... It looks like you would ideally want an expression with side effects. If this were allowed in Python: ``` if m = re.match('foo (\w+) bar (\d+)', line): # do stuff with m.group(1) and m.group(2) elif m = re.match('baz whoo_(\d+)', line): # do stuff with m.group(1) elif ... ``` ... then yo...
You might like [this module](http://code.activestate.com/recipes/456151/) which implements the wrapper you are looking for.
Python's re module - saving state?
[ "", "python", "regex", "" ]
I want to read, write and create Spreadsheets in the Open Document Format with Java. And I want the resulting Java-program running on a computer without OpenOffice.org or other ODS-capable programs installed. Exists a library to access this format?
Take a look at jOpenDocument: <http://www.jopendocument.org/documentation.html> Especially: <http://www.jopendocument.org/start_spreadsheet_3.html>
jOpenDocument is all you need.
How can I access spreadsheets in the open document format (.ods) with Java?
[ "", "java", "spreadsheet", "odf", "" ]
I have a Windows Forms (.Net 2.0) app and I have a request to embed some custom images into some textboxes(like the new version of Tortoise does).
I haven't used OwnerDraw on a textbox, but I've used it on other controls such as the listbox and listview and I've seen other people do this with textboxes. I found a tutorial that should point you in the right direction, it's not used for displaying images in the textbox per se, but it could be used for that: <http:...
Hmm. Why don't you create a new userControl which has the BackColor of the TextBox. Hide TextBox's Border. Then subscribe to Paint event of the UC and draw the borders to resemble the textbox one. In the Paint Handler you can also draw an image. In the UserControl you can easily set the bounds of any child control such...
Embed image into a textbox
[ "", "c#", "winforms", "" ]
From Joel Spolsky's [article](http://www.joelonsoftware.com/articles/LeakyAbstractions.html) on leaky abstractions: > [C]ertain SQL queries are thousands of times slower than other logically equivalent queries. A famous example of this is that some SQL servers are dramatically faster if you specify "where a=b and b=c ...
Obviously, a = b and b = c => a = c - this is related to transitive closure. The point Joel was making is that some SQL servers are poor at optimizing queries, so some of the SQL queries might be written with "extra" qualifiers as in the example. In this example, remember that a, b and c as above often refer to differ...
Here's a simpler explanation, where everything is all in one table. Suppose A and C are both indexed, but B is not. If the optimizer can't realize that A = C, then it has to use the non-indexed B for both WHERE conditions. But if you then tell the server that a=c, it can efficiently apply that filter first and greatl...
SQL question from Joel Spolsky article
[ "", "sql", "query-optimization", "" ]
I appear to have a memory leak in this piece of code. It is a console app, which creates a couple of classes (WorkerThread), each of which writes to the console at specified intervals. The Threading.Timer is used to do this, hence writing to the console is performed in a separate thread (the TimerCallback is called in ...
Well, having had some time to look into this again, it appears that the memory leak is a bit of a red herring. *When I stop writing to the console, the memory usage stops increasing*. However, there is a remaining issue in that every time I edit the test.xml file (which fires the Changed event on the FileSystemWatcher...
You have two issues, both separate: In Watcher.Changed's handler you call Thread.Sleep(3000); This is poor behaviour in a callback of a thread you do not own (since it is being supplied by the pool owned/used by the watcher. This is not the source of your problem though. This it in direct violation of the [guidelines ...
Memory leak while using Threads
[ "", "c#", ".net", "multithreading", "memory", "timer", "" ]
I am creating a test program to test the functionality of program which calcultes CPU Utilization. Now I want to test that program at different times when CPU utilization is 100%, 50% 0% etc. My question how to make CPU to utilize to 100% or may be > 80%. I think creating a while loop like will suffice ``` while(i+...
You're right to use a loop, but: * You've got IO * You've got a sleep Basically nothing in that loop is going to take very much CPU time compared with the time it's sleeping or waiting for IO. To kill a CPU you need to give it *just* CPU stuff. The only tricky bit really is making sure the C++ compiler doesn't optim...
Your loop mostly sleeps, which means it has very light CPU load. Besides of Sleep, be sure to include some loop performing any computations, like this (Factorial implementation is left as an exercise to reader, you may replace it with any other non-trivial function). ``` while(i++< 2000) { int sleepBalance = 10; //...
Create thread with >70% CPU utilization
[ "", "c++", "windows", "" ]
In the current C++ standard (C++03), there are too few specifications about text localization and that makes the C++ developer's life harder than usual when working with localized texts (certainly the C++0x standard will help here later). ### Assuming the following scenario (which is from real PC-Mac game development ...
At a small Video Game Company, Black Lantern Studios, I was the Lead developer for a game called Lionel Trains DS. We localized into English, Spanish, French, and German. We knew all the languages up front, so including them at compile time was the only option. (They are burned to a ROM, you see) I can give you inform...
I strongly disagree with the accepted answer. First, the part about using static array lookups to speed up the text lookups [is counterproductive premature optimization](https://stackoverflow.com/questions/385506/when-is-optimisation-premature/385529) - Calculating the layout for said text and rendering said text uses ...
Bests practices for localized texts in C++ cross-platform applications?
[ "", "c++", "localization", "" ]
Currently i am working on a desktop application which consists mathematical analysiss.I am using qt for GUI and project written in c++. When user starts an analysis, i open a worker thread and start a progress bar.Everything is ok up to now, problem starts when user cancels operation.Operation is complex, i am using se...
A pretty common way to close down worker threads, is to mark it with a flag, and let the worker thread inspect this flag at regular intervals. If marked, it should discontinue its workflow, clean up and exit. Is that a possibility in your situation?
The worker thread should check for a message to stop. the message can be through a flag or an event. when stop message received the thread should exit. USE BOOST safe pointers for all memory allocated. on exit you would have no memory leaks. ever.
How to prevent memory leaks while cancelling an operation in a worker thread?
[ "", "c++", "design-patterns", "qt", "memory-leaks", "worker-thread", "" ]
In my quest in trying to learn more about OOP in PHP. I have come across the constructor function a good few times and simply can't ignore it anymore. In my understanding, the constructor is called upon the moment I create an object, is this correct? But why would I need to create this constructor if I can use "normal...
Yes the constructor is called when the object is created. A small example of the usefulness of a constructor is this ``` class Bar { // The variable we will be using within our class var $val; // This function is called when someone does $foo = new Bar(); // But this constructor has also an $var with...
The constructor allows you to ensure that the object is put in a particular state before you attempt to use it. For example, if your object has certain properties that are required for it to be used, you could initialize them in the constructor. Also, constructors allow a efficient way to initialize objects.
Benefits of using a constructor?
[ "", "php", "oop", "constructor", "" ]
I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success? If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas?
Besides the Jeff Hardy blog post on [Django + IronPython](http://jdhardy.blogspot.com/2008/12/django-ironpython.html) mentioned by Tony Meyer, it might be useful to also read Jeff's two other posts in the same series on his struggles with IronPython, easy\_install and zlib. The first is [Solving the zlib problem](http:...
[Here's a database provider that runs on .NET & that works with Django](http://blogs.msdn.com/dinoviehland/archive/2008/03/17/ironpython-ms-sql-and-pep-249.aspx)
Django on IronPython
[ "", "python", "django", "ironpython", "" ]
I'm trying to create system users with a php script securely, In that, I'd like to be able to hash the password with the php script, so that their password shows up nowhere in the bash history. How to I take a string, and hash it so it is a unix password hash? ``` $UX_PW = some_function('my_password'); exec("useradd ...
It's `crypt()` that implements the UNIX password hashing. <http://us.php.net/manual/en/function.crypt.php>
Depending on your system, you're either looking for `crypt()` or `md5()`. Traditionally, unix uses DES-encrypted passwords (thats the 'crypt' function), with a 2-character salt (two random characters from the set [a-zA-Z0-9./]) which is prepended to the hash to perturb the algorithm. Newer systems often use MD5 thoug...
How do I create a unix password hash with php
[ "", "php", "security", "unix", "hash", "passwords", "" ]
Part of a programme builds this list, ``` [u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale'] ``` I'm currently trying to sort it alphabetically by the name of the evolution rather than by the number. Is there any way I...
You have to get the "key" from the string. ``` def myKeyFunc( aString ): stuff, x, label = aString.partition(' x ') return label aList.sort( key= myKeyFunc ) ```
How about: ``` lst.sort(key=lamdba s: s.split(' x ')[1]) ```
python, sorting a list by a key that's a substring of each element
[ "", "python", "list", "sorting", "" ]
I'm using google app engine, and am having trouble writing querys to filter ReferenceProperties. eg. ``` class Group(db.Model): name = db.StringProperty(required=True) creator = db.ReferenceProperty(User) class GroupMember(db.Model): group = db.ReferenceProperty(Group) user = db.ReferenceProperty(Use...
If what you want is to get the members of a group, ReferenceProperties have that built-in. ``` class GroupMember(db.Model): group = db.ReferenceProperty(Group, collection_name="groupMembers") user = db.ReferenceProperty(User, collection_name="groupMembers") ``` Then you can write: ``` # get the group entity ...
If your groups are uniquely named, then your "group.name" is a unique identifier of a Group entity. That means you can write: ``` members = models.GroupMember.all().filter( "group =",model.Group.gql("WHERE name=:1", group_name).get() ) ``` though you only need to do that if you don't already have the group...
Filtering models with ReferenceProperties
[ "", "python", "google-app-engine", "" ]
I am trying to compile the following code: ``` private String dataToString(){ Map data = (HashMap<MyClass.Key, String>) getData(); String toString = ""; for( MyClass.Key key: data.keySet() ){ toString += key.toString() + ": " + data.get( key ); return toString; } ``` I get an error in the for ...
A slightly more efficient way to do this: ``` Map<MyClass.Key, String> data = (HashMap<MyClass.Key, String>) getData(); StringBuffer sb = new StringBuffer(); for (Map.Entry<MyClass.Key,String> entry : data.entrySet()) { sb.append(entry.getKey()); sb.append(": "); sb.append(entry.getValue())...
Change: ``` Map data = (HashMap<MyClass.Key, String>) getData(); ``` to ``` Map<MyClass.Key, String> data = (HashMap<MyClass.Key, String>) getData(); ``` The problem is that `data.keySet()` returns a `Collection<Object>` if data is just a `Map`. Once you make it generic, `keySet()` will return a `Collection<MyClass...
How do I use a foreach loop in Java to loop through the values in a HashMap?
[ "", "java", "foreach", "hashmap", "" ]
> **Possible Duplicate:** > [Escape string for use in Javascript regex](https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex) I have a msg like this: > **Max {0} chars allowed in {1}** And I have a function to create a message using the arguments passed as ``` for(var i = 0; i < a...
Your regexp is `/{0}/gi` since you create it from a string. And it is not a valid expression. You need to escape { in the regexp because it has a special meaning in the regexp syntax, so it should be: ``` new RegExp('\\{'+i+'\\}', 'gi'); ``` which is `/\\{0\\}/gi`. You need to *escape* the escaping `\\` in the string...
I would strongly encourage you to use the functional form of [String.replace()](https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/String/Replace) to solve your problem, rather than trying to parametrize the regexp in a for-loop that iterates over {0},{1},etc. In other words, rather than loo...
passing variable to a regexp in javascript
[ "", "javascript", "regex", "" ]
I have an annoying SQL statement that seem simple but it looks awfull. I want the sql to return a resultset with userdata ordered so that a certain user is the first row in the resultset if that users emailaddress is in the companies table. I have this SQL that returns what i want but i think it looks awful: ``` sele...
You could do something like this.. ``` select CASE WHEN exists (select email from companies c where c.Id = u.ID and c.Email = u.Email) THEN 1 ELSE 2 END as SortMeFirst, * From Users u where companyId = 1 order by SortMeFirst ```
will this work?: ``` select c.email, * from Users u LEFT JOIN companies c on u.email = c.email where companyid = 1 order by c.email desc -- order by case when c.email is null then 0 else 1 end ```
SQL UNION and ORDER BY
[ "", "sql", "sorting", "select", "union", "" ]
> **Possible Duplicate:** > [Which is faster/best? SELECT \* or SELECT column1, colum2, column3, etc](https://stackoverflow.com/questions/65512/which-is-faster-best-select-or-select-column1-colum2-column3-etc) > [What is the reason not to use select \*?](https://stackoverflow.com/questions/321299/what-is-the-reason...
If you need a subset of the columns, you are giving bad help to the optimizer (cannot choose for index, or cannot go only to index, ...) Some database can choose to retrieve data from indexes only. That thing is very very helpfull and give an incredible speedup. Running SELECT \* queries does not allow this trick. An...
Take a look at this post: [What is the reason not to use select \*?](https://stackoverflow.com/questions/321299/what-is-the-reason-not-to-use-select) and these: * [Performance benefit when SQL query is limited vs calling entire row](https://stackoverflow.com/questions/430605/performance-benefit-when-sql-query-is-lim...
Performance issue in using SELECT *?
[ "", "sql", "database", "performance", "" ]
Our code uses a lot of system properties eg, 'java.io.tmpdir', 'user.home', 'user.name' etc. We do not have any constants defined for these anywhere (and neither does java I think) or any other clever thing for dealing with them so they are in plain text littered throughout the code. ``` String tempFolderPath = System...
I would treat this just as any other String constant you have scattered throughout your code and define a constant variable for it. Granted, in this case "java.io.tmpdir" is unlikely to change, but you never know. (I don't mean that Sun might change the meaning of "java.io.tmpdir", or what system property it points to,...
[SystemUtils](http://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html?org/apache/commons/lang3/SystemUtils.html) provided by Apache Commons Lang package, solves this problem. SystemUtils has defined constant for most of the system properties, which can be obtained by a lookup, for example: ``` i...
Best Practice for Using Java System Properties
[ "", "java", "properties", "" ]
I have a few classes which do nothing except in their constructors/destructors. Here's an example ``` class BusyCursor { private: Cursor oldCursor_; public: BusyCursor() { oldCursor_ = CurrentCursor(); SetCursor(BUSY_CURSOR); } ~BusyCursor() { SetCursor(oldCursor_); ...
This technique is very common and is known as the design pattern: [Resource Acquisition Is Initialization (RAII)](http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization). I would not hesitate to use this design pattern at all. It's much better that you are coding using this design pattern because you wil...
As others have said, this is good C++ style. To aid readability, I always prefix such RAII-only classes with `Scoped` (for example, `ScopedBusyCursor`) to make it clear from a glance what the class's purpose is.
Good or Bad C++ Idiom - Objects used purely for constructor/destructor?
[ "", "c++", "idioms", "raii", "" ]
For my exception class i have a constructor that has multi arguments (...) which works fine under windows, how ever, under linux it compiles fine but refuses to link to it. Why does this not work under linux? here is an example: ``` class gcException { public: gcException() { //code here } g...
It compiles and links just fine. I expanded your test code to a full "program": ``` class gcException { public: gcException() { } gcException(int errId, const char* format, ...) { } }; int main() { new gcException(1, "foo", "bar", "baz"); } ``` And then `g++ -Wall test.cpp` ran without errors. Acc...
The problem is that your copy constructor doesn't accept the temporary that you give the throw. It's a temporary and thus an rvalue. A reference-to-nonconst, namely `gcException&` can't bind to it. Read [here](https://stackoverflow.com/questions/445570/when-cant-an-object-be-converted-to-a-reference#445591) on the deta...
Why doesnt Multi Args in constructor work under linux?
[ "", "c++", "linux", "variadic-functions", "" ]
What does the word "literal" mean when used in context such as literal strings and literal values? What is the difference between a literal value and a value?
A literal is "any notation for **representing** a value within source code" ([wikipedia](http://en.wikipedia.org/wiki/Literal)) (Contrast this with *identifiers*, which *refer* to a value in memory.) Examples: * `"hey"` (a string) * `false` (a boolean) * `3.14` (a real number) * `[1,2,3]` (a list of numbers) * `(x) ...
A literal is a value that has been hard-coded directly into your source. For example: ``` string x = "This is a literal"; int y = 2; // so is 2, but not y int z = y + 4; // y and z are not literals, but 4 is int a = 1 + 2; // 1 + 2 is not a literal (it is an expression), but 1 and 2 considered separately are literals...
What does the word "literal" mean?
[ "", "c#", "language-agnostic", "terminology", "glossary", "" ]
Does someone know an open source project or code snippets, which demonstrate how to create a google-chrome like interface with similar tabs and toolbar in Swing? I know, that I can use [JTabbedPane](http://java.sun.com/javase/6/docs/api/javax/swing/JTabbedPane.html), but I'm thinking of an interface which looks and fe...
I have just created my own open-source library for this, called Jhrome. Check it out! It's available on github: <https://github.com/jedwards1211/Jhrome> Documentation is sparse right now, but it's pretty solid, except for AWT/Swing memory leaks I haven't figured out yet. If enough people are interested in it I'll pol...
You can probably pull it off with an undecorated JFrame (setUndecorated(true)) to get rid of the title bar. You'd then create a layout with a tabbed pane filling the window and then overlay the min/max/close buttons on the top right. If tabbed pane is too inflexible, you will need to put a button bar across the top, ...
How to build a Google-chrome tabs and menubar interface in Java Swing?
[ "", "java", "user-interface", "swing", "open-source", "google-chrome", "" ]
I have a horizontal css menu with 5 items. e.g 1) Home 2) Users 3) Category 4) Products 5) Contact When "home" is selected the background color (via css) of the entire menu div (id="topmenu") is blue. I want the background color of the div to change to say green when "users" is selected and say purple when "category...
``` <div id="topmenu"> <ul> <li><a href="home" onclick="changeBackground('green');">Home</a></li> <li><a href="users" onclick="changeBackground('blue');">Users</a></li> <li><a href="home" onclick="changeBackground('purple');">Category</a></li> <li><a href="home" onclick="changeBackground('brown');">Products</a></li> <l...
You can set up multiple classes like so: ``` <ul> <li class="Menu1 Selected"><a href="#">Home</a></li> <li class="Menu2"><a href="#">Users</a></li> </ul> ``` Then in your CSS you have a class set for each menu item for it's selected state: ``` .Menu1 .Selected { background-color: #000000; } .Menu2 .Select...
Change background color of menu based on menu selection
[ "", "asp.net", "javascript", "css", "" ]
Actually I am trying to move some box alternatively with in another box. I made it work, but both the blocks do not interrupt each other. What should I do? How can I make the blocks cross each other? I try using style:position, but it is not working. Here is the code I have been using: ``` <marquee direction="down" b...
Oh, dear Lord! Well. They don't cross because they're positioned statically one above the other. The second marquee cannot go above the first. You can solve\* this problem by ungluing the marquees from each other using absolute positioning. Then doubly-nest each one with different horizontal and vertical motion: ```...
Please don't use the marquee tag, it's non-standard and deprecated. Use some JavaScript library like [jQuery UI](http://ui.jquery.com) for any kind of animation.
Nested and multiple <marquee> troubles
[ "", "javascript", "html", "marquee", "" ]
We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it. This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout. Our inventory management system runs off a server in the office, while the three websit...
One possibility would be to expose a web service interface on your inventory management system that allows the transactions used by the web shopfront to be accessed remotely. With a reasonably secure VPN link or ssh tunnel type arrangement, the web shopfront could get stock levels, place orders or execute searches agai...
I don't see the problem... You have an application running on one server that manages your database locally. There's no reason a remote server can't also talk to that database. Of course, if you don't have a database and are instead using a homegrown app to act as some sort of faux-database, I recommend that you refac...
Inventory Control Across Multiple Servers .. Ideas?
[ "", "python", "tracking", "inventory", "" ]
### The Question What is the correct way to install Python 3.0 alongside Python 2.x using Cygwin? ### Notes I already have a working copy of Cygwin, and Python 2.x is installed within Cygwin (`/lib/python2.x`, not `c:\python2.x`). Also, I would like to be able to call python 3 separately (and only intentionally) by...
The standard `make install` target of the Python 3.0 sources doesn't install a python binary. Instead, make install prints at the end ``` * Note: not installed as 'python'. * Use 'make fullinstall' to install as 'python'. * However, 'make fullinstall' is discouraged, * as it will clobber your Python 2.x installation. ...
As of yesterday (Wed 25 July 2012), [Python 3.2.3 is included in the standard Cygwin installer](http://cygwin.com/ml/cygwin/2012-07/msg00553.html). Just run Cygwin's `setup.exe` again (download it from [cygwin.com](http://www.cygwin.com) again if you need to), and you should be able to select and install it like any ot...
Installing Python 3.0 on Cygwin
[ "", "python", "windows", "cygwin", "" ]
I've never been sure that I understand the difference between str/unicode decode and encode. I know that `str().decode()` is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string. I know that `unicode().encode()` converts unicode c...
The `decode` method of unicode strings really doesn't have any applications at all (unless you have some non-text data in a unicode string for some reason -- see below). It is mainly there for historical reasons, i think. In Python 3 it is completely gone. `unicode().decode()` will perform an implicit *encoding* of `s...
To represent a unicode string as a string of bytes is known as **encoding**. Use `u'...'.encode(encoding)`. Example: ``` >>> u'æøå'.encode('utf8') '\xc3\x83\xc2\xa6\xc3\x83\xc2\xb8\xc3\x83\xc2\xa5' >>> u'æøå'.encode('latin1') '\xc3\xa6\xc3\xb8\xc3\xa5' >>> u'æøå'.encode('ascii') UnicodeEncodeE...
What is the difference between encode/decode?
[ "", "python", "string", "unicode", "character-encoding", "python-2.x", "" ]
I have a control which I have to make large modifications to. I'd like to completely prevent it from redrawing while I do that - SuspendLayout and ResumeLayout aren't enough. How do I suspend painting for a control and its children?
At my previous job, we struggled with getting our rich UI app to paint instantly and smoothly. We were using standard .Net controls, custom controls and devexpress controls. After a lot of googling and reflector usage, I came across the WM\_SETREDRAW win32 message. This really stops controls drawing whilst you update ...
The following is the same solution of ng5000 but doesn't use P/Invoke. ``` public static class SuspendUpdate { private const int WM_SETREDRAW = 0x000B; public static void Suspend(Control control) { Message msgSuspendUpdate = Message.Create(control.Handle, WM_SETREDRAW, IntPtr.Zero, Int...
How do I suspend painting for a control and its children?
[ "", "c#", ".net", "winforms", "paint", "" ]
code snippet: ``` //byte[] myByteArray = byte array from database (database BLOB) myByteArray = (byte[]) ((dbCommand.Parameters["parameter"].Value)); string myString =System.Text.Encoding.UTF8.GetString(myByteArray); Xmldocument doc = new Xmldocument(); doc.Load(myString); ``` ============ I am getting `System.Ou...
If you've got a string containing XML text, you actually want [XmlDocument.LoadXML](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.loadxml.aspx). XmlDocument.Load treats the string as a URL. That said, [XmlDocument.Load](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.load.aspx) has over...
XmlDocument.Load(String) tries to load the XML document from the URL given as parameter, i.e. it tries to interpret your possibly HUGE string as an URL. No wonder that something goes wrong. Use LoadXml() instead.
getting 'System.OutOfMemoryException' when converting byte array to string
[ "", "c#", ".net", "optimization", "" ]
I'm working with Quickbook's IIF file format and I need to write a parser to read and write IIF files and I'm running into some issues reading the files. The files are simple, they're tab deliminated. Every line is either a table definition or a row. Definitions begin with'!' and the table name, and rows begin with ju...
I did it: ``` public DataSet parseIIF(Stream file) { iifSet = new DataSet(); String fileText; using (StreamReader sr = new StreamReader(file)) { fileText = sr.ReadToEnd(); } //replace line breaks with tabs //fileText.Replace('\n'...
It has been a while since I have done IIF but unless they have fixed it QuickBooks will barf on those line breaks anyway. It seems [these folks](http://getmytime.com/faq.asp#atq7) have the same issue and they handled it with spaces. Personally I would lean toward pipes or something that will clearly delineate the line...
Parsing a Quickbook IIF format file
[ "", "c#", "parsing", "io", "text-parsing", "fileparsing", "" ]
I am an ActiveMQ / Camel noob with a specific scenario in mind, I wonder firstly if it is possible and secondly whether someone might provide a little direction. Basically I need to perform dynamic throttling off the queue. I.E the ability to set **at runtime** the rate a particular group of messages will be consumed ...
Yeah looks like you are looking for broker side throtteling to avoid consumers to block. Have you raised your request at the ActiveMQ user/dev forum?
You could just use Camel's existing [throttler](http://activemq.apache.org/camel/throttler.html) then using a different queue for each type of messages where you need to configure a different throttle rate? e.g. ``` from("activemq:Queue1.Input"). throttle(20). to("activemq:Queue1.Output"); from("activemq:Qu...
Dynamic throttling of an ActiveMQ message queue with Camel
[ "", "java", "jms", "activemq-classic", "apache-camel", "" ]
Do any of the IDEs (or any other tool for that matter) have the ability to generate a POM based on an existing project? --- I ended up generating the POM with a Maven archetype as [Peter](https://stackoverflow.com/users/57695/peter-lawrey) and [Sal](https://stackoverflow.com/users/13753/sal) suggested and then moving...
You can do this in IntelliJ, but the POM it generates may be more complex than if you write by hand. If your project is currently in JBuilder or Eclipse you can import this first. Instead I would suggest you describe your project in a POM and use it to generate your project information. You can do this for eclipse and...
One way to do this it to create a template project via maven archetype then move your existing code to the template. I would recommend this only for really simple projects. It would work something like this. ``` mvn archetype:generate mv src/* src/main/java mv test/* src/test/java mvn package ``` You'll get errors. ...
Generating a Maven POM from an existing project?
[ "", "java", "maven-2", "ide", "" ]
Well I was reading this [post](http://handyfloss.wordpress.com/2008/02/17/summary-of-my-python-optimization-adventures/) and then I came across a code which was: ``` jokes=range(1000000) domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)] ``` I thought wouldn't it be better to calculate the value of len(jo...
You're not using [`timeit`](http://docs.python.org/library/timeit.html) correctly: the argument to `-s` (setup) is a statement to be executed once initially, so you're really just testing an empty statement. You want to do ``` $ python -m timeit -s "jokes=range(1000000)" "domain=[(0,(len(jokes)*2)-i-1) for i in range(...
Read this: [Python Speed / Performance Tips](http://wiki.python.org/moin/PythonSpeed/PerformanceTips) Also, in your example, the total time is so short that the margin of error will outweigh any actual difference in speed.
Optimization in Python - do's, don'ts and rules of thumb
[ "", "python", "optimization", "" ]
The SQL Server (2000/2005) function gets the table name and the field name as parameters and returns results from a dynamic query within the function. The results should be assigned to a `Table` variable which will be used further in a stored procedure. How to achieve this? I am getting error: "Only functions and exte...
I'm not sure how this works with functions, but if you have a Stored Procedure that returns a resultset, you can insert that into a table variable using INSERT EXEC statements. ``` INSERT @TableVariable EXEC spYourProcedure ``` As long as the fields match that will work. Otherwise you can use: ``` INSERT @TableVaria...
just to close the loop... here is the syntax for calling the function and putting those results in a table variable small build on @simons solution this ran on sql2012 and sql2014. [ dont forget to close off the table statement. Easy enough to do if you have the table all on a single line. ] ``` declare @t table(f...
Assign function result to a table variable
[ "", "sql", "stored-procedures", "dynamic-queries", "" ]
I'm using Visual Studio 2008 to write an installation, and I'm a completely new to installations. I've created an installation and successfully written some custom actions using a C# assembly. One action sets a RunOnce registry value, and now I need to prompt the user to reboot when the installation finishes, but I hav...
Thanks. I ended up using a post-build event to run a batch file with the following command. The hard part was tracking down WiRunSQL.vbs, which was in the ["Windows SDK Components for Windows Installer Developers"](http://msdn.microsoft.com/en-us/library/aa370834(VS.85).aspx) download. ``` cscript "C:\Program Files\Mi...
If you are implementing your installer using [WiX](http://en.wikipedia.org/wiki/WiX), you need to add this: ``` <ScheduleReboot After="InstallFinalize"/> ``` If you're using the cut-down "Installer" project in [Visual Studio](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio), I'm not sure... But this link [here](...
How can I prompt the user to reboot in a .NET installation?
[ "", "c#", ".net", "installation", "windows-installer", "" ]
I have a C++/MFC app on windows - dynamically linked it's only 60kb static it's > 3Mb. It is a being distributed to customers by email and so needs to be as small as possible. It statically links the MFC and MSCVRT libraries - because it is a fix to some problems and I don't want more support calls about missing lib...
You can't mix the CRT/MFC dlls. Going from memory... As the other answer suggested, you can #define WIN32\_LEAN\_AND\_MEAN and VC\_EXTRALEAN. These probably won't help though. They tend to be about minimizing build time - not the final exe size. Short of rebuilding MFC (Which is an option - you could rebuild it /Os, ...
For programs using the CRT, you can use the technique in [this video by Per Vognsen](https://www.youtube.com/watch?v=5tg_TbURMy0) on achieving 3.5KB executables. `Windows\System32\msvcrt.dll` ships with every Windows since 95, so by linking to that, you needn't package the Visual C++ Redistributable with your app. The...
Reduce windows executable size
[ "", "c++", "windows", "dll", "mfc", "linker", "" ]
I need to generate many internal client-side (within the company only) graphs from streams of data, and since the data itself is "secret", I can't use a service like Google-Graphs for generating the graphs. So I was wondering if anyone has some recomendations for a javascript graph library that doesn't require a server...
Have a look at [flot](http://code.google.com/p/flot/) a javascript plotting library. **EDIT** The official flot repo [lives on github](https://github.com/flot/flot)
Have a look at [Raphael](http://raphaeljs.com/) ([github](https://github.com/DmitryBaranovskiy/raphael/tree)).
is there a client side (javascript) graph library that doesn't require a server?
[ "", "javascript", "graph", "client-side", "" ]
I have seen code around with these two styles , I am not not sure if one is better than another (is it just a matter of style)? Do you have any recommendations of why you would choose one over another. ``` // Example1 class Test { private: static const char* const str; }; const char* const Test::str = "my...
Usually you should prefer `std::string` over plain char pointers. Here, however, the char pointer initialized with the string literal has a significant benefit. There are two initializations for static data. The one is called static initialization, and the other is called dynamic initialization. For those objects that...
Hmmm, a std::string is not the same as a const char \*. I usually err on the side of using std::string because it is a class that has many additional capabilities that make it much easier to use. If performance is paramount and you are using const char \* for efficiency, go that way.
Should I use std::string or const char* for string constants?
[ "", "c++", "constants", "static-members", "stdstring", "" ]
I have this Javascript data: ``` [{id:123,type:"test"},{id:154,type:"another"}] ``` How would you transform that into something so that I can pass it as a HTTP post request? ``` menu[0][id] = 123 menu[0][type] = test menu[1][id] = 154 menu[1][type] = another ``` I dont want to pass the actual JSON data, I want to c...
``` var data = [{id:123,type:"test"},{id:154,type:"another"}]; var params = new Array(); for(var x = 0; x < data.length; x++) { params.push("id=[" + x + "]=" + escape(data[x].id)); params.push("type=[" + x + "]=" + escape(data[x].type)); } alert(params.join("&")); // output: id=[0]=123&type=[0]=test&id=[1]=154&...
``` "?qsparam=" + escape("[{id:123,type:'test'},{id:154,type:'another'},...]") ```
Represent a query string in JSON
[ "", "javascript", "json", "query-string", "" ]
When comparing two strings in c# for equality, what is the difference between InvariantCulture and Ordinal comparison?
## InvariantCulture Uses a "standard" set of character orderings (a,b,c, ... etc.). This is in contrast to some specific locales, which may sort characters in different orders ('a-with-acute' may be before ***or*** after 'a', depending on the locale, and so on). ## Ordinal On the other hand, looks purely at the valu...
It does matter, for example - there is a thing called character expansion ``` var s1 = "Strasse"; var s2 = "Straße"; s1.Equals(s2, StringComparison.Ordinal); //false s1.Equals(s2, StringComparison.InvariantCulture); //true ``` With `InvariantCulture` the ß character gets expanded to ss.
Difference between InvariantCulture and Ordinal string comparison
[ "", "c#", ".net", "string-comparison", "ordinal", "" ]
A static function `retUnique()` returns a unique value. My question is that if there are many users who are using the same function at a given point of time, what happens? Is there a best practice to make sure that each users accessing this static function simultaneously get a unique value and also do not face threadin...
Assuming you want to simply return a unique incrementing integer value, the simplest safe approach is probably to use a private static counter and a private static lock object. Something like: ``` private static int s_UniqueCounter; // starts at 0 by default private static readonly object s_UniqueCounterLock = new obj...
There is nothing special about static functions that make them more or less safe to use on multiple threads. Instead, you need to examine the data which the function accesses and modifies, and make sure that it still respects the integrity of that data when called concurrently. Here's an example that might be relevant...
Is there a best practice to implement static function that gives unique value on simultaneous access
[ "", "c#", "multithreading", "" ]
I'm going through some old stored procedures at work and constantly come across ``` CASE MyColumn WHEN 'Y' THEN 'Yes' WHEN 'N' THEN 'No' ELSE 'Unknown' END ``` It gets even worse when this is tied not to a word, but instead a colour. ``` CASE MyColumn WHEN 'Y' THEN 'style="background-color:pink"' ELSE '' END ``` Th...
When speed is of the essence, the SQL case statements might even be the fastest (I'll run a test) but for maintainability, returning the plain values to the presentation layer (or some business layer thingy) is the best option. [update] ran some quick and dirty tests (code below) and found the C# code variant slightly...
I would be concerned putting this kind of logic in SQL statements. What happens if your database engine changes? Will you have to update every SQL statement to Oracle SQL? What if the repository itself changes, when you move to a message bus, XML files, or web service call... It looks like you're storing display infor...
SQL CASE Statement Versus Conditional Statements In Programming Language
[ "", "sql", "language-agnostic", "" ]
jQuery and JavaScript in general are new ground for me. What are some good resources to get me up and running. I am particularly interested in page manipulation - eg moving elements about programmatically.
Well, [docs.jquery.com](http://docs.jquery.com/) would be a good start (especially the [Manipulation](http://docs.jquery.com/Manipulation) section). Usually lots of good examples as well as the documentation. I picked up [jQuery in Action](http://www.manning.com/bibeault/) which was well-worth a read.
[Visual jQuery](http://visualjquery.com/) is a more pleasant way of browsing the jQuery documentation...
What are good resources for getting started with jQuery?
[ "", "javascript", "jquery", "resources", "" ]
Does Java and/or Spring have the concept of properties? I have bunch of domain models, each of which has several properties. Example: ``` public class Person { private String name; private Date dateOfBirth; private float height; private float weight; // getters and setters not shown } ``` When dis...
If I understand you correctly, you want to be able to put the format and description of some of these properties in an external file. You might want to take a look at Spring's [`MessageSource`](http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#context-functionality-messagesource) (link to [javado...
To do this using JSP and JSTL, you can use the "fmt" tag library which supports localization and formatting for numbers, dates, etc. In the example you posted, the code would be something like this: ``` <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <%-- ..assuming bundle and locale are already set....
Java web application properties
[ "", "java", "spring", "jakarta-ee", "properties", "jstl", "" ]
My current application has a JFrame with about 15 actions stored as fields within the JFrame. Each of the actions is an anonymous class and some of them are pretty long. Is it common to break actions into their own classes possibly within a sub-package called actions? If not, how's this complexity usually tamed? Tha...
If it is possible that your actions could be reusable (e.g., from keyboard shortcuts, other menus, other dialogs, etc.) and especially if they can work directly on the underlying model (rather than on the UI), then it is generally better not to have them as anonymous classes. Rather, create a separate package, and cre...
That's typically how I do it. Each action gets it's own class which has a reference to the "app" object so it can get to resources it needs. I usually have an action manager that holds all the actions so there's one place to access them as well as one place to update their enablement and stuff. Eventually this also be...
Organizing Actions in a Swing Application?
[ "", "java", "swing", "code-organization", "" ]
This is for an arrivals/departures flight display. The display is difficult to read because of blurry fonts. The current state is an asp.net page displayed using internet explorer on a HDTV. From the software side, what can I do to produce good looking fonts? I've noticed that powerpoint presentations have nicely rend...
> The current hardware setup is a vga output to hardware to convert to component video and a long cable run to a hdtv. One more thing: as a rule, component video comes in several predefined resolutions, namely: 720x576 (576p), 1280x720 (720p) and 1920x1080 (1080p). It seems that your `VGA -> YPrPb` hardware rescales ...
Use [ClearType](http://blogs.msdn.com/ie/archive/2006/02/03/524367.aspx). If it's an `LCD` connected with `DVI` or `VGA`, set it to the native resolution.
How to get the best font clarity to display on an HDTV with c#?
[ "", "c#", "asp.net", "" ]
We have a user provided string that may contain unicode characters, and we want the robot to type that string. How do you convert a string into keyCodes that the robot will use? How do you do it so it is also java version independant (1.3 -> 1.6)? What we have working for "ascii" chars is ``` //char c = nextChar()...
Based on javamonkey79's code I've created the following snippet which should work for all Unicode values... ``` public static void pressUnicode(Robot r, int key_code) { r.keyPress(KeyEvent.VK_ALT); for(int i = 3; i >= 0; --i) { // extracts a single decade of the key-code and adds // an off...
The [KeyEvent Class](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/event/KeyEvent.html) does not have direct mappings for many unicode classes in JRE 1.5. If you are running this on a Windows box what you may have to do is write a custom handler that does something like this: ``` Robot robot = new Robot(); char cur...
How to make the Java.awt.Robot type unicode characters? (Is it possible?)
[ "", "java", "unicode", "automation", "" ]
I`m writing client-server app for windows using WinSock and I have class for server. while initialising server I have such code: ``` class Server { static const int MaxClients = 10; std::vector connections; CRITICAL_SECTION cs; int port; SOCKET ServerSocket; sockaddr_in ServerAddress; voi...
It depends on whether you're actually going to *handle* the exception, e.g. retry with a slightly different input, or decide to ignore the problem and proceed anyway (rarely appropriate, but *can* be useful). In this case, you may well want to catch the exception close to its source. In most cases, the only thing you ...
The basic rule is that you only catch exceptions in that part of the code, where you can actually *handle* it. By handling it I mean that you can take some action based upon the exception thrown, for instance trying to create the socket another time, or trying to use a different configuration. Additionally, exceptions...
How to decide where to handle an exception - in scope of function it been thrown or in global one?
[ "", "c++", "exception", "" ]
I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input: `http://google.com/resource?key=value1 & value2` I expect the output: `http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value...
Jersey's [UriBuilder](http://download.oracle.com/javaee/6/api/javax/ws/rs/core/UriBuilder.html) encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc > Builder methods perform contextual encoding of characters not permitted in the corresponding URI component fo...
You could also use Spring's [UriUtils](http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/util/UriUtils.html)
How do I encode URI parameter values?
[ "", "java", "url", "rest", "urlencode", "rfc2396", "" ]
I'm trying to migrate a MySQL-based app over to Microsoft SQL Server 2005 (not by choice, but that's life). In the original app, we used *almost* entirely ANSI-SQL compliant statements, with one significant exception -- we used MySQL's `group_concat` function fairly frequently. `group_concat`, by the way, does this: ...
No REAL easy way to do this. Lots of ideas out there, though. [Best one I've found](http://blog.shlomoid.com/2008/11/emulating-mysqls-groupconcat-function.html): ``` SELECT table_name, LEFT(column_names , LEN(column_names )-1) AS column_names FROM information_schema.columns AS extern CROSS APPLY ( SELECT column_n...
I may be a bit late to the party but this [STUFF()](https://learn.microsoft.com/en-us/sql/t-sql/functions/stuff-transact-sql?view=sql-server-ver16) + [FOR XML](https://learn.microsoft.com/en-us/sql/relational-databases/xml/for-xml-sql-server?view=sql-server-ver16) method works for me and is easier than the COALESCE met...
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
[ "", "sql", "sql-server", "sql-server-2005", "string-aggregation", "" ]
I'm trying to read the target file/directory of a shortcut (`.lnk`) file from Python. Is there a headache-free way to do it? The spec is way over my head. I don't mind using Windows-only APIs. My ultimate goal is to find the `"(My) Videos"` folder on Windows XP and Vista. On XP, by default, it's at `%HOMEPATH%\My Docu...
**Create a shortcut using Python (via WSH)** ``` import sys import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut("t:\\test.lnk") shortcut.Targetpath = "t:\\ftemp" shortcut.save() ``` **Read the Target of a Shortcut using Python (via WSH)** ``` import sys import w...
I know this is an older thread but I feel that there isn't much information on the method that uses the link specification as noted in the original question. My shortcut target implementation could not use the win32com module and after a lot of searching, decided to come up with my own. Nothing else seemed to accompli...
Reading the target of a .lnk file in Python?
[ "", "python", "directory", "shortcut", "target", "lnk", "" ]
> **Possible Duplicate:** > [How do I find out which DOM element has the focus?](https://stackoverflow.com/questions/497094/how-do-i-find-out-which-dom-element-has-the-focus) Is there a way in javascript to determine which html page element has focus?
**Use the [`document.activeElement`](https://developer.mozilla.org/en-US/docs/DOM/document.activeElement#Browser_compatibility) property.** The `document.activeElement` property is supported on Chrome 2+, Firefox 3+, IE4+, Opera 9.6+ and Safari 4+. Note that this property will only contain elements that accept keystr...
Check out [this blog post](http://ajaxandxml.blogspot.com/2007/11/emulating-activeelement-property-with.html). It gives a workaround so that `document.activeElement` works in all browsers. ``` function _dom_trackActiveElement(evt) { if (evt && evt.target) { document.activeElement = evt.target == document ...
How to determine which html page element has focus?
[ "", "javascript", "html", "" ]
Could anyone point me to an example implementation of a HOT Queue or give some pointers on how to approach implementing one?
[Here is a page](http://www.lonesock.net/misc.html) I found that provides at least a clue toward what data structures you might use to implement this. Scroll down to the section called "Making A\* Scalable." It's unfortunate that the academic papers on the subject mention having written C++ code but don't provide any.
Here is the link to the paper describing HOT queues. It's very abstract, that's why i wanted to see a coded example (I'm still trying to fin my way around it). <http://www.star-lab.com/goldberg/pub/neci-tr-97-104.ps> The "cheapest", sort to speak variant of this is a two-level heap queue (maybe this sounds more famili...
HOT(Heap On Top) Queues
[ "", "c++", "" ]
This is a bit of an open question but I would really like to hear people opinions. I rarely make use of explicitly declared temporary tables (either table variables or regular #tmp tables) as I believe not doing so leads to more concise, readable and debuggable T-SQL. I also think that SQL can do a better job than I o...
Temporary tables are most useful for a complex batch process like a report or ETL job. Generally you would expect to use them fairly rarely in a transactional application. If you're doing complex query with a join involving multiple large tables (perhaps for a report) the query optimiser may not actually be able to op...
It really depends on what you are doing. I generally try to avoid them, but sometimes you need to do something complicated that takes multiple steps. Generally this is way beyond the simple select from table stuff. Like anything else it's a tool that you have to know when to use. I would agree with you that I normally...
Temporary Table Usage in SQL Server
[ "", "sql", "sql-server", "t-sql", "star-schema", "" ]
I have the following code in my index view. ``` latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10] for entry in latest_entry_list: entry.views = entry.views + 1 entry.save() ``` If there are ten (the limit) rows returned from the initial query, will the save issue 10 ...
You can use `F()` objects for this. Here is how you import `F`: `from django.db.models import F` **[New in Django 1.1](http://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once).** Calls to update can also use F() objects to update one field based on the value of another field in the...
You could handle the updates in a single transaction, which could improve performance significantly. Use a separate function, decorated with @transaction.commit\_manually. ``` @transaction.commit_manually def update_latest_entries(latest_entry_list): for entry in latest_entry_list: entry.views += 1 ...
Django: Increment blog entry view count by one. Is this efficient?
[ "", "python", "database", "django", "performance", "" ]
For my work I need to create a Autorun application for a CD for our client. The problem is all I'm a C# programmer by trade and .NET does not make for the best autoruns since not all computers will have .NET installed on them. What is a good solution that will work on Win98-Vista computers?
The answer to this question is really one of preference. Technically, anything can be instructed to open as an autorun. The autorun.inf file is simply an instruction file that Windows knows how to read in order to determine what it should do when a CD is inserted. That could be an application (written in any language y...
There are many small autorun-utils (some free) that are configurable. I would go for one of those. <http://www.ezau.com/latest/articles/083.shtml>
Best solution for making an Autorun application?
[ "", "c#", ".net", "windows", "windows-vista", "autorun", "" ]
[This article](http://www.sitepoint.com/article/php-security-blunders/) states that > If your site is run on a shared Web > server, be aware that any session > variables can easily be viewed by any > other users on the same server. On a larger host like GoDaddy, **are there really no protections in place against this...
It is ridiculously easy because by default [`php.ini#session.save_path`](https://www.php.net/manual/en/session.configuration.php#ini.session.save-path) points to `/tmp` on Linux installs and similar for Windows. This is bad because most users have read and write privileges to `/tmp` because they need them. You can prot...
The session files by default are stored in the location given by the [session.save\_path](http://php.net/manual/en/session.configuration.php#ini.session.save-path) in php.ini. While this can be defined separately for each vhost, the files have to be readable by the httpd process, and so if you know the location, your s...
How Easy Is It to Hijack Session Vars on GoDaddy (PHP)
[ "", "php", "security", "session-hijacking", "" ]
In JavaScript, I know that a closure is can be defined as a nested function that has access to its containing function's variables. For example: ``` function outerFunction(x, y) { function innerFunction() { return x + y + 10; } return innerFunction; } ``` Now, the following code is wiring up a cal...
Yes, you are correct in assuming that it is a closure by definition. It sounds like you know your stuff but [here is a good, extensive article on javascript closures](http://www.jibbering.com/faq/faq_notes/closures.html).
I wholeheartedly agree that too many inline closure functions don't enhance readability. On the other hand I strongly dislike the `var self = this` style of writing closures, to which `this` is just a variant, as it's still too verbose in its declaration, and you introduce your own new 'keyword' whether that is `this` ...
Based on how they are constructed, can callbacks also be defined as closures?
[ "", "javascript", "closures", "callback", "" ]
I have a few remote SQL servers that I need to pull a large amount of data from regularly (say 5,000,000 rows per server). This data also needs to be formatted and FTPed to another server. The dial-up portion is fine, I can connect and communicate with the server, but sometimes the connection is slow, maybe only 19Kbps...
What I ended up doing was creating a small app in C (a few of these are WINNT and that was the easiest way, it also allows other to retrieve the data manually if necessary without the ability to alter the source) that takes a few arguments to build the query I need. It then runs the query and dumps the results in the r...
If it is an option, zip it up, ftp and do the bulk insert on your side.
What is the best way to bulk copying SQL data over a dial-up connection?
[ "", "c#", "sql-server", "ras", "" ]
I am wondering what type the 'value' keyword in a property takes. so: ``` public class Test { string _numberAsString; int _number = -1; public Test() {} public string NumberAsString { get { return _numberAsString; } set { _numberAsString= value; } } public int Number ...
Yes, the type of 'value' is determined by the return type of the property. What exactly are you trying to accomplish? Do you want to be able to set either Number or NumberAsString to a valid value and get a result back out from either property? If that's the case you need to do something like this: ``` public class T...
The type of the value in the setter is the type of the property - you cannot pass a string to a property that is an int, this must first be parsed to an int. Strings in .net cannot be coerced into any other type (in the way perl, awk and many other dynamic languages allow) they can only be treated as string, or as the...
What is the type of the 'value' reserved word in C# properties
[ "", "c#", "properties", "types", "keyword", "" ]
Basically the app writes the contents of a Collection to XML. I'm using XMLStreamWriter (`XMLOutputFactory.newInstance().createXMLStreamWriter(...)`) for this purpose. Works great except for the fact that I can't get how to append data to an existing file. Don't really like the idea of reading all of it first, appendi...
If you're appending a top-level element, you can probably get away with doing what you want. e.g., If you have this file: ``` <some_element> <nested_element> ... </nested_element> </some_element> ``` you can most likely get away with appending another `some_element` element. However, you're obviously screwed...
Simply appending to an XML file will result in malformed XML. You should build the DOM and attach what new elements you need.
Appending to XML with XMLStreamWriter
[ "", "java", "xml", "" ]
Is it possible to have something like the following: ``` class C { public Foo Foos[int i] { ... } public Bar Bars[int i] { ... } } ``` If not, then are what are some of the ways I can achieve this? I know I could make functions called getFoo(int i) and getBar(int i) but I was ...
Not in C#, no. However, you can always return collections from properties, as follows: ``` public IList<Foo> Foos { get { return ...; } } public IList<Bar> Bars { get { return ...; } } ``` IList<T> has an indexer, so you can write the following: ``` C whatever = new C(); Foo myFoo = whatever.Foos[13]; ``` ...
This from C# 3.0 spec "Overloading of indexers permits a class, struct, or interface to declare multiple indexers, provided their signatures are unique within that class, struct, or interface." ``` public class MultiIndexer : List<string> { public string this[int i] { get{ return this[i]...
C# Multiple Indexers
[ "", "c#", "properties", "indexer", "" ]
I'm writing an application that gets data from URLs, but I want to make it an option whether or not the user uses "clean" urls (ex: <http://example.com/hello/world>) or "dirty" urls (ex: <http://example.com/?action=hello&sub=world>). What would be the best way to get variables form both URL schemes?
If your mod\_rewrite has a rule like the following: ``` RewriteRule ^hello/world /?action=hello&sub=world [NC,L] ``` or, the more generalised: ``` // Assuming only lowercase letters in action & sub.. RewriteRule ^([a-z]+)/([a-z]+) /?action=$1&sub=$2 [NC,L] ``` then the same PHP script is being called, with the `$_R...
If you're application is running in Apache server, I would recommend the use of mod\_rewrite. Basically, you code your application to use "dirty" URLs inside. What I mean by this is that you can still use the "clean" URLs in the templates and such, but you use the "dirty" version when parsing the URL. Like, you're rea...
Best way to get data from "clean" and "dirty" URLs
[ "", "php", "" ]
How do you get the proper index of a selected input from a set of input elements with irregularly numbered indexes using JQuery? JQuery's "index" function always returns a value starting from 0 instead of the indexes I used. My code is below: JQuery: ``` $("input[name^=myboxes]").click(function() { var elemen...
The value of your ID does not have an "index" property. It's just a string. One suggestion: parse the id string to get your value: ``` $("input[name^=myboxes]").click(function() { var element_id = $(this).attr('id'); //the initial starting point of the substring is based on "myboxes[" var ix = element_id....
The following is what has always worked for me. JQuery: ``` $("input[name^=myboxes]").click(function() { var element_id = $(this).attr("meta:index"); alert(element_id); }); ``` HTML: ``` <input type="checkbox" id="myboxes[3]" name="myboxes[3]" meta:index="3" value="CHECKED" > <input type="checkbox"...
Getting correct index from input array in JQuery
[ "", "javascript", "jquery", "html", "" ]
I've created a custom thread pool utility, but there seems to be a problem that I cannot find. ``` using System; using System.Collections; using System.Collections.Generic; using System.Threading; namespace iWallpaper.S3Uploader { public class QueueManager<T> { private readonly Queue queue = Queue.Synchronized(ne...
Writing robust threaded code is not trivial. There are numerous thread-pools around that you might look at for reference, but also note that Parallel Extensions (available as [CTP](http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3&displaylang=en), or later in .NET 4.0) includ...
I looked through your code and here are a couple of issues I saw. 1. You lock the queue object even though it is synchronized queue. This is unnecessary 2. You inconsistently lock the queue object. It should either be locked for every access or not locked and depending on the Synchronized behavior. 3. The Proceed meth...
What is wrong with my custom thread pool?
[ "", "c#", ".net", "multithreading", "lambda", "" ]
Example ``` int *ptr; *ptr = 1000; ``` can I catch memory access violation exception using standard C++ without using any microsoft specific.
Nope. C++ does not throw an exception when you do something bad, that would incur a performance hit. Things like access violations or division by zero errors are more like "machine" exceptions, rather than language-level things that you can catch.
Read it and weep! I figured it out. If you don't throw from the handler, the handler will just continue and so will the exception. The magic happens when you throw you own exception and handle that. ``` #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <tchar.h> void SignalHand...
Catching access violation exceptions?
[ "", "c++", "exception", "" ]
I found this statement is some old code and it took me a second to figure out... ``` IsTestActive = (TestStateID == 1 ? true : false); ``` Please correct me if I'm wrong but isn't this the same as this one?: ``` IsTestActive = (TestStateID == 1); ``` If it is, why would you ever want to use the first? Which one is ...
Yes, it is exactly the same. Yes, the latter is more readable.
``` IsTestActive = (TestStateID == 1); ``` is definitely more readable. You *could* make a case for defining a constant ``` ACTIVE = 1 ``` then replacing the boolean variable `IsTestActive` with ``` (TestStateID == ACTIVE) ``` The way the code is now, the state of the boolean `IsTestActive` will be erroneous if t...
Setting a boolean value based on an integer
[ "", "c#", "coding-style", "readability", "" ]
I have an application written in VB.NET that interacts with Excel via interop. I eventually ran into the known issue of Cell-edit mode (see [MSDN](http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=4087801&SiteID=1) and [stackoverflow](https://stackoverflow.com/questions/221984/how-to-tell-if-excel-application-is-in...
As a quick-and-dirty fix i used the following code as an alternative ``` Private Function isEditMode() As Boolean isEditMode = False Try oExcel.GoTo("###") Catch Ex As Exception ' Either returns "Reference is not valid." ' or "Exception from HRESULT: 0x800A03EC" If ex.Message....
An older post but not an old problem. The solution above for detect and exit is fine but I found another solution for getting Excel out of edit mode which doesn't need to use an API to find the window or use Sendkeys to click a cell, my solution uses events. Excel can even be in edit mode and minimised and this solutio...
Workaround to see if Excel is in cell-edit mode in .NET
[ "", "c#", "vb.net", "excel", "interop", "excel-interop", "" ]
A "non-believer" of C# was asking me what the purpose to extension methods was. I explained that you could then add new methods to objects that were already defined, especially when you don't own/control the source to the original object. He brought up "Why not just add a method to your own class?" We've been going ro...
I think extension methods help a lot when writing code, if you add extension methods to basic types you'll get them quicky in the intellisense. I have a format provider to [format a file size](https://stackoverflow.com/questions/128618/c-file-size-format-provider). To use it I need to write: ``` Console.WriteLine(Str...
The **only** advantage of extension methods is code readability. That's it. Extension methods allow you to do this: ``` foo.bar(); ``` instead of this: ``` Util.bar(foo); ``` Now there are a lot of things in C# that are like this. In other words there are many features in C# that seem trivial and don't have great ...
What Advantages of Extension Methods have you found?
[ "", "c#", "extension-methods", "" ]
I have a database with millions of phone numbers with free-for-all formatting. Ie, the UI does not enforce any constraints and the users are typing in whatever they want. What I'm looking for is a Java API that can make a best-effort to convert these into a consistent format. Ideally, the API would take the free text ...
You could write your own (for US phone # format): * Strip any non-numeric characters from the string * Check that the remaining string is ten characters long * Put parentheses around the first three characters and a dash between the sixth and seventh character. * Prepend "+1 " to the string --- ### Update: Google r...
You could try this Java phone number formatting library <https://github.com/googlei18n/libphonenumber> It has data for hundreds of countries and formats.
Java phone number format API
[ "", "java", "" ]
I was playing around with Boost.Regex to parse strings for words and numbers. This is what I have so far: ``` #include <iostream> #include <string> #include <boost/foreach.hpp> #include <boost/regex.hpp> #include <boost/range.hpp> using namespace std; using namespace boost; int main() { regex re ( "(...
Boost.IOStreams has a [regex\_filter](http://www.boost.org/doc/libs/1_55_0/libs/iostreams/doc/classes/regex_filter.html) allowing one to perform the equivalent of a regex\_replace on a stream. However, looking at the implementation, it seems to "cheat" in that it simply loads the whole stream into a buffer and then cal...
The regex\_iterator constructor requires BidirectionalIterators, but std::istream\_iterator is only an InputIterator, so it appears that you'd not be able to do this with any of the standard stream classes and/or objects (cin, ifstream, etc.). If you had a custom stream that exposed a bidirectional iterator, it should ...
Can you use Boost.Regex to parse a stream?
[ "", "c++", "regex", "boost", "stream", "" ]
Ok, this is bugging me, and I just can't figure out what is wrong... I have made two forms. First form just has a simple button on it, which opens the other as a dialog like so: ``` using (Form2 f = new Form2()) { if (f.ShowDialog() != DialogResult.OK) MessageBox.Show("Not OK"); else MessageBo...
Just setting the `AcceptButton`/`CancelButton` is not enough. This just tells which button should be invoked on `Enter`/`Esc`. You have to set the button's `DialogResult` property.
Try setting `DialogResult` on `button1` ``` this.button1.DialogResult = System.Windows.Forms.DialogResult.OK; ```
WinForms AcceptButton not working?
[ "", "c#", "winforms", "modal-dialog", "" ]
Currently I'm working on a simple Mail-Merge module. I need to load plain \*.RTF template, then replace all words enclosed in [[field]] tags and at the end and print them out. I found the iText library which is free and capable of loading/saving pdfs and rtf. I managed to load rtf, merge a few copies to one huge doc ...
Finally I decided to use \*.docx and "Open XML SDK 2.0 for Microsoft Office" .NET strongly typed wrapper.
I don't think that pdf is the way you want to go. According to [this article](http://itext.ugent.be/library/question.php?id=48) it is extremely difficult at best and not possible at worst. Would something like [RTFLib](http://xmlgraphics.apache.org/fop/dev/rtflib.html) work better for you? G-Man
iText - how to do search/replace on existing RTF document
[ "", "c#", "itext", "mailmerge", "" ]
We have an old legacy PHP application. Now I want to write a new application module using Ruby on Rails. Deployment is a one problem. I guess that it should be possible to run PHP app (via mod\_php) and RoR app (via mod\_proxy / mongrel) on a one Apache server. I don't want to use mod\_rails because it requires to run...
First, if you are placing the rails app in a sub directory it is possible to use mod\_rails. In your configuration for the PHP site you can have a location that has a root for rails. ``` <Location /railsapp> DocumentRoot /.../app/public </Location> ``` To get a session over to the rails side, you could either creat...
I've done a mixed PHP/RoR app before (old PHP code, new hawt RoR features, as stuff needed fixing it got re-implemented). It's not really all that hard -- you just serve up the PHP as normal files, and use a 404 handler to redirect everything else to the Rails app. As far as the session data goes, you *could* stuff it...
Tricky integration of a legacy PHP app and a new Ruby on Rails app
[ "", "php", "ruby-on-rails", "interop", "" ]
Is there any advantage over using a class over a struct in cases such as these? (note: it will only hold variables, there will never be functions) ``` class Foo { private: struct Pos { int x, y, z }; public: Pos Position; }; ``` Versus: ``` struct Foo { struct Pos { int x, y, z } Pos; }; ``` --- ...
There is no real advantage of using one over the other, in c++, the only difference between a struct and a class is the default visibility of it's members (structs default to public, classes default to private). Personally, I tend to prefer structs for POD types and use classes for everything else. EDIT: [litb](https...
One side point is that structs are often used for aggregate initialized data structures, since all non-static data members must be public anyway (C++03, 8.5.1/1). ``` struct A { // (valid) { int a; int b; } x = { 1, 2 }; struct A { // (invalid) private: int a; int b; } x = { 1, 2 }; class A { // (inva...
Class vs Struct for data only?
[ "", "c++", "class", "struct", "" ]
I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter and return to that state easily. I started by ...
Try this code from ActiveState recipes: <http://code.activestate.com/recipes/572213/> It extends pickle so it supports pickling anything defined in the shell console. Theoretically you should just be able to pickle the **main** module, according to their documentation: ``` import savestate, pickle, __main__ pickle.du...
I'd suggest tackling the root cause problem. > "The application takes a long time to > start up and I have no ability to > restart the interpreter without > restarting the whole application" I doubt this is actually 100% true. If the overall application is the result of an act of Congress, okay, it can't be changed. ...
Restarting a Python Interpreter Quietly
[ "", "python", "interpreter", "" ]