Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
How does container object like vector in stl get destroyed even though they are created in heap? **EDIT** If the container holds pointers then how to destroy those pointer objects
An STL container of pointer will NOT clean up the data pointed at. It will only clean up the space holding the pointer. If you want the vector to clean up pointer data you need to use some kind of smart pointer implementation: ``` { std::vector<SomeClass*> v1; v1.push_back(new SomeClass()); std::vector<boost::shared_ptr<SomeClass> > v2; boost::shared_ptr<SomeClass> obj(new SomeClass); v2.push_back(obj); } ``` When that scope ends both vectors will free their internal arrays. v1 will leak the SomeClass that was created since only the pointer to it is in the array. v2 will not leak any data.
If you have a `vector<T*>`, your code needs to delete those pointers before delete'ing the vector: otherwise, that memory is leaked. Know that C++ doesn't do garbage collection, here is an example of why (appologies for syntax errors, it has been a while since I've written C++): ``` typedef vector<T*> vt; ⋮ vt *vt1 = new vt, *vt2 = new vt; T* t = new T; vt1.push_back(t); vt2.push_back(t); ⋮ delete vt1; ``` The last line (`delete vt1;`) clearly should not delete the pointer it contains; after all, it's also in vt2. So it doesn't. And neither will the delete of `vt2`. (If you want a vector type that deletes pointers on destroy, such a type can of course be written. Probably has been. But beware of delete'ing pointers that someone else is still holding a copy of.)
How do stl containers get deleted?
[ "", "c++", "memory-management", "stl", "vector", "containers", "" ]
I need some SQL to update a record in a database if it exists and insert it when it does not, looking around there looks to be several solutions for this, but I don't know what are the correct/ accepted ways to do this. I would ideally like it to work on both Firebird 2 and MySQL 5 as the update will need to be ran against both databases, and it would be simpler if the same SQL ran on both, if it worked on more database that would be a plus. Speed and reliability also factor in, reliability over speed in this case but it will potentially be used to update 1000's of records in quick succession (over different tables). any subjections?
You should either use something like this: ``` BEGIN TRANSACTION IF EXISTS (SELECT * FROM the_table WHERE pk = 'whatever') UPDATE the_table SET data = 'stuff' WHERE pk = 'whatever' ELSE INSERT INTO the_table (pk, data) VALUES ('whatever', 'stuff') COMMIT ``` Or this, but send them separately and ignore any errors from the INSERT about violating primary key constraints: ``` INSERT INTO the_table (pk, data) VALUES ('whatever', 'stuff') UPDATE the_table SET data = 'stuff' WHERE pk = 'whatever' ```
In Firebird 2.1 you can use [UPDATE OR INSERT](http://www.firebirdsql.org/refdocs/langrefupd25-update-or-insert.html) for simple cases or [MERGE](http://www.firebirdsql.org/refdocs/langrefupd21-merge.html) for more complex scenarios.
What is the correct/ fastest way to update/insert a record in sql (Firebird/MySql)
[ "", "sql", "mysql", "firebird", "upsert", "" ]
I have to following code: <http://www.nomorepasting.com/getpaste.php?pasteid=22987> If `PHPSESSID` is not already in the table the `REPLACE INTO` query works just fine, however if `PHPSESSID` exists the call to execute succeeds but sqlstate is set to 'HY000' which isn't very helpful and `$_mysqli_session_write->errno` and `$_mysqli_session_write->error` are both empty and the data column doesn't update. I am fairly certain that the problem is in my script somewhere, as manually executing the `REPLACE INTO` from mysql works fine regardless of whether of not the `PHPSESSID` is in the table.
So as it turns out there are other issues with using REPLACE that I was not aware of: [Bug #10795: REPLACE reallocates new AUTO\_INCREMENT](http://bugs.mysql.com/bug.php?id=10795) (Which according to the comments is not actually a bug but the 'expected' behaviour) As a result my id field keeps getting incremented so the better solution is to use something along the lines of: ``` INSERT INTO session(phpsessid, data) VALUES('{$id}', '{$data}') ON DUPLICATE KEY UPDATE data='{$data}' ``` This also prevents any foreign key constraints from breaking and potential causing data integrity problems.
Why are you trying to doing your prepare in the session open function? I don't believe the write function is called more then once during a session, so preparing it in the open doesn't do much for you, you might as well do that in your session write. Anyway I believe you need some whitespace after the table name, and before the column list. Without the whitespace I believe mysql would act as if you where trying to call the non-existent function named session(). ``` REPLACE INTO session (phpsessid, data) VALUES(?, ?) ``` --- > MySQL sees no difference between > 'COUNT (*)' and 'COUNT(*)' Interesting, when I run the below in the mysql CLI I seem to get a different result. ``` mysql> select count (*); ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*)' at line 1 mysql> select count(*); +----------+ | count(*) | +----------+ | 1 | +----------+ 1 row in set (0.00 sec) ```
MySQLi prepared statements and REPLACE INTO
[ "", "php", "mysql", "mysqli", "" ]
When reviewing our codebase, I found an inheritance structure that resembles the following pattern: ``` interface IBase { void Method1(); void Method2(); } interface IInterface2 : IBase { void Method3(); } class Class1 : IInterface2 { ... } class Class2 : IInterface2 { ... } class Class3 : IInterface2 { ... } ``` In `Class2`, `Method1` throws `NotImplementedException`. Questions: * What do you think in general about inheriting interfaces? * Does the relationship between `IBase` and `Class2` violate the Liskov Substitution Principle?
Well, first of all, I'm generally against implementing an interface by throwing NotImplementedException exceptions. It is basically like saying "Well, this class can also function as a calculator, err, almost". But in some cases it really is the only way to do something "the right way", so I'm not 100% against it. Just something to be aware of. An interface is a contract, by implementing the interface you say that you abide by the contract. If you then start negating parts of the contract, it sounds to me as the contract, or the implementation of it, was poorly thought out. --- **Edit**: After seing [Greg Beech](https://stackoverflow.com/users/13552/greg-beech)'s answer: If an interface specifically says that implementations should throw these exceptions, then it's part of the contract, then I agree that the class is fully allowed to do it. --- As for the substitution principle, it [states](http://en.wikipedia.org/wiki/Liskov_substitution_principle) that: > Let q(x) be a property provable about objects x of type T. Then q(y) should be true for objects y of type S where S is a subtype of T. In this context, it violates the principle just as much as overriding a method from a base class does, if you change what the method does in the descendant type. The principle is more detailed on the wikipedia page, like the following points (parenthesis and emphasis on my comments): * Preconditions cannot be strengthened in a subclass. **(A precondition could be that "the class is ready for a call to this method at this point")** * Postconditions cannot be weakened in a subclass. **(A postcondition could be that after calling the method, something is true about the state of the class)** Since you have not shown the full contract of your interfaces, only the declarative part that the compiler can check, it is impossible to know wether the principle holds for your implementation of not. For instance, if your Method2 has the following conditions attached to it: * Can be called at all times * Modifies the state of the object to be ready for the next event in a chain of events Then throwing a NotImplementedException violates the principles. However, if the contract also states that: * For classes that doesn't support chains of events, this method should throw NotImplementedException or NotSupportedException Then it probably does not.
So, I'm assuming the question you're asking is: > If a derived type throws a > `NotImplementedException` for a method > where a base type does not, does this > violate the Liskov subsitution > principle. I'd say that depends on whether the interface documentation says that a method may throw this exception to fulfill its contract. If so then it does not violate the principle, otherwise it does. The classic example of thisin the .NET framework is the `Stream` class which has a bunch of operations such as `Read`, `Write` and `Seek` yet there is no requirement for a stream to support all of these operations, and are documented as being allowed to throw `NotSupportedException`.
Interface inheritance: what do you think of this:
[ "", "c#", "oop", "inheritance", "liskov-substitution-principle", "" ]
How can you join between a table with a sparse number of dates and another table with an exhaustive number of dates such that the gaps between the sparse dates take the values of the previous sparse date? Illustrative example: ``` PRICE table (sparse dates): date itemid price 2008-12-04 1 $1 2008-12-11 1 $3 2008-12-15 1 $7 VOLUME table (exhaustive dates): date itemid volume_amt 2008-12-04 1 12345 2008-12-05 1 23456 2008-12-08 1 34567 2008-12-09 1 ... 2008-12-10 1 2008-12-11 1 2008-12-12 1 2008-12-15 1 2008-12-16 1 2008-12-17 1 2008-12-18 1 ``` Desired result: ``` date price volume_amt 2008-12-04 $1 12345 2008-12-05 $1 23456 2008-12-08 $1 34567 2008-12-09 $1 ... 2008-12-10 $1 2008-12-11 $3 2008-12-12 $3 2008-12-15 $7 2008-12-16 $7 2008-12-17 $7 2008-12-18 $7 ``` Update: A couple people have suggested a correlated subquery that accomplishes the desired result. (Correlated subquery = a subquery that contains a reference to the outer query.) This will work; however, I should have noted that the platform I'm using is MySQL, for which correlated subqueries are poorly optimized. Any way to do it without using a correlated subquery?
This isn't as simple as a single LEFT OUTER JOIN to the sparse table, because you want the NULLs left by the outer join to be filled with the most recent price. ``` EXPLAIN SELECT v.`date`, v.volume_amt, p1.item_id, p1.price FROM Volume v JOIN Price p1 ON (v.`date` >= p1.`date` AND v.item_id = p1.item_id) LEFT OUTER JOIN Price p2 ON (v.`date` >= p2.`date` AND v.item_id = p2.item_id AND p1.`date` < p2.`date`) WHERE p2.item_id IS NULL; ``` This query matches Volume to all rows in Price that are earlier, and then uses another join to make sure we find only the most recent price. I tested this on MySQL 5.0.51. It uses neither correlated subqueries nor group by. **edit:** Updated the query to match to item\_id as well as date. This seems to work too. I created an index on `(date)` and an index on `(date, item_id)` and the EXPLAIN plan was identical. An index on `(item_id, date)` may be better in this case. Here's the EXPLAIN output for that: ``` +----+-------------+-------+------+---------------+---------+---------+-----------------+------+--------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+---------+---------+-----------------+------+--------------------------------------+ | 1 | SIMPLE | p1 | ALL | item_id | NULL | NULL | NULL | 6 | | | 1 | SIMPLE | v | ref | item_id | item_id | 22 | test.p1.item_id | 3 | Using where | | 1 | SIMPLE | p2 | ref | item_id | item_id | 22 | test.v.item_id | 1 | Using where; Using index; Not exists | +----+-------------+-------+------+---------------+---------+---------+-----------------+------+--------------------------------------+ ``` But I have a very small data set, and the optimization may depend on larger data sets. You should experiment, analyzing the optimization using a larger data set. **edit:** I pasted the wrong EXPLAIN output before. The one above is corrected, and shows better use of the `(item_id, date)` index.
Assuming there is only 1 price per date/itemid: ``` select v.date, v.itemid, p.price from volume v join price p on p.itemid = v.item_id where p.date = (select max(p2.date) from price p2 where p2.itemid = v.itemid and p2.date <= v.date); ```
Need help with a complex Join statement in SQL
[ "", "sql", "greatest-n-per-group", "" ]
I am new to threads and in need of help. I have a data entry app that takes an exorbitant amount of time to insert a new record(i.e 50-75 seconds). So my solution was to send an insert statement out via a ThreadPool and allow the user to begin entering the data for the record while that insert which returns a new record ID while that insert is running. My problem is that a user can hit save before the new ID is returned from that insert. I tried putting in a Boolean variable which get set to true via an event from that thread when it is safe to save. I then put in ``` while (safeToSave == false) { Thread.Sleep(200) } ``` I think that is a bad idea. If i run the save method before that tread returns, it gets stuck. So my questions are: 1. Is there a better way of doing this? 2. What am I doing wrong here? Thanks for any help. Doug **Edit for more information:** It is doing an insert into a very large (approaching max size) FoxPro database. The file has about 200 fields and almost as many indexes on it. And before you ask, no I cannot change the structure of it as it was here before I was and there is a ton of legacy code hitting it. The first problem is, in order to get a new ID I must first find the max(id) in the table then increment and checksum it. That takes about 45 seconds. Then the first insert is simply and insert of that new id and an enterdate field. This table is not/ cannot be put into a DBC so that rules out auto-generating ids and the like. **@joshua.ewer** You have the proccess correct and I think for the short term I will just disable the save button, but I will be looking into your idea of passing it into a queue. Do you have any references to MSMQ that I should take a look at?
Everyone else, including you, addressed the core problems (insert time, why you're doing an insert, then update), so I'll stick with just the technical concerns with your proposed solution. So, if I get the flow right: * Thread 1: Start data entry for record * Thread 2: Background calls to DB to retrieve new Id * The save button is always enabled, if user tries to save before Thread 2 completes, you put #1 to sleep for 200 ms? The simplest, not best, answer is to just have the button disabled, and have that thread make a [callback](http://msdn.microsoft.com/en-us/library/system.threading.waitcallback.aspx "callback") to a delegate that enables the button. They can't start the update operation until you're sure things are set up appropriately. Though, I think a much better solution (though it might be overblown if you're just building a Q&D front end to FoxPro), would be to throw those save operations into a queue. The user can key as quickly as possible, then the requests are put into something like MSMQ and they can complete in their own time asynchronously.
1) Many :), for example you could disable the "save" button while the thread is inserting the object, or you can setup a Thread Worker which handle a queue of "save requests" (but I think the problem here is that the user wants to modify the newly created record, so disabling the button maybe it's better) 2) I think we need some more code to be able to understand... (or maybe is a synchronization issue, I am not a bug fan of threads too) btw, I just don't understand why an insert should take so long..I think that you should check that code first! <- just as charles stated before (sorry, dind't read the post) :)
ThreadPool and GUI wait question
[ "", "c#", "threadpool", "deadlock", "" ]
While looking at online code samples, I have sometimes come across an assignment of a String constant to a String object via the use of the new operator. For example: ``` String s; ... s = new String("Hello World"); ``` This, of course, compared to ``` s = "Hello World"; ``` I'm not familiar with this syntax and have no idea what the purpose or effect would be. Since String constants typically get stored in the constant pool and then in whatever representation the JVM has for dealing with String constants, would anything even be allocated on the heap?
The one place where you may *think* you want `new String(String)` is to force a distinct copy of the internal character array, as in ``` small=new String(huge.substring(10,20)) ``` However, this behavior is unfortunately undocumented and implementation dependent. I have been burned by this when reading large files (some up to 20 MiB) into a String and carving it into lines after the fact. I ended up with all the strings for the lines referencing the char[] consisting of entire file. Unfortunately, that unintentionally kept a reference to the entire array for the few lines I held on to for a longer time than processing the file - I was forced to use `new String()` to work around it, since processing 20,000 files very quickly consumed huge amounts of RAM. The only implementation agnostic way to do this is: ``` small=new String(huge.substring(10,20).toCharArray()); ``` This unfortunately must copy the array twice, once for `toCharArray()` and once in the String constructor. There needs to be a documented way to get a new String by copying the chars of an existing one; or the documentation of `String(String)` needs to be improved to make it more explicit (there is an implication there, but it's rather vague and open to interpretation). ### Pitfall of Assuming what the Doc Doesn't State In response to the comments, which keep coming in, observe what the Apache Harmony implementation of `new String()` was: ``` public String(String string) { value = string.value; offset = string.offset; count = string.count; } ``` That's right, no copy of the underlying array there. And yet, it still conforms to the (Java 7) String documentation, in that it: > Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable. The salient piece being "copy of the argument ***string***"; it does not say "copy of the argument string and the underlying character array supporting the string". Be careful that you program to the *documentation* and not **one** *implementation*.
The only time I have found this useful is in declaring lock variables: ``` private final String lock = new String("Database lock"); .... synchronized(lock) { // do something } ``` In this case, debugging tools like Eclipse will show the string when listing what locks a thread currently holds or is waiting for. You have to use "new String", i.e. allocate a new String object, because otherwise a shared string literal could possibly be locked in some other unrelated code.
What is the purpose of the expression "new String(...)" in Java?
[ "", "java", "string", "" ]
Okay, so basically I want to be able to retrieve keyboard text. Like entering text into a text field or something. I'm only writing my game for windows. I've disregarded using Guide.BeginShowKeyboardInput because it breaks the feel of a self contained game, and the fact that the Guide always shows XBOX buttons doesn't seem right to me either. Yes it's the easiest way, but I don't like it. Next I tried using System.Windows.Forms.NativeWindow. I created a class that inherited from it, and passed it the Games window handle, implemented the WndProc function to catch WM\_CHAR (or WM\_KEYDOWN) though the WndProc got called for other messages, WM\_CHAR and WM\_KEYDOWN never did. So I had to abandon that idea, and besides, I was also referencing the whole of Windows forms, which meant unnecessary memory footprint bloat. So my last idea was to create a Thread level, low level keyboard hook. This has been the most successful so far. I get WM\_KEYDOWN message, (not tried WM\_CHAR yet) translate the virtual keycode with Win32 funcation MapVirtualKey to a char. And I get my text! (I'm just printing with Debug.Write at the moment) A couple problems though. It's as if I have caps lock on, and an unresponsive shift key. (Of course it's not however, it's just that there is only one Virtual Key Code per key, so translating it only has one output) and it adds overhead as it attaches itself to the Windows Hook List and isn't as fast as I'd like it to be, but the slowness could be more due to Debug.Write. Has anyone else approached this and solved it, without having to resort to an on screen keyboard? or does anyone have further ideas for me to try? thanks in advance. Question asked by Jimmy > Maybe I'm not understanding the question, but why can't you use the XNA Keyboard and KeyboardState classes? My comment: > It's because though you can read keystates, you can't get access to typed text as and how it is typed by the user. So let me further clarify. I want to implement being able to read text input from the user as if they are typing into textbox is windows. The keyboard and KeyboardState class get states of all keys, but I'd have to map each key and combination to it's character representation. This falls over when the user doesn't use the same keyboard language as I do especially with symbols (my double quotes is shift + 2, while american keyboards have theirs somewhere near the return key). --- it seems my window hook was the way to go, just the reason I wasn't getting WM\_CHAR is because the XNA message pump doesn't do translate message. Adding TranslateMessage in whenever I received a WM`_`KEYDOWN message meant I got my WM\_CHAR message, I then used this to fire a character typed event in my MessageHook class which my KeyboardBuffer class had subscribed to, which then buffers that to a text buffer :D (or StringBuilder, but the result is the same) So I have it all working as I want. Many thanks to Jimmy for a link to a very informative thread.
Maybe I'm not understanding the question, but why can't you use the XNA Keyboard and KeyboardState classes?
For adding a windows hook in XNA ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; using System.Reflection; /* Author: Sekhat * * License: Public Domain. * * Usage: * * Inherit from this class, and override the WndProc function in your derived class, * in which you handle your windows messages. * * To start recieving the message, create an instance of your derived class, passing in the * window handle of the window you want to listen for messages for. * * in XNA: this would be the Game.Window.Handle property * in Winforms Form.Handle property */ namespace WindowsHookExample { public abstract class WindowsHook : IDisposable { IntPtr hHook; IntPtr hWnd; // Stored here to stop it from getting garbage collected Win32.WndProcDelegate wndProcDelegate; public WindowsHook(IntPtr hWnd) { this.hWnd = hWnd; wndProcDelegate = WndProcHook; CreateHook(); } ~WindowsHook() { Dispose(false); } private void CreateHook() { uint threadId = Win32.GetWindowThreadProcessId(hWnd, IntPtr.Zero); hHook = Win32.SetWindowsHookEx(Win32.HookType.WH_CALLWNDPROC, wndProcDelegate, IntPtr.Zero, threadId); } private int WndProcHook(int nCode, IntPtr wParam, ref Win32.Message lParam) { if (nCode >= 0) { Win32.TranslateMessage(ref lParam); // You may want to remove this line, if you find your not quite getting the right messages through. This is here so that WM_CHAR is correctly called when a key is pressed. WndProc(ref lParam); } return Win32.CallNextHookEx(hHook, nCode, wParam, ref lParam); } protected abstract void WndProc(ref Win32.Message message); #region Interop Stuff // I say thankya to P/Invoke.net. // Contains all the Win32 functions I need to deal with protected static class Win32 { public enum HookType : int { WH_JOURNALRECORD = 0, WH_JOURNALPLAYBACK = 1, WH_KEYBOARD = 2, WH_GETMESSAGE = 3, WH_CALLWNDPROC = 4, WH_CBT = 5, WH_SYSMSGFILTER = 6, WH_MOUSE = 7, WH_HARDWARE = 8, WH_DEBUG = 9, WH_SHELL = 10, WH_FOREGROUNDIDLE = 11, WH_CALLWNDPROCRET = 12, WH_KEYBOARD_LL = 13, WH_MOUSE_LL = 14 } public struct Message { public IntPtr lparam; public IntPtr wparam; public uint msg; public IntPtr hWnd; } /// <summary> /// Defines the windows proc delegate to pass into the windows hook /// </summary> public delegate int WndProcDelegate(int nCode, IntPtr wParam, ref Message m); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SetWindowsHookEx(HookType hook, WndProcDelegate callback, IntPtr hMod, uint dwThreadId); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern bool UnhookWindowsHookEx(IntPtr hhk); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, ref Message m); [DllImport("coredll.dll", SetLastError = true)] public static extern IntPtr GetModuleHandle(string module); [DllImport("user32.dll", EntryPoint = "TranslateMessage")] public extern static bool TranslateMessage(ref Message m); [DllImport("user32.dll")] public extern static uint GetWindowThreadProcessId(IntPtr window, IntPtr module); } #endregion #region IDisposable Members public void Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (disposing) { // Free managed resources here } // Free unmanaged resources here if (hHook != IntPtr.Zero) { Win32.UnhookWindowsHookEx(hHook); } } #endregion } } ```
XNA - Keyboard text input
[ "", "c#", ".net", "xna", "" ]
I have just moved job and gone from VB 6 to VB.Net and found the learning jump fairly steep, have more a problem with the object / conceptual side of things .. but getting there now ... but as I was a assembler / C++ 10/15 years ago and was considering learning C++/C# .Net (XNA games library calls my name) but not sure if it would hinder my VB.NET learning .... or should I just get myself certified
To me the biggest obstacle for .NET is learn what is available in the framework. Therefore, if you find it easier to code in C# it will mean you only struggle with one thing instead of two. Once you know the framework it's just syntax really as 95% of the stuff you can do with C# can be done with VB. Also, C# will force you to write code in a more object orientated manner as you can't fall back to coding in a VB6 style. '[yield return](http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx)' is an example of something that doesn't have an equivalent in VB9 (there are rumours this is being added for VBX though).
I was (back in the day) a VB6 dev, and I would expect it to help. There is a much-commented tendency for VB6 developers to keep writing VB6 in .NET; even just a brief look at C# might help you think about VB.NET as a .NET language, rather than a Visual Studio 6 ancestor. Of course, you might find (as I did) that you don't want to go back to VB.NET after C# ;-p But as has already been mentioned - the *framework* is identical. And with C# 4.0, many of the differences will become even less (with "dynamic" making it easier for C# to talk to late-bound COM, and the named arguments / auto-ref stuff making it easier for typed COM). There is a lot of drive for converging the feature sets of C# 4.0 and VB.NET in VS2010
Learning C# help or hinder VB.NET learning
[ "", "c#", "vb.net", "" ]
I can't tell if this is a result of the jQuery I'm using, but this is what I'm trying to do: ``` <div class="info" style="display: inline;" onMouseOut="$(this).children('div').hide('normal');" onMouseOver="$(this).children('div').show('normal');" > <img src="images/target.png"> <div class="tooltiptwo" id="tooltip" style="font-weight: normal; font-size: 0.8em;" >TOOLTIP TEXT</div> </div> ``` To anyone familiar with basic CSS and jQuery, I'm trying to add a simple animation to my tooltips. The problem is the triggering of such an animation. It seems that when the animation happens, if the user moves their mouse over the tooltip, the animation will go into a loop of showing and hiding until the user moves the mouse away. This is an undesired effect, as I want the animation to go away just once, when the mouse moves out of the *parent* div. I've positioned my CSS so that the tooltip appears away from the parent div, but regardless the actions should be triggering only on the parent, and not any of its children. So basically, how would I go about achieving this? I want my hover/out state on my parent element to trigger a function (an animation) on the children of that parent, without the hover/out states of the children doing anything. It seems that the normal method of `onMouseOver` and `onMouseOut` is triggering even for the children of the parent that the method belongs to, which is causing some rather undesirable effects. Note that I'm new to jQuery (although its amazing so far, I want to coat my site in its goodness if I can) and if there is a better way to achieve the hover/out states using jQuery I probably don't know about them.
**edit**: actually this is a much better solution ([credit](https://stackoverflow.com/questions/308411/#308720)): ``` $('.info').bind('mouseenter', function() { $('div', this).show('normal'); }); $('.info').bind('mouseleave', function() { $('div', this).hide('normal'); }); // hide the tooltip to start off $('.info div').hide(); ``` **edit2**: in response to the comments, i think i would suggest structuring your HTML differently then, or binding the event to the sibling element (the image) instead: ``` <div class="info"> <img src="stuff.jpg" /> </div> <div class="tooltip"></div> ``` or binding on the image: ``` $('.info img').bind('mouseenter', function() { etc... }); $('.info img').bind('mouseleave', function() { etc... }); ```
Did you follow this **[tutorial](http://www.kriesi.at/archives/create-simple-tooltips-with-css-and-jquery)** ? Especially the mousemove part, where he constantly sets the positioning values left and top to align the tooltip next to the cursor. the X and Y coordinates are called via .pageX and .pageY. And he also adds a little offset of 15 px so the tooltip is not directly below the cursor. That way, the mouse can not be over the tooltip, even the fadeout phase. Hence no infinite loop
Javascript "onMouseOver" triggering for children?
[ "", "javascript", "jquery", "parent-child", "jquery-events", "" ]
I once came across a validation framework for java, where you wrote one method that protected the integrity of the data-type and any CRUD operations on that data-type automatically called this method. Does anyone know what this framework is? I simply want to avoid repetitive validation on every CRUD method attached to a data-type.
Here's a huge list of Java Validation Libraries / Frameworks - <http://java-source.net/open-source/validation>
Apache Commons has a [validation](http://commons.apache.org/validator/) framework.
Java Validation Frameworks
[ "", "java", "validation", "frameworks", "" ]
Are there any sorts of useful idioms I can make use of when writing an API that is asynchronous? I would like to standardize on something as I seem to be using a few different styles throughout. It seems hard to make asynchronous code simple; I suppose this is because asynchronous operations are anything but. At the most basic level, the user of the API must be able to: 1. Have data pushed to them as it becomes available- Check the status of the asynchronous operation- Be notified of errors that occur- Wait for completion (converting the asynchronous operation to a synchronous one) My classes support several asynchronous operations. I have been putting some of the status/error callbacks in the class around it, but the class is becoming gunked up with a lot of incidental fields, as well as getting too large. I am curious if anyone has used an asynchronous API they found to be well-organized. I have looked at .NET's Begin/EndAsyncOperation + AsyncResult design, as well as some classes in Java (e.g. Future). This is being written in Python, so it remains very flexible. There is a caveat: some of these asynchronous operations are being marshaled to a remote machine and executed over there. Thus, not every operation necessarily executes in a separate thread.
Also have a look at the Asynchronous Completion Token and ActiveObject patterns.
You may want to look at [Python Twisted](http://twistedmatrix.com/trac/). It is a nice [Reactor](http://en.wikipedia.org/wiki/Reactor_pattern) based API that supports [asynchronous](http://twistedmatrix.com/projects/core/documentation/howto/async.html) operations. [Proactor](http://www.cs.uu.nl/docs/vakken/no/proactor.pdf) is the common term for asynchronous completion handler like frameworks.
Idiomatic asynchronous design
[ "", "python", "asynchronous", "" ]
George Marsaglia has written an excellent random number generator that is extremely fast, simple, and has a much higher period than the Mersenne Twister. Here is the code with a description: [good C random number generator](http://school.anhb.uwa.edu.au/personalpages/kwessen/shared/Marsaglia03.html) I wanted to port the CMWC4096 code to Java, but it uses several unsigned datatypes so I am not sure how to do this properly. Here is the full C code: ``` /* choose random initial c<809430660 and */ /* 4096 random 32-bit integers for Q[] */ static unsigned long Q[4096],c=362436; unsigned long CMWC4096(void) { unsigned long long t, a=18782LL; static unsigned long i=4095; unsigned long x,r=0xfffffffe; i = (i+1) & 4095; t = a*Q[i] + c; c = (t>>32); x = t + c; if (x < c) { x++; c++; } return (Q[i] = r - x); } ``` Can anyone port this to Java? How does this work when you only have signed numbers available? **EDIT:** Thanks everybody for the quick answers! For the first 100 million numbers this java code seems to produce the same result as the C code. It is 3 times faster than Java's java.util.Random. ``` public class ComplimentaryMultiplyWithCarryRandom { /** * Choose 4096 random 32-bit integers */ private long[] Q; /** * choose random initial c<809430660 */ private long c = 362436; private int i; public ComplimentaryMultiplyWithCarryRandom() { Random r = new Random(1); Q = new long[4096]; // TODO initialize with real random 32bit values for (int i = 0; i < 4096; ++i) { long v = r.nextInt(); v -= Integer.MIN_VALUE; Q[i] = v; } i = 4095; } int next() { i = (i + 1) & 4095; long t = 18782 * Q[i] + c; c = t >>> 32; long x = (t + c) & 0xffffffffL; if (x < c) { ++x; ++c; } long v = 0xfffffffeL - x; Q[i] = v; return (int) v; } } ```
> Can anyone port this to Java? How does > this work when you only have signed > numbers available? No Stress! `a=18782` so the largest `t` could ever be is not large enough to cause signed vs. unsigned problems. You would have to "upgrade" the result of using Q to a value equal to a 32-bit unsigned number before using it anywhere. e.g. if Q is an `int` (32-bit signed) then you'd have to do this before using it in the `t=a*Q[i]+c` statement, e.g. ``` t=a*(((long)Q[i])&0xffffffffL)+c ``` where this (((long)Q[i])&0xffffffffL) business promotes Q[i] to a 64-bit # and ensures its high 32 bits are 0's. (edit: NOTE: you need 0xffffffffL here. Java does the wrong thing if you use 0xffffffff, it seems like it "optimizes" itself to the wrong answer & you get a negative number if Q[i]'s high bit is 1.) You should be able to verify this by running the algorithms in C++ and Java to compare the outputs. edit: here's a shot at it. I tried running it in C++ and Java for N=100000; they both match. Apologies if I used bad Java idioms, I'm still fairly new to Java. C++: ``` // marsaglia2003.cpp #include <stdio.h> #include <stdlib.h> // for atoi class m2003 { enum {c0=362436, sz=4096, mask=4095}; unsigned long Q[sz]; unsigned long c; short i; public: m2003() { // a real program would seed this with a good random seed // i'm just putting in something that makes the output interesting for (int j = 0; j < sz; ++j) Q[j] = j + (j << 16); i = 4095; c = c0; } unsigned long next() { unsigned long long t, a=18782LL; unsigned long x; unsigned long r=0xfffffffe; i = (i+1)&mask; t=a*Q[i]+c; c=(unsigned long)(t>>32); x=(unsigned long)t + c; if (x<c) { x++; c++; } return (Q[i]=r-x); } }; int main(int argc, char *argv[]) { m2003 generator; int n = 100; if (argc > 1) n = atoi(argv[1]); for (int i = 0; i < n; ++i) { printf("%08x\n", generator.next()); } return 0; } ``` java: (slower than compiled C++ but it matches for N=100000) ``` // Marsaglia2003.java import java.util.*; class Marsaglia2003 { final static private int sz=4096; final static private int mask=4095; final private int[] Q = new int[sz]; private int c=362436; private int i=sz-1; public Marsaglia2003() { // a real program would seed this with a good random seed // i'm just putting in something that makes the output interesting for (int j = 0; j < sz; ++j) Q[j] = j + (j << 16); } public int next() // note: returns a SIGNED 32-bit number. // if you want to use as unsigned, cast to a (long), // then AND it with 0xffffffffL { long t, a=18782; int x; int r=0xfffffffe; i = (i+1)&mask; long Qi = ((long)Q[i]) & 0xffffffffL; // treat as unsigned 32-bit t=a*Qi+c; c=(int)(t>>32); // because "a" is relatively small this result is also small x=((int)t) + c; if (x<c && x>=0) // tweak to treat x as unsigned { x++; c++; } return (Q[i]=r-x); } public static void main(String args[]) { Marsaglia2003 m2003 = new Marsaglia2003(); int n = 100; if (args.length > 0) n = Integer.parseInt(args[0]); for (int i = 0; i < n; ++i) { System.out.printf("%08x\n", m2003.next()); } } }; ```
Most of the time there is no need to use larger numeric types for simulating unsigned types in Java. For addition, subtraction, multiplication, shift left, the logical operations, equality and casting to a smaller numeric type it doesn't matter whether the operands are signed or unsigned, the result will be the same regardless, viewed as a bit pattern. For shifting to the right use >> for signed, >>> for unsigned. For signed casting to a larger type just do it. For unsigned casting from a smaller type to a long use & with a mask of type long for the smaller type. E.g., short to long: s & 0xffffL. For unsigned casting from a smaller type to an int use & with a mask of type int. E.g., byte to int: b & 0xff. Otherwise do like in the int case and apply a cast on top. E.g., byte to short: (short) (b & 0xff). For the comparison operators < etc. and division the easiest is to cast to a larger type and do the operation there. But there also exist other options, e.g. do comparisons after adding an appropriate offset.
Port of Random generator from C to Java?
[ "", "java", "c", "random", "porting", "" ]
I have a group of strings in Javascript and I need to write a function that detects if another specific string belongs to this group or not. What is the fastest way to achieve this? Is it alright to put the group of values into an array, and then write a function that searches through the array? I think if I keep the values sorted and do a binary search, it should work fast enough. Or is there some other smart way of doing this, which can work faster?
Use a hash table, and do this: ``` // Initialise the set mySet = {}; // Add to the set mySet["some string value"] = true; ... // Test if a value is in the set: if (testValue in mySet) { alert(testValue + " is in the set"); } else { alert(testValue + " is not in the set"); } ```
You can use an object like so: ``` // prepare a mock-up object setOfValues = {}; for (var i = 0; i < 100; i++) setOfValues["example value " + i] = true; // check for existence if (setOfValues["example value 99"]); // true if (setOfValues["example value 101"]); // undefined, essentially: false ``` This takes advantage of the fact that objects are implemented as associative arrays. How fast that is depends on your data and the JavaScript engine implementation, but you can do some performance testing easily to compare against other variants of doing it. If a value can occur more than once in your set and the "how often" is important to you, you can also use an incrementing number in place of the boolean I used for my example.
fastest way to detect if a value is in a group of values in Javascript
[ "", "javascript", "search", "" ]
I want to know if its possible and how to do the following , i have a basic MVC application (ASP.Net) that i have modified to work for me. Now the application already handles authentication perfectly fine but i need to use this authentication in another app. Without creating a webservice is it possible for me to make calls to the applications authcontroller , if so how
You can't directly call a controller in another application because it is in a separate AppDomain. If you just want to reuse the existing code, you could refactor it into a separate assembly (library project), include that assembly in your new application, and just reference it from your logon controller. If you are trying to do single-sign on, then you may want to look at existing SSO solutions, such as [JA-SIG CAS 2.0](http://www.ja-sig.org/products/cas/).
Authentication is a cross-cutting concern that shouldn't be embedded into a single use case/controller. AOP afficionados would say it should be encapsulated in an aspect.
Make a call to a external mvc controller
[ "", "c#", "asp.net-mvc", "" ]
I'm using this to check for the availability of a URL: ``` $fp = fsockopen($url, 443, $errno, $errstr); ``` and I get this error back... **Warning: fsockopen() [function.fsockopen]: unable to connect to <https://example.com/soapserver.php:443> (Unable to find the socket transport "https" - did you forget to enable it when you configured PHP?) in C:\Home etc etc....** I'm using an IIS server btw,( no its not my doing! ) so I think its something to do with not having open-ssl, but I'm not sure. Can anyone help please? I did a phpinfo() and I do have ssl, but on IMAP and cURL, thats all. Any ideas?
also for ssl you need to prefix the host with ssl://
Uncomment the line: `extension=php_openssl.dll` in `php.ini`
Unable to find the socket transport "https"
[ "", "php", "iis", "fsockopen", "" ]
How can I create a list in C++? I need it to create a linked list. How would I go about doing that? Are there good tutorials or examples I could follow?
I take it that you know that C++ already has a linked list class, and you want to implement your own because you want to learn how to do it. First, read [Why do we use arrays instead of other data structures?](https://stackoverflow.com/questions/392397/arrays-whats-the-point) , which contains a good answer of basic data-structures. Then think about how to model them in C++: ``` struct Node { int data; Node * next; }; ``` Basically that's all you need to implement a list! (a *very* simple one). Yet it has no abstractions, you have to link the items per hand: ``` Node a={1}, b={20, &a}, c={35, &b} d={42, &c}; ``` Now, you have have a linked list of nodes, all allocated on the stack: ``` d -> c -> b -> a 42 35 20 1 ``` Next step is to write a wrapper class `List` that points to the start node, and allows to add nodes as needed, keeping track of the head of the list (the following is very simplified): ``` class List { struct Node { int data; Node * next; }; Node * head; public: List() { head = NULL; } ~List() { while(head != NULL) { Node * n = head->next; delete head; head = n; } } void add(int value) { Node * n = new Node; n->data = value; n->next = head; head = n; } // ... }; ``` Next step is to make the List a template, so that you can stuff other values (not only integers). If you are familiar with smart pointers, you can then replace the raw pointers used with smart pointers. Often i find people recommend smart pointers to starters. But in my opinion you should first understand why you need smart pointers, and then use them. But that requires that you need first understand raw pointers. Otherwise, you use some magic tool, without knowing why you need it.
You should really use the [standard List class](http://en.cppreference.com/w/cpp/container/list). Unless, of course, this is a homework question, or you want to know how lists are implemented by STL. You'll find plenty of simple tutorials via google, like [this one](http://www.mochima.com/tutorials/STL.html). If you want to know how linked lists work "under the hood", try searching for C list examples/tutorials rather than C++.
How could I create a list in c++?
[ "", "c++", "list", "linked-list", "" ]
I've got a structure as follows: ``` typedef struct { std::wstring DevAgentVersion; std::wstring SerialNumber; } DeviceInfo; ``` But when I try to use it I get all sorts of memory allocation errors. If I try to pass it into a function like this: ``` GetDeviceInfo(DeviceInfo *info); ``` I will get a runtime check error complaining that I didn't initialize it before using it, which I seemed to have fixed with: ``` DeviceInfo *info = (DeviceInfo*)malloc(sizeof(DeviceInfo)); ``` But then, in the function, when I try to set either of the structures stings, it complains that I'm trying to access a bad pointer when trying to set a value to the string. What is the best way to initialize this structure (and all of it's internal strings?
You should use `new` instead of `malloc`, to assure the constructor gets called for the `DeviceInfo` and its contained `wstring`s. ``` DeviceInfo *info = new DeviceInfo; ``` In general, it's best to avoid using `malloc` in C++. Also, make sure to `delete` the pointer when you're done using it. Edit: Of course if you only need `info` in the local scope, you shouldn't allocate it on the heap. Just do this instead: ``` DeviceInfo info; // constructed on the stack GetDeviceInfo( &info ); // pass the address of the info ```
std::wstring creates an object, and objects need to be constructed. By using malloc, you bypassed the constructor for your structure, which would include constructors for all the members. The error you're getting is from std::wstring trying to use one of its own members that is still uninitialized. You can use new instead of malloc, but probably the best solution is to use a local temporary variable and pass its address to the function. ``` DeviceInfo info; GetDeviceInfo(&info); ```
Init Structure with std::wstring
[ "", "c++", "string", "structure", "" ]
I'm having an issue with the following code: ``` private void DataPortal_Fetch(TaskCriteria criteria) { using (var ctx = ContextManager<Gimli.Data.GimliDataContext> .GetManager(Database.ApplicationConnection, false)) { this.RaiseListChangedEvents = false; this.IsReadOnly = false; IQueryable<Data.Task> query = ctx.DataContext.Tasks; if (criteria.ReadyForPricing) { query = query.Where(row => row.IsPriced != true); query = query.Where(row => row.Status == (int)TaskStatus.Closed); query = query.Where(row => row.InvoiceId == Guid.Empty); } if (criteria.ReadyForInvoicing) { query = query.Where(row => row.IsPriced == true); query = query.Where(row => row.Status == (int)TaskStatus.Closed); query = query.Where(row => row.InvoiceId == Guid.Empty); } var data = query.Select(row => TaskInfo.FetchTaskInfo(row)); this.AddRange(data); this.IsReadOnly = true; this.RaiseListChangedEvents = true; } } ``` My web application, when it calls this method, always hangs if I don't comment out the following line: ``` query = query.Where(row => row.InvoiceId == Guid.Empty) ``` Any idea why this would be happening?
The following code works ... interestingly enough ... any idea of why? ``` query = query.Where(row => row.InvoiceId == new Guid("00000000-0000-0000-0000-000000000000")); ```
Try changing the code to: ``` query.Where(row => object.Equals(row.InvoiceId, Guid.Empty)) ``` Post back if that helped...
Hanging Linq query with Guid.Empty in the where expression
[ "", "c#", "linq", "linq-to-sql", "csla", "" ]
Checkstyle reports this code as "The double-checked locking idiom is broken", but I don't think that my code actually is affected by the problems with double-checked locking. The code is supposed to create a row in a database if a row with that id doesn't exist. It runs in a multi-threaded environment and I want to avoid the primary-key-exists SQL-exceptions. The pseudo-code: ``` private void createRow(int id) { Row row = dao().fetch(id); if (row == null) { synchronized (TestClass.class) { row = dao().fetch(id); if (row == null) { dao().create(id); } } } } ``` I can agree that it looks like double-checked locking, but I am not using static variables and the code in fetch() and create() is probably too complex to be inlined and put out of order. Am I wrong or checkstyle? :)
Assuming you want that innermost line to read: ``` row = dao().create(id); ``` It's not a classic double-checked lock problem assuming `dao().fetch` is properly mutexed from the create method. **Edit**: (code was updated) The classic problem of a double-checked lock is having a value assigned before initialization occurs where two threads are accessing the same value. Assuming the DAO is properly synchronized and will not return a partially initialized value, this doesn't suffer from the flaws of the double-checked lock idiom.
I think in this case, checkstyle is correct. In your code as presented, consider what would happen if two threads both had `row == null` at the entry to the synchronized block. Thread A would enter the block, and insert the new row. Then after thread A exits the block, thread B would enter the block (because it doesn't know what just happened), and try to insert the same new row again. I see you just changed the code and added a pretty important missing line in there. In the *new* code, you might be able to get away with that, since two threads won't be relying on changes to a shared (static) variable. But you might be better off seeing if your DBMS supports a statement such as `INSERT OR UPDATE`. Another good reason to delegate this functionality to the DBMS is if you ever need to deploy more than one application server. Since `synchronized` blocks don't work across machines, you will have to do something else in that case anyway.
Is this broken double checked locking?
[ "", "java", "synchronization", "locking", "double-checked-locking", "" ]
How do you open a file from a java application when you do not know which application the file is associated with. Also, because I'm using Java, I'd prefer a platform independent solution.
With JDK1.6, the [`java.awt.Desktop`](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html) class can be useful. ``` public static void open(File document) throws IOException { Desktop dt = Desktop.getDesktop(); dt.open(document); } ```
``` File file Desktop.getDesktop().open( file ); ``` Since Java 1.6 Previous to that you could [check this question](https://stackoverflow.com/questions/325299) *Summary* It would look something like this: ``` Runtime.getRuntime().exec( getCommand( file ) ); public String getCommand( String file ){ // Depending on the platform could be //String.format("gnome-open %s", fileName) //String.format("open %s", fileName) //String.format("cmd /c start %s", fileName) // etc. } ```
Open a file with an external application on Java
[ "", "java", "external-application", "" ]
I wrote a google map lookup page. Everthing worked fine until I referenced the page to use a master page. I removed the form tag from the master page as the search button on the map page is a submit button. Everything else on my page appears but the google map div appears with map navigation controls and logo but no map visuals appear. I retested with the previous, non master page version and the map appears correctly. Any thoughts on what I'm missing?
Please view below Code and let me know its useful ... **MasterPage Code ( GMap.master page)** ``` < body onload="initialize()" onunload="GUnload()" > < form id="form1" runat="server" > < div > < asp:contentplaceholder id="ContentPlaceHolder1" runat="server" > < /asp:contentplaceholder > < /div > < /form > < /body > ``` **GMatTest.aspx Page which is used GMap.Master page** ``` < %@ Page Language="C#" MasterPageFile="~/MasterPages/GMap.master" AutoEventWireup="true" CodeFile="GMapTest.aspx.cs" Inherits="GMapTest" Title="Google Map Page" % > < asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server" > < script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=< % = AppConfig.GoogleMapApiKey % >" type="text/javascript" >< /script > < script type="text/javascript" > var map = null; var geocoder = null; var latsgn = 1; var lgsgn = 1; var zm = 0; var marker = null; function initialize() { if (GBrowserIsCompatible()) { var latitude= ""; var longitude= ""; map = new GMap2(document.getElementById("map_canvas")); var center = new GLatLng(0,0); map.setCenter(center, 17); map.addControl(new GLargeMapControl()); map.addControl(new GScaleControl()); map.enableScrollWheelZoom(); map.addControl(new GMapTypeControl()); map.enableDoubleClickZoom(); marker = new GMarker(center,{draggable: true}); geocoder = new GClientGeocoder(); GEvent.addListener(marker, "dragend", function() { var point = marker.getLatLng(); marker.openInfoWindowHtml("Latitude: " + point.y + "< /br > Longitude: " + point.x ); }); GEvent.addListener(marker, "click", function() { var point = marker.getLatLng(); }); map.addOverlay(marker); GEvent.trigger(marker, "click"); if (latitude > 0 && longitude > 0) { } else { showAddress(); } } } ``` Below porsion is continue so please copy it also ``` function showAddress() { var isAddressFound=false; var companyAddress = ''; var address='satyam mall, vastrapur, ahmedabad, gujrat, india'; if (geocoder) { geocoder.getLatLng(address,function(point) { if (!point) { alert(address + " not found"); } else { isAddressFound =true; map.setCenter(point,17); zm = 1; marker.setPoint(point); GEvent.trigger(marker, "click"); } } ); //If address not found then redirect to company address if(!isAddressFound) { geocoder.getLatLng(companyAddress, function(point) { if (!point) { } else { isAddressFound =true; map.setCenter(point,17); zm = 1; marker.setPoint(point); GEvent.trigger(marker, "click"); } } ); } } } < /script > < div id="map_canvas" style="width: 100%; height: 425px" > < /div > < /asp:Content > ```
this is the code i used.it works fine here but whenever i add master page it does not perform any use functionality ``` <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Find latitude and longitude with Google Maps</title> <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAPkZq56tNYNmeuZjNQQ2p3hT0NZP-HbfQNNfWb9Z5SLbjZKYKwBTrGBqtttFmF2d-kWv2B2nqW_NyEQ" type="text/javascript"></script> <script type="text/javascript"> function load() { if (GBrowserIsCompatible()) { var map = new GMap2(document.getElementById("map")); map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); var center = new GLatLng(48.89364, 2.33739); map.setCenter(center, 15); geocoder = new GClientGeocoder(); var marker = new GMarker(center, {draggable: true}); map.addOverlay(marker); document.getElementById("lat").innerHTML = center.lat().toFixed(6); document.getElementById("lng").innerHTML = center.lng().toFixed(6); GEvent.addListener(marker, "dragend", function() { var point = marker.getPoint(); map.panTo(point); document.getElementById("lat").innerHTML = point.lat().toFixed(6); document.getElementById("lng").innerHTML = point.lng().toFixed(6); }); GEvent.addListener(map, "moveend", function() { map.clearOverlays(); var center = map.getCenter(); var marker = new GMarker(center, {draggable: true}); map.addOverlay(marker); document.getElementById("lat").innerHTML = center.lat().toFixed(6); document.getElementById("lng").innerHTML = center.lng().toFixed(6); GEvent.addListener(marker, "dragend", function() { var point =marker.getPoint(); map.panTo(point); document.getElementById("lat").innerHTML = point.lat().toFixed(6); document.getElementById("lng").innerHTML = point.lng().toFixed(6); }); }); } } function showAddress(address) { var map = new GMap2(document.getElementById("map")); map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); if (geocoder) { geocoder.getLatLng( address, function(point) { if (!point) { alert(address + " not found"); } else { document.getElementById("lat").innerHTML = point.lat().toFixed(6); document.getElementById("lng").innerHTML = point.lng().toFixed(6); map.clearOverlays() map.setCenter(point, 14); var marker = new GMarker(point, {draggable: true}); map.addOverlay(marker); GEvent.addListener(marker, "dragend", function() { var pt = marker.getPoint(); map.panTo(pt); document.getElementById("lat").innerHTML = pt.lat().toFixed(6); document.getElementById("lng").innerHTML = pt.lng().toFixed(6); }); GEvent.addListener(map, "moveend", function() { map.clearOverlays(); var center = map.getCenter(); var marker = new GMarker(center, {draggable: true}); map.addOverlay(marker); document.getElementById("lat").innerHTML = center.lat().toFixed(6); document.getElementById("lng").innerHTML = center.lng().toFixed(6); GEvent.addListener(marker, "dragend", function() { var pt = marker.getPoint(); map.panTo(pt); document.getElementById("lat").innerHTML = pt.lat().toFixed(6); document.getElementById("lng").innerHTML = pt.lng().toFixed(6); }); }); } } ); } } </script> </head> <body onload="load()" onunload="GUnload()" > <p>This page uses the Google Maps API to find out accurate geographical coordinates (latitude and longitude) for any place on Earth. <br/>It provides two ways to search, either by moving around the map and zooming in, or by typing an address if the place is unknown.<br/> <i> <p> The default location and address are those of Mondeca office in Paris.<br /> <p><b> Find coordinates by moving around the map</b></p> <p>1. Drag and drop the map to broad location. <br/> 2. Zoom in for greater accuracy. <br/> 3. Drag and drop the marker to pinpoint the place. The coordinates are refreshed at the end of each move. </p> <form action="#" onsubmit="showAddress(this.address.value); return false"> <p> <input type="text" size="60" name="address" value="3 cit&eacute; Nollez Paris France" /> <input type="submit" value="Search!" /> </p> </form> <p align="left"> <table bgcolor="#FFFFCC" width="300"> <tr> <td width="100"><b>Latitude</b></td> <td id="lat"></td> </tr> <tr> <td width="100"><b>Longitude</b></td> <td id="lng"></td> </tr> </table> </p> <p> <div align="center" id="map" style="width: 600px; height: 400px"><br/></div> </p> </body> </html> ```
Google map blank when used with master page
[ "", "c#", "asp.net", "google-maps", "" ]
For the following code: ``` <% foreach (Entities.Core.Location loc in locations){ %> <div class="place_meta"> <img src="~/static/images/stars/star_25_sml.gif" runat="server" class="star_rating"/> </div> <% }; %> ``` I would like to display the star rating image for each location object displayed. However, only the first location object's star rating is displayed. For the rest, the image tag becomes `<img class="star_rating" />` Am I missing anything in the syntax that allows the ability to have controls with runat=server within a foreach on the aspx page? This is with ASP.net 2.0. I could possibly call a function in the codebehind or a display class to absolute map the URL but I am very curious if there is a solution to this problem. Just for clarifications, the path to the image could possibly be different for each location object.
You can't use server controls within an inline loop, because ASP.NET needs to be able to uniquely identify each control to process it. The for... loop prevents this. The easiest and cleanest way is to use a Repeater control and bind your collection to it (in code-behind). Set the URL property in the bind event handler, and maintain a counter variable while binding, to check if you're at the first item or not. Edit: I've played around with this some more, and found that if you assign an ID attribute, all looped instances get the same ID, but ASP.NET only recognizes the first control found. This would be an extremely dirty way to set properties on the first instance only. Please don't write code like this.
Unless you're using MVC, you might find a Repeater Control more useful in this situation. If I remember correctly, you can use a source of data (your *locations* in this instance) and then loop through and set each image.
foreach in ASP.net with nested runat="server"
[ "", "c#", "asp.net", "" ]
We have lots of logging calls in our app. Our logger takes a System.Type parameter so it can show which component created the call. Sometimes, when we can be bothered, we do something like: ``` class Foo { private static readonly Type myType = typeof(Foo); void SomeMethod() { Logger.Log(myType, "SomeMethod started..."); } } ``` As this requires getting the Type object only once. However we don't have any actual metrics on this. Anyone got any idea how much this saves over calling this.GetType() each time we log? (I realise I could do the metrics myself with no big problem, but hey, what's StackOverflow for?)
I strongly suspect that GetType() will take significantly less time than any actual logging. Of course, there's the possibility that your call to Logger.Log won't do any actual IO... I still suspect the difference will be irrelevant though. EDIT: Benchmark code is at the bottom. Results: ``` typeof(Test): 2756ms TestType (field): 1175ms test.GetType(): 3734ms ``` That's calling the method 100 *million* times - the optimisation gains a couple of seconds or so. I suspect the real logging method will have a lot more work to do, and calling that 100 million times will take a lot longer than 4 seconds in total, even if it doesn't write anything out. (I could be wrong, of course - you'd have to try that yourself.) In other words, as normal, I'd go with the most readable code rather than micro-optimising. ``` using System; using System.Diagnostics; using System.Runtime.CompilerServices; class Test { const int Iterations = 100000000; private static readonly Type TestType = typeof(Test); static void Main() { int total = 0; // Make sure it's JIT-compiled Log(typeof(Test)); Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { total += Log(typeof(Test)); } sw.Stop(); Console.WriteLine("typeof(Test): {0}ms", sw.ElapsedMilliseconds); sw = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { total += Log(TestType); } sw.Stop(); Console.WriteLine("TestType (field): {0}ms", sw.ElapsedMilliseconds); Test test = new Test(); sw = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { total += Log(test.GetType()); } sw.Stop(); Console.WriteLine("test.GetType(): {0}ms", sw.ElapsedMilliseconds); } // I suspect your real Log method won't be inlined, // so let's mimic that here [MethodImpl(MethodImplOptions.NoInlining)] static int Log(Type type) { return 1; } } ```
The `GetType()` function is marked with the special attribute `[MethodImpl(MethodImplOptions.InternalCall)]`. This means its method body doesn't contain IL but instead is a hook into the internals of the .NET CLR. In this case, it looks at the binary structure of the object's metadata and constructs a `System.Type` object around it. **EDIT:** I guess I was wrong about something ... I said that: "because `GetType()` requires a new Object to be build" but it seems this is not correct. Somehow, the CLR caches the `Type` and always returns the same object so it doesn't need to build a new Type object. I'm based on the following test: ``` Object o1 = new Object(); Type t1 = o1.GetType(); Type t2 = o1.GetType(); if (object.ReferenceEquals(t1,t2)) Console.WriteLine("same reference"); ``` So, I don't expect much gain in your implementation.
Performance of Object.GetType()
[ "", "c#", ".net", "performance", "" ]
Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application. Users can save "products" in the database and give them names and descriptions, but since the whole site should be localized, i must provide a way of translating theses names and descriptions to the users. Is there a natural way in django to do this? Or do i have to realize it as part of the application (by representing the translations in the datamodel) Thanks, Janosch
I would suggest checking out [django-multilingual](http://code.google.com/p/django-multilingual/). It is a third party app that lets you define translation fields on your models. Of course, you still have to type in the actual translations, but they are stored transparently in the database (as opposed to in static PO files), which is what I believe you are asking about.
I use [django-multilingual](http://code.google.com/p/django-multilingual/) for localize content and [django-localeurl](http://code.google.com/p/django-localeurl/) for choosing language based on url (for example mypage/en/). You can see how multilingua and localeurl work on [JewishKrakow.net](http://www.jewishkrakow.nwt/) page.
How to localize Content of a Django application
[ "", "python", "django", "localization", "internationalization", "" ]
I have an xml in which i have stored some html under comments like this ``` <root> <node> <!-- <a href="mailto:some@one.com"> Mail me </a> --> </node> </root> ``` now in my Transform Xslt code of mine i am giving XPathNavigator which is pointing to node and in xslt i am passing the comment value of as a parameter. assuming $href to be `<a href="mailto:some@one.com"> Mail me </a>` in xslt i am doing `<xsl:value-of select="$href" disable-output-escaping="yes">` but $href is still escaped the result of xslt transformation comes up with < > Does any one know whats wrong with it any help in this regard would be highly appericiated. Thanks Regards Azeem
When part of the comment the node looses its special meaning - thus "href" is not a node so you cannot use it to select stuff. You can select comments like this: ``` <xsl:template match="/"> <xsl:value-of select="/root/node/comment()" disable-output-escaping="yes"/> </xsl:template> ``` This will produce based on your XML input: ``` cristi:tmp diciu$ xsltproc test.xsl test.xml <?xml version="1.0"?> <a href="mailto:some@one.com"> Mail me </a> ```
As diciu mentioned, once commented the text inside is no longer XML-parsed. One solution to this problem is to use a two-pass approach. One pass to take out the commented `<a href=""></a>` node and place it into normal XML, and a second pass to enrich the data with your desired output: `<a href="">Your Text Here</a>`. A second, single-pass approach would be to extract the text you need from the comment (in this case the email address) via a regular expression (or in our case just pulling from the XML), and then create the markup needed around it. ``` <xsl:template match="ahrefmail/comment()"> <xsl:element name="a"> <xsl:attribute name="href" select="../../mail"/> <xsl:attribute name="class" select="'text'"/> <xsl:text>Mail Me!</xsl:text> </xsl:element> </xsl:template> ``` This assumes you already have an [identity template](http://www.xmlplease.com/xsltidentity) in place
XSLT Transformation Problem with disable output escaping
[ "", "c#", "xslt", "escaping", "" ]
I am trying to use onkeypress on an input type="text" control to fire off some javascript if the enter button is pressed. It works on most pages, but I also have some pages with custom .NET controls. The problem is that the .NET submit fires before the onkeypress. Does anybody have an insight on how to make onkeypress fire first? If it helps, here is my javascript: ``` function SearchSiteSubmit(myfield, e) { var keycode; if (window.event) keycode = window.event.keyCode; else if (e) keycode = e.which; else return true; if (keycode == 13) { SearchSite(); return false; } else return true; } ```
How are you assigning the javascript? It should look like: ``` <input id="TextID" type="text" onkeypress="return SearchSiteSubmit('TextID', event)" /> ```
Javascript `OnKeyPress` will always fire first, it's more a case of wether or not it has completed its operation before the page is posted back.. I would say rethink what is going on and where.. What is taking place at the server side?
.NET Submit Fires Before Javascript onKeypress
[ "", ".net", "javascript", "onkeypress", "" ]
You guys were very helpful yesterday. I am still a bit confused here though. I want to make it so that the numbers on the rightmost column are rounded off to the nearest dollar: <http://www.nextadvisor.com/voip_services/voip_calculator.php?monthlybill=50&Submit=Submit> the code for the table looks like this: I want $offer[1,2,3,4,5,6,7]calcsavingsann to be rounded, how can do this? ``` <table width="100%;" border="0" cellspacing="0" cellpadding="0"class="credit_table2" > <tr class="credit_table2_brd"> <td class="credit_table2_brd_lbl" width="100px;">Services:</td> <td class="credit_table2_brd_lbl" width="120px;">Our Ratings:</td> <td class="credit_table2_brd_lbl" width="155px;">Monthly VoIP Bill:</td> <td class="credit_table2_brd_lbl" width="155px;">Annual Savings:</td> </tr> <?php $offer1price="24.99"; $offer2price="20.00"; $offer3price="21.95"; $offer4price="23.95"; $offer5price="19.95"; $offer6price="23.97"; $offer7price="24.99"; $offer1calcsavings= $monthlybill - $offer1price; $offer2calcsavings= $monthlybill - $offer2price; $offer3calcsavings= $monthlybill - $offer3price; $offer4calcsavings= $monthlybill - $offer4price; $offer5calcsavings= $monthlybill - $offer5price; $offer6calcsavings= $monthlybill - $offer6price; $offer7calcsavings= $monthlybill - $offer7price; $monthybill="monthlybill"; $offer1calcsavingsann= $offer1calcsavings * 12; $offer2calcsavingsann= $offer2calcsavings * 12; $offer3calcsavingsann= $offer3calcsavings * 12; $offer4calcsavingsann= $offer4calcsavings * 12; $offer5calcsavingsann= $offer5calcsavings * 12; $offer6calcsavingsann= $offer6calcsavings * 12; $offer7calcsavingsann= $offer7calcsavings * 12; $re=1; $offer ='offer'.$re.'name'; $offername= ${$offer}; while($offername!=""){ $offerlo ='offer'.$re.'logo'; $offerlogo=${$offerlo}; $offerli ='offer'.$re.'link'; $offerlink=${$offerli}; $offeran ='offer'.$re.'anchor'; $offeranchor=${$offeran}; $offerst ='offer'.$re.'star1'; $offerstar=${$offerst}; $offerbot='offer'.$re.'bottomline'; $offerbottomline=${$offerbot}; $offerca ='offer'.$re.'calcsavings'; $offercalcsavings=${$offerca}; $offerpr ='offer'.$re.'price'; $offerprice=${$offerpr}; $offersavann ='offer'.$re.'calcsavingsann'; $offercalcsavingsann=${$offersavann}; echo '<tr > <td > <a href="'.$offerlink.'" target="blank"><img src="http://www.nextadvisor.com'.$offerlogo.'" alt="'.$offername.'" /> </a> </td> <td ><span class="rating_text">Rating:</span> <span class="star_rating1"> <img src="http://www.nextadvisor.com'.$offerstar.'" alt="" /> </span> <br /> <div style="margin-top:5px; color:#0000FF;"> <a href="'.$offerlink.'" target="blank">Go to Site</a> <span style="margin:0px 7px 0px 7px;">|</span><a href="'.$offeranchor.'">Review</a> </div> </td> <td >$'.$offerprice.'</td> <td >$'.$offercalcsavingsann.'</td> </tr>'; $re=$re+1; $offer ='offer'.$re.'name'; $offername= ${$offer}; } ?> </table> ```
Do you want rounded up/down/truncated to the nearest dollar? Here are some suggested functions you can use: **Rounding** [round](http://us.php.net/manual/en/function.round.php) [floor](http://us.php.net/manual/en/function.floor.php) [ceil](http://us.php.net/manual/en/function.ceil.php) **Formatting/Truncating** [sprintf](http://us.php.net/manual/en/function.sprintf.php)
Grepsedawk's answer is good; the only thing I would add is that rather than displaying $336.6, for example, you could could use [number\_format](http://php.net/number_format) to output $336.60. (I know this wasn't your question, but looking at the link, I thought that might be useful for you.) Edit - Thanks to Andy for suggesting [money\_format](http://php.net/money_format) instead.
basic php form help (currency display)
[ "", "php", "forms", "currency", "rounding", "" ]
I find this comes up a lot, and I'm not sure the best way to approach it. **The question I have is how to make the decision between using foreign keys to lookup tables, or using lookup table values directly in the tables requesting it, avoiding the lookup table relationship completely.** Points to keep in mind: * With the second method you would need to do mass updates to all records referencing the data if it is changed in the lookup table. * This is focused more towards tables that have a lot of the column's referencing many lookup tables.Therefore lots of foreign keys means a lot of joins every time you query the table. * This data would be coming from drop down lists which would be pulled from the lookup tables. In order to match up data when reloading, the values need to be in the existing list (*related to the first point*). Is there a best practice here, or any key points to consider?
You can use a lookup table with a VARCHAR primary key, and your main data table uses a FOREIGN KEY on its column, with cascading updates. ``` CREATE TABLE ColorLookup ( color VARCHAR(20) PRIMARY KEY ); CREATE TABLE ItemsWithColors ( ...other columns..., color VARCHAR(20), FOREIGN KEY (color) REFERENCES ColorLookup(color) ON UPDATE CASCADE ON DELETE SET NULL ); ``` This solution has the following advantages: * You can query the color names in the main data table without requiring a join to the lookup table. * Nevertheless, color names are constrained to the set of colors in the lookup table. * You can get a list of unique colors names (even if none are currently in use in the main data) by querying the lookup table. * If you change a color in the lookup table, the change automatically cascades to all referencing rows in the main data table. --- It's surprising to me that so many other people on this thread seem to have mistaken ideas of what "normalization" is. Using a surrogate keys (the ubiquitous "id") has nothing to do with normalization! --- Re comment from @MacGruber: Yes, the size is a factor. In InnoDB for example, every secondary index stores the primary key value of the row(s) where a given index value occurs. So the more secondary indexes you have, the greater the overhead for using a "bulky" data type for the primary key. Also this affects foreign keys; the foreign key column must be the same data type as the primary key it references. You might have a small lookup table so you think the primary key size in a 50-row table doesn't matter. But that lookup table might be referenced by millions or *billions* of rows in other tables! There's no right answer for all cases. Any answer can be correct for different cases. You just learn about the tradeoffs, and try to make an informed decision on a case by case basis.
In cases of simple atomic values, I tend to disagree with the common wisdom on this one, mainly on the complexity front. Consider a table containing hats. You can do the "denormalized" way: ``` CREATE TABLE Hat ( hat_id INT NOT NULL PRIMARY KEY, brand VARCHAR(255) NOT NULL, size INT NOT NULL, color VARCHAR(30) NOT NULL /* color is a string, like "Red", "Blue" */ ) ``` Or you can normalize it more by making a "color" table: ``` CREATE TABLE Color ( color_id INT NOT NULL PRIMARY KEY, color_name VARCHAR(30) NOT NULL ) CREATE TABLE Hat ( hat_id INT NOT NULL PRIMARY KEY, brand VARCHAR(255) NOT NULL, size INT NOT NULL, color_id INT NOT NULL REFERENCES Color(color_id) ) ``` The end result of the latter is that you've added some complexity - instead of: ``` SELECT * FROM Hat ``` You now have to say: ``` SELECT * FROM Hat H INNER JOIN Color C ON H.color_id = C.color_id ``` Is that extra join a huge deal? No - in fact, that's the foundation of the relational design model - normalizing allows you to prevent possible inconsistencies in the data. But every situation like this adds a *little bit* of complexity, and unless there's a good reason, it's worth asking why you're doing it. I consider possible "good reasons" to include: * **Are there other attributes that "hang off of" this attribute?** Are you capturing, say, both "color name" and "hex value", such that hex value is always dependent on color name? If so, then you definitely want a separate color table, to prevent situations where one row has ("Red", "#FF0000") and another has ("Red", "#FF3333"). Multiple correlated attributes are the #1 signal that an entity should be normalized. * **Will the set of possible values change frequently?** Using a normalized lookup table will make future changes to the elements of the set easier, because you're just updating a single row. If it's infrequent, though, don't balk at statements that have to update lots of rows in the main table instead; databases are quite good at that. Do some speed tests if you're not sure. * **Will the set of possible values be directly administered by the users?** I.e. is there a screen where they can add / remove / reorder the elements in the list? If so, a separate table is a must, obviously. * **Will the list of distinct values power some UI element?** E.g. is "color" a droplist in the UI? Then you'll be better off having it in its own table, rather than doing a SELECT DISTINCT on the table every time you need to show the droplist. If none of those apply, I'd be hard pressed to find another (good) reason to normalize. If you just want to make sure that the value is one of a certain (small) set of legal values, you're better off using a CONSTRAINT that says the value must be in a specific list; keeps things simple, and you can always "upgrade" to a separate table later if the need arises.
Decision between storing lookup table id's or pure data
[ "", "sql", "database", "lookup", "database-normalization", "" ]
I am sorry, my question is stupid, but I am not able to answer it, as a java illiterate. I run a tomcat (5) on CentOS5 (for a CAS server), and when I try to open this URL <http://192.168.1.17:8080/cas-server-webapp-3.3.1/login> I get this error : first error: java.lang.NoClassDefFoundError: Could not initialize class **org.springframework.webflow.util.RandomGuid** and root error: org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.springframework.webflow.util.RandomGuid $CLASSPATH is empty, and it seems to be a problem, but I don't know what to put in it. EDIT: Jared is right, my hosts files defined 127.0.0.1 as localhost, and now it work very well!
It is important to keep two or three different exceptions strait in our head in this case: 1. **`java.lang.ClassNotFoundException`** This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath. 2. **`java.lang.NoClassDefFoundError`** This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying again, but we're not even going to try to load it, because we failed loading it earlier. The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem. That being said, another answer poster indicates that the RandomGUID requires a call to InetAddress.getLocalHost(). On many operating systems, this would trigger a host lookup that would use the hosts file (`/etc/hosts` on \*NIX systems, `%WINDOWS%/system32/drivers/etc/HOSTS` on a Windows system.) I have seen similar errors quite frequently when that file incorrectly defines the localhost address. `127.0.0.1` should point to 'localhost' (and probably also `localhost.localdomain`.) It should **NOT** point to the actual host name of the machine (although for some reason, many older RedHat Linux installers liked to set it incorrectly.)
Nowadays, the environment variable $CLASSPATH should not be used; instead, the java application should have the classpath set on the command line. However, in the case of tomcat and libraries used in the webapps, you simply put the JARs (for Spring) into the shared/lib/ folder of the tomcat installation.
Error java.lang.NoClassDefFoundError on org.springframework.webflow.util.RandomGuid
[ "", "java", "linux", "tomcat", "classpath", "centos5", "" ]
i've got a site with a lot of referenced .js-Files; those are rather small files, but I want to keep my methods separated by topic/functionality. Is it better to keep all the methods in one .js-File or is it no problem to have many (~ 20 - 30) small files all including only some lines?
By all means keep them separate for development, but you should consider bundling them together into one file for production. There is a nice discussion at [sitepoint.com](http://www.sitepoint.com/blogs/2007/04/10/faster-page-loads-bundle-your-css-and-javascript/) > For each of these files, an HTTP > request is sent to the server, and > then the browser awaits a response > before requesting the next file. > Limits (or limitations) of the browser > generally prevent parallel downloads. > This means that for each file, you > wait for the request to reach the > server, the server to process the > request, and the reply (including the > file content itself) to reach you. Put > end to end, a few of these can make a > big difference to page load times.
Actually it's a bad idea to have so many referenced files. The basic idea for performance issues is to try to minimize HTTP Requests as much as possible (at least on your production server). Take a look at this <http://developer.yahoo.com/performance/rules.html#num_http>
jQuery/JavaScript - performance-issue when having a lot of small .js-Files?
[ "", "javascript", "jquery", "performance", "include", "jscompress", "" ]
I am building a calculator in C#. I am not sure what the best way is to have it increment a number in an array every time the button is pressed. Here is one of my current button event handler methods: ``` //Assign button '2' to 2 with array address of 1 private void num2_Click(object sender, EventArgs e) { numbers[1] = 2; lblUpdate(1); } ``` I would like it so every time this button is pressed, numbers[1] gets increased by 2. Right now, it just gets set to 2 no matter how many times the button is pressed. Thanks so much!
``` numbers[1] += 2; ```
numbers[1] += 2; That should do the trick.
incrementing array value with each button press?
[ "", "c#", "arrays", "events", "increment", "calculator", "" ]
Or is it okay to do something like this: ``` new Thread( new ThreadStart( delegate { DoSomething(); } ) ).Start(); ``` ? I seem to recall that under such a scenario, the Thread object would be garbage collected, but the underlying OS thread would continue to run until the end of the delegate passed into it. I'm basically looking for ThreadPool functionality, but don't want the threads to be background threads (i.e. I want them to keep the app alive). **Update:** According to Jason, the CLR actually keeps an internal reference to the Thread object, while running, so it won't be garbage collected until the thread exits.
I have generally found that if I need to directly start a new thread the way you are in your example, rather than grabbing one from the thread pool, then it is a long running thread and I will need a reference to it later to kill it, monitor it, etc. For short run threads like invoking IO on a background thread, etc, I always use a thread pool thread (usually indirectly through a someDelete.BeginBlah(...) method call). When using a thread pool thread like this I prefer to NOT keep a reference around. I don't know if another programmer might inappropriately use a reference to that thread. If I don't need a reference, I don't keep it around to clutter up code. **Edit:** To answer your edit about threads being garbage collected, this will not occur while the thread is running. The CLR keeps a reference to every running thread. The object representing the thread will NOT be collected.
It depends. In the situation where the user can cancel the operation of your thread, you should keep the reference so the thread can be canceled when the user want. In other situations, there may be no need to store the reference.
Should one always keep a reference to a running Thread object in C#?
[ "", "c#", "multithreading", "reference", "" ]
How do I get whole and fractional parts from double in JSP/Java ? If the value is 3.25 then I want to get `fractional =.25`, `whole = 3` How can we do this in Java?
<http://www.java2s.com/Code/Java/Data-Type/Obtainingtheintegerandfractionalparts.htm> ``` double num; long iPart; double fPart; // Get user input num = 2.3d; iPart = (long) num; fPart = num - iPart; System.out.println("Integer part = " + iPart); System.out.println("Fractional part = " + fPart); ``` Outputs: ``` Integer part = 2 Fractional part = 0.2999999999999998 ```
``` double value = 3.25; double fractionalPart = value % 1; double integralPart = value - fractionalPart; ```
How do I get whole and fractional parts from double in JSP/Java?
[ "", "java", "math", "jsp", "" ]
I have a cookie which is generated from a servlet and that I would like to be persistent - that is, set the cookie, close down IE, start it back up, and still be able to read the cookie. The code that I'm using is the following: ``` HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance() .getExternalContext().getResponse(); Cookie cookie = new Cookie("someKey", "someValue"); cookie.setMaxAge(7 * 24 * 60 * 60); response.addCookie(cookie); ``` This works great in firefox, but in IE 6/7, the cookie is not saved between browser restarts. I've checked everything that I can think of in my settings, but can't figure out what would be causing the cookie to be deleted. As far as I know, calling setMaxAge with a positive number makes the cookie persistent. Any ideas why this would be going wrong? **Edit** I have verified, using the more info trick suggested by Olaf, that the cookie is attempting to be set as a session cookie, not a persistent cookie; the max age is set to "end of session". So it doesn't seem like the max age is being set for IE - I have verified that in Firefox, the max age is set correctly. I still have no idea what's going on.
I know nothing of Java or servlets, but IE will only persist a cookie if it has an Expires date, setting max-age is not sufficient, IE will continue to treat it as a session cookie.
Few suggestions. 1. Are you using fqdn to access the site? 2. use [fiddler](http://www.fiddlertool.com/fiddler/) to check how does the cookie looks in the http response. 3. Check if other sites on the internet are storing cookies successfully.
Persistent cookies from a servlet in IE
[ "", "java", "internet-explorer", "servlets", "cookies", "" ]
I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone. Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file. Before, there was a ipython2.4 package but it is deprecated.
Ok, I answer my own question : I'm dumb :-) ``` ls /usr/bin/ipython* /usr/bin/ipython /usr/bin/ipython2.4 /usr/bin/ipython2.5 ``` Now it's built-in...
I'm using Ubuntu 10.10 and there's only on ipython installed. (There's also only one python available, but I got an older version with [the deadsnakes ppa](https://launchpad.net/~fkrull/+archive/deadsnakes).) To get ipython2.5, I installed ipython from your virtualenv: ``` virtualenv --python=/usr/bin/python2.5 project_name source project_name/bin/activate pip install ipython ``` Then the ipython version should match the python passed into virtualenv with `--python`.
How to force iPython to use an older version of Python?
[ "", "python", "ipython", "" ]
As a [C#](http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29) developer I'm used to running through constructors: ``` class Test { public Test() { DoSomething(); } public Test(int count) : this() { DoSomethingWithCount(count); } public Test(int count, string name) : this(count) { DoSomethingWithName(name); } } ``` Is there a way to do this in C++? I tried calling the Class name and using the 'this' keyword, but both fail.
**C++11: Yes!** C++11 and onwards has this same feature (called [delegating constructors](https://secure.wikimedia.org/wikipedia/en/wiki/C++11#Object_construction_improvement)). The syntax is slightly different from C#: ``` class Foo { public: Foo(char x, int y) {} Foo(int y) : Foo('a', y) {} }; ``` **C++03: No** Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this: 1. You can combine two (or more) constructors via default parameters: ``` class Foo { public: Foo(char x, int y=0); // combines two constructors (char) and (char, int) // ... }; ``` 2. Use an init method to share common code: ``` class Foo { public: Foo(char x); Foo(char x, int y); // ... private: void init(char x, int y); }; Foo::Foo(char x) { init(x, int(x) + 7); // ... } Foo::Foo(char x, int y) { init(x, y); // ... } void Foo::init(char x, int y) { // ... } ``` See [the C++FAQ entry](https://isocpp.org/wiki/faq/ctors#init-methods) for reference.
Yes and No, depending on which version of C++. In C++03, you can't call one constructor from another (called a delegating constructor). This changed in C++11 (aka C++0x), which added support for the following syntax: (example taken from [Wikipedia](http://en.wikipedia.org/wiki/C%2B%2B11#Object_construction_improvement)) ``` class SomeType { int number; public: SomeType(int newNumber) : number(newNumber) {} SomeType() : SomeType(42) {} }; ```
Can I call a constructor from another constructor (do constructor chaining) in C++?
[ "", "c++", "constructor", "delegates", "" ]
I am working on a C++ project and I noticed that we have a number of warnings about unused parameters. What effect could it have if these warnings are ignored?
The function with an unused parameter may have a real bug in the following cases: 1. There is an **output** parameter, which is not being assigned or written into, resulting in undefined value for the caller. 2. One of parameters is a callback function pointer, which you must invoke and forget to do so. May happen if there is a lot of `#ifdef`s in the function. 3. You declare a local variable with the same name that shadows a parameter and subsequently use the wrong value down in the function. Not using an **input** parameters **may** be harmless, but you can reduce the noise to see useful warnings by marking unused input parameters explicitly in the beginning of the function by casting it to `void` (works for both C and C++): ``` (void)param1; ``` Or, ``` #define UNUSED(expr) do { (void)(expr); } while (0) ... void foo(int param1, int param2) { UNUSED(param2); bar(param1); } ``` Or omit parameter name (C++ only): ``` void foo(int param1, int /*param2*/) { bar(param1); } ```
If you have a whole lot of unimportant warnings that are not important to you, you may overlook the important warning about the line of code that you just wrote that is hiding in the middle of them.
What are the consequences of ignoring: warning: unused parameter
[ "", "c++", "warnings", "" ]
Been thinking, what's the difference between declaring a variable with [] or \* ? The way I see it: ``` char *str = new char[100]; char str2[] = "Hi world!"; ``` .. should be the main difference, though Im unsure if you can do something like ``` char *str = "Hi all"; ``` .. since the pointer should the reference to a static member, which I don't know if it can? Anyways, what's really bugging me is knowing the difference between: ``` void upperCaseString(char *_str) {}; void upperCaseString(char _str[]) {}; ``` So, would be much appreciated if anyone could tell me the difference? I have a hunch that both might be compiled down the same, except in some special cases? Ty
Let's look into it (for the following, note `char const` and `const char` are the same in C++): ## String literals and char \* `"hello"` is an array of 6 const characters: `char const[6]`. As every array, it can convert implicitly to a pointer to its first element: `char const * s = "hello";` For compatibility with C code, C++ allows one other conversion, which would be otherwise ill-formed: `char * s = "hello";` it removes the const!. This is an exception, to allow that C-ish code to compile, but it is deprecated to make a `char *` point to a string literal. So what do we have for `char * s = "foo";` ? `"foo"` -> `array-to-pointer` -> `char const*` -> `qualification-conversion` -> `char *`. A string literal is read-only, and won't be allocated on the stack. You can freely make a pointer point to them, and return that one from a function, *without* crashing :). ### Initialization of an array using a String literal Now, what is `char s[] = "hello";` ? It's a *whole* other thing. That will create an array of characters, and fill it with the String `"hello"`. The literal isn't pointed to. Instead it is copied to the character-array. And the array is created *on the stack*. You cannot validly return a pointer to it from a function. ## Array Parameter types. How can you make your function accept an array as parameter? You just declare your parameter to be an array: ``` void accept_array(char foo[]); ``` but you omit the size. Actually, any size would do it, as it is just ignored: The Standard says that parameters declared in that way will be transformed to be the same as ``` void accept_array(char * foo); ``` ### Excursion: Multi Dimensional Arrays Substitute `char` by any type, including arrays itself: ``` void accept_array(char foo[][10]); ``` accepts a two-dimensional array, whose last dimension has size 10. *The first element of a multi-dimensional array is its first sub-array of the next dimension*! Now, let's transform it. It will be a pointer to its first element again. So, actually it will accept a pointer to an array of 10 chars: (remove the `[]` in head, and then just make a pointer to the type you see in your head then): ``` void accept_array(char (*foo)[10]); ``` As arrays implicitly convert to a pointer to their first element, you can just pass an two-dimensional array in it (whose last dimension size is 10), and it will work. Indeed, that's the case for *any* n-dimensional array, including the special-case of `n = 1`; ## Conclusion ``` void upperCaseString(char *_str) {}; ``` and ``` void upperCaseString(char _str[]) {}; ``` are the same, as the first is just a pointer to char. But note if you want to pass a String-literal to that (say it doesn't change its argument), then you should change the parameter to `char const* _str` so you don't do deprecated things.
The three different declarations let the pointer point to different memory segments: ``` char* str = new char[100]; ``` lets str point to the heap. ``` char str2[] = "Hi world!"; ``` puts the string on the stack. ``` char* str3 = "Hi world!"; ``` points to the data segment. The two declarations ``` void upperCaseString(char *_str) {}; void upperCaseString(char _str[]) {}; ``` are equal, the compiler complains about the function already having a body when you try to declare them in the same scope.
C++ strings: [] vs. *
[ "", "c++", "syntax", "reference", "pointers", "" ]
When we can catch an exception like: `Violation of UNIQUE KEY constraint 'IX_Product'. Cannot insert duplicate key in object 'Product'. (2627)`. The challenge is how to dechiper the Index Name IX\_Product as a Member (i.e. I don't want to substring out the message). There could be more than one unique constraint on a table and we would need to know which one to give more detailed information to the user. It would be preferable to catch it as DbException so it isn't SQL Server specific. Is there a way to get the affected index from the exception without having to parse the string? The only solution I have came up with but I have not tested would to use a stored procedure and trap the error in there and returned the more detailed message from the stored procedure. But I believe this would still have issues.
You'll have to either: 1. code your client component to recognize the constraint names that each insert/update statement might throw exceptions for, 2. rename all your constraints so that they are "decipherable" in the way you want to use them in client code, or... 3. check all the contraints in a stored proc before attempting the insert/update, and throw (Raise) your own custom exception in the proc if the check fails, BEFORE attempting the insert update and letting the contraint create the exception...
uh...maybe i'm missing something obvious...but wouldn't it be a better use of your time to *fix the bug* instead of parsing the exception?
Handling database exceptions in .net
[ "", "c#", "sql-server", "exception", "" ]
I am working on a c++ win32 program that involves a keyboard hook. The application is a win32 project with no user interface whatsoever. I need to keep the application from closing without using causing the hook to not work or use up a bunch of system resources. I used to use a message box but I need the application to be completely invisible. Any help would be appreciated! If you have any questions just ask.
I think what you need is [message only window](http://msdn.microsoft.com/en-us/library/ms632599(VS.85).aspx#message_only) > (***MSDN says***) A message-only window enables you to send and receive messages. It is not visible, has no z-order, cannot be enumerated, and does not receive broadcast messages. The window simply dispatches messages.
Do you really need windows? The [MSDN LowLevelKeyboardProc page](http://msdn.microsoft.com/en-us/library/ms644985%28v=vs.85%29.aspx) recommends using a simple message loop. Just insert this snippet after the hook call. ``` // message loop to keep the keyboard hook running MSG msg; while(GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } ```
keep a formless application from closing for a keyboard hook
[ "", "c++", "winapi", "keyboard", "hook", "" ]
I'm writing a little arcade-like game in C++ (a multidirectional 2d space shooter) and I'm finishing up the collision detection part. Here's how I organized it (I just made it up so it might be a shitty system): Every ship is composed of circular components - the amount of components in each ship is sort of arbitrary (more components, more CPU cycles). I have a maxComponent distance which I calculate upon creation of the ship which is basically the longest line I can draw from the center of the ship to the edge of the furthest component. I keep track of stuff onscreen and use this maxComponentDistance to see if they're even close enough to be colliding. If they are in close proximity I start checking to see if the components of different ships intersect. Here is where my efficiency question comes in. I have a (x,y) locations of the component relative to the ship's center, but it doesn't account for how the ship is currently rotated. I keep them relative because I don't want to have to recalculate components every single time the ship moves. So I have a little formula for the rotation calculation and I return a 2d-vector corresponding to rotation-considerate position relative to the ships center. The collision detection is in the GameEngine and it uses the 2d-vector. My question is about the return types. Should I just create and return a 2d-vector object everytime that function is called or should I give that component object an additional private 2d-vector variable, edit the private variable when the function is called, and return a pointer to that object? I'm not sure about the efficiency of memory allocation vs having a permanent, editable, private variable. I know that memory would also have to be allocated for the private variable, but not every time it was checked for collisions, only when a new component was created. Components are not constant in my environment as they are deleted when the ship is destroyed. That's my main dilemma. I would also appreciate any pointers with the design of my actual collision detection system. It's my first time giving a hack at it (maybe should have read up a bit) Thanks in advance.
You should absolutely try to avoid doing memory allocations for your component-vector on each call to the getter-function. Do the allocation as seldom as possible, instead. For instance, you could do it when the component composition of the ship changes, or even more seldom (by over-allocating). You could of course also investigate memory pools, where you pre-allocate lots of such components and put in a pool, so you can allocate a new component in constant time. As a general (and apologies if it's too obvious) point when doing this kind of collision-detection: square the distances, rather than computing the square roots. :)
If your 2D vector is just: ``` class Vector2D { double x, y; }; ``` Then by all means return it! E.g: ``` Vector2D function( ... ); ``` Or pass by reference: ``` void function( Vector2D * theReturnedVector2D, ... ); ``` **Avoid at all costs:** ``` vector<double> function(...); ``` The constant heap allocation/deallocation inherent to the Vector class is a mistake! --- Copying your own Vector2D class is very cheap, computationally speaking. Unlike Vector<>, your own Vector2D class can incorporate whatever methods you like. I've used this feature in the past to incorporate methods such as distanceToOtherPointSquared(), scanfFromCommandLineArguments(), printfNicelyFormatted(), and operator[](int). --- ***or should I give that component object an additional private 2d-vector variable, edit the private variable when the function is called, and return a pointer to that object?*** Watch out for multiple function calls invalidating previous data. That's a recipe for disaster!
Simple efficiency question C++ (memory allocation)..and maybe some collision detection help?
[ "", "c++", "memory", "performance", "allocation", "" ]
Tried something like this: ``` HttpApplication app = s as HttpApplication; //s is sender of the OnBeginRequest event System.Web.UI.Page p = (System.Web.UI.Page)app.Context.Handler; System.Web.UI.WebControls.Label lbl = new System.Web.UI.WebControls.Label(); lbl.Text = "TEST TEST TEST"; p.Controls.Add(lbl); ``` when running this I get "Object reference not set to an instance of an object." for the last line... How do I get to insert two lines of text (asp.net/html) at specific loactions in the original file? And how do I figure out the extension of the file (I only want to apply this on aspx files...?
I'm not sure, but I don't think you can use an HttpModule to alter the Page's control tree (please correct me if I'm wrong). You CAN modify the HTML markup however, you'll have to write a "response filter" for this. For an example, see <http://aspnetresources.com/articles/HttpFilters.aspx>, or google for "httpmodule response filter".
Its simplier than you think: ``` public void Init(HttpApplication app) { app.PreRequestHandlerExecute += OnPreRequestHandlerExecute; } private void OnPreRequestHandlerExecute(object sender, EventArgs args) { HttpApplication app = sender as HttpApplication; if (app != null) { Page page = app.Context.Handler as Page; if (page != null) { page.PreRender += OnPreRender; } } } private void OnPreRender(object sender, EventArgs args) { Page page = sender as Page; if (page != null) { page.Controls.Clear(); // Or do whatever u want with ur page... } } ``` If the PreRender Event isn't sufficient u can add whatever Event u need in the PreRequestHandlerExecute EventHandler...
HttpModule - get HTML content or controls for modifications
[ "", "c#", "httpmodule", ".net-1.1", "" ]
As a win32 developer moving into web deveopment the last few years, I found the web desktops based on extjs very interesting. [Coolite Desktop](http://examples.coolite.com/Examples/Desktop/Introduction/Overview/Desktop.aspx) (broken) [Extjs Desktop](http://extjs.com/deploy/dev/examples/desktop/desktop.html) [Puppy Web Desktop](http://pupweb.org/desktop/) [Wikipedia list](http://en.wikipedia.org/wiki/Web_desktop) [Lifehack list](http://www.lifehack.org/articles/technology/your-desktop-anywhere-21-web-based-desktops.html) [Windows 3.1 desktop](http://209.213.121.56.nyud.net/) (broken) Do you know about others? Without any experience of developing applications as web desktops (and I am not promoting extjs, only impressed...), I have to say I like the concept. What do you think, is it useful? Edit Dec 30 More about the subject here: [are-webos-practical-yet](https://stackoverflow.com/questions/398915/are-webos-practical-yet)
I find it an interesting experiment, but I don't really find much added value in it. The desktop concept works for an operating system. Most people use one operating system. They are familiar with how it works and what to expect in terms of navigation. That being said, having a desktop at an application (or site) level adds another navigation model that the user must learn. If they are expecting it to be the same at their OS (which it won't likely be), then it can lead to confusion because it doesn't work exactly like what they're used to - although it looks like it *should*.
NO. Also, [Uncanny valley](https://blog.codinghorror.com/avoiding-the-uncanny-valley-of-user-interface/) of UI.
Web desktops - do you find it interesting?
[ "", "javascript", "windows", "" ]
``` class String { private: char* rep; public: String (const char*); void toUpper() const; }; String :: String (const char* s) { rep = new char [strlen(s)+1]; strcpy (rep, s); } void String :: toUpper () const { for (int i = 0; rep [i]; i++) rep[i] = toupper(rep[i]); } int main () { const String lower ("lower"); lower.toUpper(); cout << lower << endl; return 0; } ```
**A const member function, is a member function that does not mutate its member variables.** **const on a member function does not imply const char \*. Which would mean that you can't change the data in the address the pointer holds.** Your example does not mutate the member variables themselves. A const on a member function, will ensure that you treat all of your member variables as const. That means if you have: ``` int x; char c; char *p; ``` Then you will have: ``` const int x; const char c; char * const p; //<-- means you cannot change what p points to, but you can change the data p points to ``` There are 2 types of const pointers. A const member function uses the one I've listed above. --- **A way to get the error you want:** Try changing: ``` char * rep; ``` to: ``` char rep[1024]; ``` And remove this line: ``` rep = new char [strlen(s)+1]; ``` It will throw the error you are expecting (can't modify members because of const keyword) Because there is only 1 type of const array. And that means you cannot modify any of its data. --- Now the whole system is actually broken with the following example: ``` class String { private: char rep2[1024]; char* rep; ... String :: String (const char* s) { rep = rep2; strcpy (rep, s); } ``` **So the lesson to learn here is that the const keyword on member functions does not ensure that your object will not change at all.** It only ensures that each member variable will be treated as const. And for pointers, there is a big diff between const char \* and char \* const. Most of the time a const member function will mean that the member function will not modify the object itself, but this is not always the case, as the above example shows.
The reason is that you don't change `rep`. If you would, you would find `rep = ...;` somewhere in your code. This is the difference between ``` char*const rep; ``` and ``` const char* rep; ``` In your case, the first one is done if you execute a const member-function: The pointer is const. So, you won't be able to reset the pointer. But you will very well be able to change what the pointer points to. Now, remember `rep[i] = ...;` is the same as `*(rep + i) = ...;`. Thus, what you change is not the pointer, but what the pointer *points to*. You are allowed, since the pointer is not of the second case type. **Solution** 1. The const meaning you are looking at is `physical constness`. However, a const member-function means your object is `logical const`. If a change to some content will change the *logical constness* of your object, for example if it changes some static variable that your object depends upon, your compiler cannot know that your class now has another logical value. And neither it can know that the logical value changes dependent on what a pointer points to: The compiler doesn't try to check logical constness in a const member function, since it cannot know what those member variables mean. This stuff is termed `const-correctness`. 2. Use an object that is not just a reference or a pointer: A const member function will make that object const, and will disallow you to change its content. `std::string`, as proposed by some, or an array of characters (note that an array *will* disallow you changing its content, as opposed to just a pointer), would be an appropriate choice. 2.
Why does this const member function allow a member variable to be modified?
[ "", "c++", "constants", "" ]
My code is built to multiple .dll files, and I have a template class that has a static member variable. I want the same instance of this static member variable to be available in all dlls, but it doesn't work: I see different instance (different value) in each of them. When I don't use templates, there is no problem: initialize the static member in one of the source files, and use \_\_declspec(dllexport) and \_\_declspec(dllimport) directives on the class. But it doesn't work with templates. Is there any way to make it work? I saw some proposed solutions that use "extern", but I think I can't use it because my code is supposed to work with visual studio 2002 and 2005. Thank you. Clarification: I want to have a different instance of static variable per each different type of template instantiation. But if I instantiate the template with the same type in 2 different dlls, I want to have the same variable in the both of them.
Create template specialization and then export the static members of the specialization.
There exists the following solution, as well: * in the **library**: explicitly instantiate some template specialization and share them with dllexport * in the **main program**: + if the specialization is available it will be used from the library + if the specialization is not available it is compiled in the main program The desciption in detail how you can do this: [Anteru's blog Explicit template instantiation](http://anteru.net/2008/11/19/318/)
Static member variable in template, with multiple dlls
[ "", "c++", "dll", "visual-studio-2005", "static", "templates", "" ]
I have a business case whereby I need to be able to specify my own calling convention when using P/Invoke. Specifically, I have a legacy dll which uses a non-standard ABI, and I need to able to specify the calling convention for each function. For example, one function in this dll accepts its first two arguments via EAX and EBX, with the rest via stack. Another function accepts one argument via ECX, with the rest on the stack. I have a few hundred of these functions, and would like to avoid writing my own intermediate bridge DLL in order to access these functions. My other option would be to hand-roll my own custom P/Invoke, which is undesirable for obvious reasons. Any help is appreciated, thanks,
I don't understand what you mean with custom P/Invoke, but I can't see how you could get away without non-managed C++ with inline assembly. However, since almost everything is passed as 32-bit values, you might get away with writing only one proxy for each function signature, as apposed to one per function. Or you could write a code generator which generates proxies from XML. I can't see this version being too undesirable though, since all proxy functions will be really simple: ``` int RealFunction(int param1, const char * param2, char param 3); int MyFunction(int param1, int param2, int param3) { // argument types do not matter as long as they are not doubles or structures __asm { mov eax, param1 mov ebx, param2 push param3 call RealFunction ; depending on calling convention, you might need to do add esp, 12 here ; if RealFunction does not return its result in eax, you will need to do mov eax, <wherever the return value is> here } } ```
I'm fairly certain there is no builtin way of accomplishing what you want without a separate dll. I've not seen a way to specify a calling convention other than what the runtime system supports.
Custom calling convention for P/Invoke and C#
[ "", "c#", "pinvoke", "calling-convention", "" ]
I'm planning to develop a web-services (SOAP to C++ client) in Java with Metro/Hibernate and front it up with a web-site written in JRuby on Rails, connecting Java modules through JRuby and generally through a database. I already wrote some code and set up everything. Now, I've heard that .NET 3.5 is really powerful and after some reading I acknowledged that to be true. However, would it make sense to drop this monstrous yet curious hybrid of Java and RoR to switch everything to .NET? Everything: services, database connection (linq for objects), web-front, ajax stuff -- everything in one huge .NET 3.5 solution. I am also looking to have fun but not as much fun as, say, in C++ for server-side :) I know that with the power of RoR it doesn't really matter whether it's either side. However, whether I'm all set up for .NET or Java, I still have the feeling I'm doing it wrong and I should just switch to the not-side-I'm-currently-on. I have a very limited experience with web development, I've only written an ASP.NET web-service once and supported Java web-service so I have a real OCD with the choice of platforms here.
I'm sorry, but what you are doing sounds like a big ball o' mud. Doesn't matter to me what path you take, but I'd simplify the architecture by reducing the number of technologies/frameworks that you are using. If you can find a way to do it in Ruby/Rails without reference to Java (although you may need to keep the C++ client-side), that would work. Obviously, working in .NET (my preferred platform) is another choice. Windows Communication Foundation makes it much easier to write web services that are lighter weight than the old ASP.NET web services -- including RESTful web services using JSON. If I were doing it today I'd use ASP.NET MVC for the web front-end, WCF (for web services), and either eliminate the C++ client or consider writing it in C# with .NET or Mono.
.NET 3.5 is loads of fun (among mainstream platforms), but in my personal opinion Ruby is as much fun as if not more fun than .NET 3.5. About the capabilities, they are also roughly equivalent, you certainly can make a SOAP web services application in both without problems. About the "monstrous hybrid", there's no such thing, it's just a (very active) port, like IronRuby or IronPython in .NET land. There will be more of a coherent whole if you stick in .NET and write in, say, C# than if you mix and match Ruby and Java, of course. But you certainly can use only JRuby. Given that the fun and capability factors are more or less equal, I'd pick JRuby, just in case I happen to have to deploy on Linux, Solaris or something that's not Windows in the future. If you are certain you'll want to stick to Windows forever, then pick whatever's most fun for you.
Java/JRuby on Rails vs .NET 3.5... feel like I'm doing it wrong
[ "", "java", ".net", "ruby-on-rails", "jruby", "" ]
Is there a Php function to determine if a string consist of only ASCII alphanumerical characters? Note: I'm sorry if the question sounds dumb to some, but I couldn't easily find such a function in the Php manual.
Try [ctype\_alnum](https://www.php.net/manual/en/function.ctype-alnum.php)
``` preg_match('/^[a-z0-9]+$/i', $str); ``` Edit: John T's answer is better. Just providing another method.
Php function to determine if a string consist of only alphanumerical characters?
[ "", "php", "string", "" ]
The following event can possibly get called hundreds of times a frame. ``` public bool OnCollision(Body body1, Body body2) { if(body2.Tag is Dog) ((Dog)body2.Tag).Bark(); } ``` I understand that using "is" causes a cast to be made and then when i want to do something with it, cast it a second time. Is there a more efficient way to check the type? I made a console app trying "if(body2.Tag.GetType() == typeOf(Dog))" but it appears to be even slower than using "is". Thanks.
``` if(body2.Tag is Dog) ``` is actually compiled as ``` Dog Temp = body2.Tag as Dog; if (temp != null) ``` In your code, you're then doing the cast again. Better would be: ``` Dog dog = body2.Tag as Dog; if (dog != null) { dog.Bark(); } ```
I would just make an abstract method on the Body object called Collided: ``` abstract class Body { abstract void Collision(Body other); } class Dog : Body { public override void Collision(Body other) { this.Bark(); } public void Bark() { ... } } ``` Then in your collision function just call Collision on the involved bodies. ``` public bool OnCollision(Body body1, Body body2) { body2.Collision(body2); } ``` This way any type of body can do whatever it needs when a collision happens, you could even optimize this to keep track of which bodies have been notified of collisions with eachother and reduce the number of function calls that you have to execute: ``` public bool OnCollision(Body body1, Body body2) { // Record that these two objects have been notified of a collision // then when these same objects are the only two operands in subsequent calls // you can just short circuit the calls. if(!AlreadyNotifiedOfCollision(body1, body2)) { body1.Collision(body2); body2.Collision(body1); NotifiedOfCollision(body1, body2); } } ``` Of course empirical testing would have to be done to validate that this check is faster than actually just doing the call twice...
Fastest Type Comparison?
[ "", "c#", "types", "xna", "" ]
I have a problem with the [`jquery-ui dialog box`](https://jqueryui.com/dialog/). **The problem is that when I close the dialog box and then I click on the link that triggers it, it does not pop-up again unless I refresh the page.** How can I call the dialog box back without refreshing the actual page. Below is my code: ``` $(document).ready(function() { $('#showTerms').click(function() { $('#terms').css('display','inline'); $('#terms').dialog({ resizable: false, modal: true, width: 400, height: 450, overlay: { backgroundColor: "#000", opacity: 0.5 }, buttons:{ "Close": function() { $(this).dialog("close"); } }, close: function(ev, ui) { $(this).remove(); }, }); }); ``` Thanks
I solved it. I used destroy instead close function (it doesn't make any sense), but it worked. ``` $(document).ready(function() { $('#showTerms').click(function() { $('#terms').css('display','inline'); $('#terms').dialog({resizable: false, modal: true, width: 400, height: 450, overlay: { backgroundColor: "#000", opacity: 0.5 }, buttons:{ "Close": function() { $(this).dialog('**destroy**'); } }, close: function(ev, ui) { $(this).close(); }, }); }); $('#form1 input#calendarTEST').datepicker({ dateFormat: 'MM d, yy' }); }); ```
You're actually supposed to use `$("#terms").dialog({ autoOpen: false });` to initialize it. Then you can use `$('#terms').dialog('open');` to open the dialog, and `$('#terms').dialog('close');` to close it.
jQuery UI Dialog Box - does not open after being closed
[ "", "javascript", "jquery", "jquery-ui", "modal-dialog", "jquery-ui-dialog", "" ]
I'm about to put my head thru this sliding glass door. I can't figure out how to execute the following code in VB.NET to save my life. ``` private static void InitStructureMap() { ObjectFactory.Initialize(x => { x.AddRegistry(new DataAccessRegistry()); x.AddRegistry(new CoreRegistry()); x.AddRegistry(new WebUIRegistry()); x.Scan(scanner => { scanner.Assembly("RPMWare.Core"); scanner.Assembly("RPMWare.Core.DataAccess"); scanner.WithDefaultConventions(); }); }); } ```
At the moment, it's simply not possible. The current version of VB does not support multiline (or statement) lambdas. Each lambda can only comprise one single expression. The next version of VB will fix that (there simply wasn't enough time in the last release). In the meantime, you'll have to make do with a delegate: ``` Private Shared Sub Foobar(x As IInitializationExpression) x.AddRegistry(New DataAccessRegistry) x.AddRegistry(New CoreRegistry) x.AddRegistry(New WebUIRegistry) x.Scan(AddressOf Barfoo) End Sub Private Shared Sub Barfoo(ByVal scanner As IAssemblyScanner) scanner.Assembly("RPMWare.Core") scanner.Assembly("RPMWare.Core.DataAccess") scanner.WithDefaultConventions End Sub ' … ' ObjectFactory.Initialize(AddressOf Foobar) ```
You can see another approach at: <http://blogs.lessthandot.com/index.php/DesktopDev/MSTech/structuremap-is-way-cool-even-in-vb-net>
How to convert C# StructureMap initialization to VB.NET?
[ "", "c#", "vb.net", "structuremap", "" ]
It's quite possible a question like this has been asked before, but I can't think of the terms to search for. I'm working on a photo gallery application, and want to display 9 thumbnails showing the context of the current photo being shown (in a 3x3 grid with the current photo in the centre, unless the current photo is in the first 4 photos being shown, in which case if e.g. if the current photo is the 2nd I want to select photos 1 through 9). For example, given an album containing the list of photos with ids: 1, 5, 9, 12, 13, 18, 19, 20, 21, 22, 23, 25, 26 If the current photo is 19, I want to also view: 9, 12, 13, 18, 19, 20, 21, 22, 23 If the current photo is 5, I want to also view: 1, 5, 9, 12, 13, 18, 19, 20, 21 I've been thinking of something along the lines of: ``` SELECT * FROM photos WHERE ABS(id - currentphoto) < 5 ORDER BY id ASC LIMIT 25 ``` but this doesn't work in the case where the ids are non-sequential (as in the example above), or for the case where there are insufficient photos before the currentphoto. Any thoughts? Thanks, Dom p.s. Please leave a comment if anything is unclear, and I'll clarify the question. If anyone can think of a more useful title to help other people find this question in future, then please comment too.
Probably could just use a UNION, and then trim off the extra results in the procedural code that displays the results (as this will return 20 rows in the non-edge cases): ``` (SELECT * FROM photos WHERE ID < #current_id# ORDER BY ID DESC LIMIT 10) UNION (SELECT * FROM photos WHERE ID >= #current_id# ORDER BY ID ASC LIMIT 10) ORDER BY ID ASC ``` EDIT: Increased limit to 10 on both sides of the UNION, as suggested by **le dorfier**. EDIT 2: Modified to better reflect final implementation, as suggested by Dominic.
If you are using SQL Server, you can use the row\_number() function to give you the row order index and do something like this: ``` declare @selected_photo integer; set @selected_photo = 5; declare @buffer_size integer; set @buffer_size = 2; select ph.rownum, ph.id from (select row_number() over (order by Id) as rownum, * from Photos) as ph where ph.rownum between case when @selected_photo - @buffer_size < 1 then 1 else @selected_photo - @buffer_size end and @selected_photo + @buffer_size ``` Edit: Here is an article on simulating the row\_number() function in MySQL, combining that with this might get you what you need - I'd try it but don't have a MySQL db handy to play with at work. :-) <http://www.xaprb.com/blog/2006/12/02/how-to-number-rows-in-mysql/>
SQL Selecting "Window" Around Particular Row
[ "", "sql", "mysql", "" ]
Earlier I asked a question about [why I see so many examples use the `var`keyword](https://stackoverflow.com/questions/335682/mvc-examples-use-of-var) and got the answer that while it is only necessary for anonymous types, that it is used nonetheless to make writing code 'quicker'/easier and 'just because'. Following [this link ("C# 3.0 - Var Isn't Objec")](http://www.interact-sw.co.uk/iangblog/2005/09/23/varisntobject) I saw that `var` gets compiled down to the correct type in the IL (you will see it about midway down article). My question is how much more, if any, IL code does using the `var` keyword take, and would it be even close to having a measurable level on the performance of the code if it was used everywhere?
There's no extra Intermediate language (IL) code for the `var` keyword: the resulting IL should be identical for non-anonymous types. If the compiler can't create that IL because it can't figure out what type you intended to use, you'll get a compiler error. The only trick is that `var` will infer an exact type where you may have chosen an Interface or parent type if you were to set the type manually.
As Joel says, the compiler works out at *compile-time* what type var should be, effectively it's just a trick the compiler performs to save keystrokes, so for example ``` var s = "hi"; ``` gets replaced by ``` string s = "hi"; ``` *by the compiler* before any IL is generated. The Generated IL will be *exactly* the same as if you'd typed string.
Will using 'var' affect performance?
[ "", "c#", "performance", "variables", "var", "" ]
I have been given a DLL ("InfoLookup.dll") that internally allocates structures and returns pointers to them from a lookup function. The structures contain string pointers: ``` extern "C" { struct Info { int id; char* szName; }; Info* LookupInfo( int id ); } ``` In C#, how can I declare the structure layout, declare the Interop call, and (assuming a non-null value is returned) utilize the string value? In other words, how do I translate the following into C#? ``` #include "InfoLookup.h" void foo() { Info* info = LookupInfo( 0 ); if( info != 0 && info->szName != 0 ) DoSomethingWith( info->szName ); // NOTE: no cleanup here, the DLL is caching the lookup table internally } ```
Try the following layout. Code automatically generated using the [PInvoke Interop Assistant](http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120). Hand coded LookpInfoWrapper() ``` [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct Info { /// int public int id; /// char* [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] public string szName; } public partial class NativeMethods { /// Return Type: Info* ///id: int [System.Runtime.InteropServices.DllImportAttribute("InfoLookup.dll", EntryPoint="LookupInfo")] public static extern System.IntPtr LookupInfo(int id) ; public static LoopInfoWrapper(int id) { IntPtr ptr = LookupInfo(id); return (Info)(Marshal.PtrToStructure(ptr, typeof(Info)); } } ```
For an example, see this [netapi32.NetShareAdd](http://www.pinvoke.net/default.aspx/netapi32.NetShareAdd) interop declaration. It includes a `SHARE_INFO_502` structure, with a `public string shi502_netname` member. Many more examples are available at [Pinvoke.net](http://www.pinvoke.net/).
In C#, how do I invoke a DLL function that returns an unmanaged structure containing a string pointer?
[ "", "c#", "interop", "" ]
What's a surefire way of detecting whether a user has Firebug enabled?
# Original answer: Check for the `console` object (created only with Firebug), like such: ``` if (window.console && window.console.firebug) { //Firebug is enabled } ``` --- # Update (January 2012): The Firebug developers have [decided to remove `window.console.firebug`](http://code.google.com/p/fbug/issues/detail?id=4772). You can still detect the presence of Firebug by [duck typing](http://en.wikipedia.org/wiki/Duck_typing) like ``` if (window.console && (window.console.firebug || window.console.exception)) { //Firebug is enabled } ``` or [various other approaches](http://code.google.com/p/fbug/issues/detail?id=4772#c8) like ``` if (document.getUserData('firebug-Token')) ... if (console.log.toString().indexOf('apply') != -1) ... if (typeof console.assert(1) == 'string') ... ``` but in general, there should be no need to actually do so.
If firebug is enabled, window.console will not be undefined. console.firebug will return the version number.
Javascript that detects Firebug?
[ "", "javascript", "firebug", "" ]
Can anyone point me in the right direction how to configure Visual Studio 2005 with our C++ console project how we can include a 'File Version' in the details section of the file properties. I've tried resource files without any luck. This is with a C++ project just for clarification, and big thank you for the guys you responded with C# suggestions. Thanks in advance.
If you are talking about unmanaged c++, you need to add a version resource to the project. right-click on the project, choose add - Resource.... Choose Version and press new. There you can enter all info you need.
You have to have one `VS_VERSION_INFO` section in your resource (\*.rc) file(s) that compile into your project. In the Visual Studio 2005 Solution Explorer, open the context menu on your C++ project and choose Add, Resource. Mark Version and click "New". Fill in the fields as desired and save the file. Build. Now your project output has a FileInfo resource. Please be aware that Windows Vista does not show all available version info in the Explorer context menu's "Details" tab.
Setting file version number in Visual Studio 2005 C++
[ "", "c++", "visual-studio", "visual-c++-2005", "" ]
What's the most efficient way to calculate the last day of the prior quarter? Example: given the date 11/19/2008, I want to return 9/30/2008. Platform is SQL Server
If @Date has the date in question ``` Select DateAdd(day, -1, dateadd(qq, DateDiff(qq, 0, @Date), 0)) ``` EDIT: Thanks to @strEagle below, simpler still is: ``` Select dateadd(qq, DateDiff(qq, 0, @Date), -1) ```
Actually simpler is: ``` SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), -1) ```
Calculate the last day of the prior quarter
[ "", "sql", "sql-server", "date", "" ]
Is it possible to create a parameterized SQL statement that will taken an arbitrary number of parameters? I'm trying to allow users to filter a list based on multiple keywords, each separated by a semicolon. So the input would be something like "Oakland;City;Planning" and the WHERE clause would come out something equivalent to the below: ``` WHERE ProjectName LIKE '%Oakland%' AND ProjectName Like '%City%' AND ProjectName Like '%Planning%' ``` It's really easy to create such a list with concatenation, but I don't want to take that approach because of the SQL injection vulnerabilities. What are my options? Do I create a bunch of parameters and hope that users never try to use more parameters that I've defined? Or is there a way to create parameterized SQL on the fly safely? Performance isn't much of an issue because the table is only about 900 rows right now, and won't be growing very quickly, maybe 50 to 100 rows per year.
A basic proof-of-concept... Actual code would be less, but since I don't know your table/field names, this is the full code, so anyone can verify it works, tweak it, etc. ``` --Search Parameters DECLARE @SearchString VARCHAR(MAX) SET @SearchString='Oakland;City;Planning' --Using your example search DECLARE @Delim CHAR(1) SET @Delim=';' --Using your deliminator from the example --I didn't know your table name, so I'm making it... along with a few extra rows... DECLARE @Projects TABLE (ProjectID INT, ProjectName VARCHAR(200)) INSERT INTO @Projects (ProjectID, ProjectName) SELECT 1, 'Oakland City Planning' INSERT INTO @Projects (ProjectID, ProjectName) SELECT 2, 'Oakland City Construction' INSERT INTO @Projects (ProjectID, ProjectName) SELECT 3, 'Skunk Works' INSERT INTO @Projects (ProjectID, ProjectName) SELECT 4, 'Oakland Town Hall' INSERT INTO @Projects (ProjectID, ProjectName) SELECT 5, 'Oakland Mall' INSERT INTO @Projects (ProjectID, ProjectName) SELECT 6, 'StackOverflow Answer Planning' --*** MAIN PROGRAM CODE STARTS HERE *** DECLARE @Keywords TABLE (Keyword VARCHAR(MAX)) DECLARE @index int SET @index = -1 --Each keyword gets inserted into the table --Single keywords are handled, but I did not add code to remove duplicates --since that affects performance only, not the result. WHILE (LEN(@SearchString) > 0) BEGIN SET @index = CHARINDEX(@Delim , @SearchString) IF (@index = 0) AND (LEN(@SearchString) > 0) BEGIN INSERT INTO @Keywords VALUES (@SearchString) BREAK END IF (@index > 1) BEGIN INSERT INTO @Keywords VALUES (LEFT(@SearchString, @index - 1)) SET @SearchString = RIGHT(@SearchString, (LEN(@SearchString) - @index)) END ELSE SET @SearchString = RIGHT(@SearchString, (LEN(@SearchString) - @index)) END --This way, only a project with all of our keywords will be shown... SELECT * FROM @Projects WHERE ProjectID NOT IN (SELECT ProjectID FROM @Projects Projects INNER JOIN @Keywords Keywords ON CHARINDEX(Keywords.Keyword,Projects.ProjectName)=0) ``` I decided to mix a few different answers together into one :-P This assumes you'll pass in a delimited string list of search keywords (passed in via @SearchString) as a **VARCHAR(MAX)**, which -- realistically -- **you won't run into a limit on for keyword searches**. Each keyword is broken down from the list and **added into a keyword table.** You'd probably want to add code to remove out duplicate keywords, but it won't hurt in my example. Just slightly less effective, since we only need to evaluate once per keyword, ideally. From there, **any keyword that isn't a part of the project name removes that project from the list**... So searching for "Oakland" gives 4 results but "Oakland;City;Planning" gives only 1 result. You can also change the delimiter, so instead of a semi-colon, it can use a space. Or whatever floats your boat... Also, because of the joins and what not instead of Dynamic SQL, it doesn't run the risk of SQL Injection like you were worried about.
You might also want to consider Full Text Search and using `CONTAINS` or `CONTAINSTABLE` for a more "natural" search capability. May be overkill for 1K rows, but it is written and is not easily subverted by injection.
Using an arbitrary number of parameters in T-SQL
[ "", "sql", "sql-server", "t-sql", "" ]
Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point. How can you determine if another point c is on the line segment defined by a and b? I use python most, but examples in any language would be helpful.
Check if the **cross product** of (b-a) and (c-a) is 0, as tells Darius Bacon, tells you if the points a, b and c are aligned. But, as you want to know if c is between a and b, you also have to check that the **dot product** of (b-a) and (c-a) is *positive* and is *less* than the square of the distance between a and b. In non-optimized pseudocode: ``` def isBetween(a, b, c): crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y) # compare versus epsilon for floating point values, or != 0 if using integers if abs(crossproduct) > epsilon: return False dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y) if dotproduct < 0: return False squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y) if dotproduct > squaredlengthba: return False return True ```
Here's how I'd do it: ``` def distance(a,b): return sqrt((a.x - b.x)**2 + (a.y - b.y)**2) def is_between(a,c,b): return distance(a,c) + distance(c,b) == distance(a,b) ```
How can you determine a point is between two other points on a line segment?
[ "", "python", "math", "geometry", "" ]
Let's say I have my pizza application with Topping and Pizza classes and they show in Django Admin like this: ``` PizzaApp - Toppings >>>>>>>>>> Add / Change Pizzas >>>>>>>>>> Add / Change ``` But I want them like this: ``` PizzaApp - Pizzas >>>>>>>>>> Add / Change Toppings >>>>>>>>>> Add / Change ``` How do I configure that in my `admin.py`?
This is actually covered at the very bottom of [Writing your first Django app, part 7](https://docs.djangoproject.com/en/3.0/intro/tutorial07/). Here's the relevant section: > **Customize the admin index page** > > On a similar note, you might want to > customize the look and feel of the > Django admin index page. > > By default, it displays all the apps > in INSTALLED\_APPS that have been > registered with the admin application, > in alphabetical order. You may want to > make significant changes to the > layout. After all, the index is > probably the most important page of > the admin, and it should be easy to > use. > > The template to customize is > admin/index.html. (Do the same as with > admin/base\_site.html in the previous > section -- copy it from the default > directory to your custom template > directory.) Edit the file, and you'll > see it uses a template variable called > app\_list. That variable contains every > installed Django app. Instead of using > that, you can hard-code links to > object-specific admin pages in > whatever way you think is best.
A workaround that you can try is tweaking your models.py as follows: ``` class Topping(models.Model): . . . class Meta: verbose_name_plural = "2. Toppings" class Pizza(models.Model): . . . class Meta: verbose_name_plural = "1. Pizzas" ``` Not sure if it is against the django's best practices but it works (tested with django trunk). Good luck! PS: sorry if this answer was posted too late but it can help others in future similar situations.
Ordering admin.ModelAdmin objects in Django Admin
[ "", "python", "django", "django-admin", "django-apps", "django-modeladmin", "" ]
I have a table with the following columns: ``` A B C --------- 1 10 X 1 11 X 2 15 X 3 20 Y 4 15 Y 4 20 Y ``` I want to group the data based on the B and C columns and count the distinct values of the A column. But if there are two ore more rows where the value on the A column is the same I want to get the maximum value from the B column. If I do a simple group by the result would be: ``` B C Count -------------- 10 X 1 11 X 1 15 X 1 20 Y 2 15 Y 1 ``` What I want is this result: ``` B C Count -------------- 11 X 1 15 X 1 20 Y 2 ``` Is there any query that can return this result. Server is SQL Server 2005.
I like to work in steps: first get rid of duplicate A records, then group. Not the most efficient, but it works on your example. ``` with t1 as ( select A, max(B) as B, C from YourTable group by A, C ) select count(A) as CountA, B, C from t1 group by B, C ```
I have actually tested this: ``` SELECT MAX( B ) AS B, C, Count FROM ( SELECT B, C, COUNT(DISTINCT A) AS Count FROM t GROUP BY B, C ) X GROUP BY C, Count ``` and it gives me: ``` B C Count ---- ---- -------- 15 X 1 15 y 1 20 y 2 ```
SQL grouping
[ "", "sql", "sql-server", "sql-server-2005", "grouping", "" ]
I wanted to see what folks thought were the best way to help junior members gain confidence in their ability to refactor code. I find that often junior developers simply follow the existing patterns and sense an aversion to break anything due to the perceived risk. I am trying to get them to look at the requirements (new and existing) and have the code map onto the domain model versus "tweaking" or "bending" the existing code base to support new functionality. Just wanted to see if there were any folks who have success here. We are currently thinking about pushing more pair programming, TDD, code reviews etc., but wanted to check if there were other success stories...
The only reliable answer will be unit tests IMHO. Not necessarily TDD -- just get them to write tests for the existing methods/classes they want to refactor, make sure they're doing what they're doing, then allow them to refactor like crazy while relying on the tests to make sure the methods are still valid. The confidence level and flexibility unit tests allow are immensely valuable in these kinds of activities.
It seems that **pair programming with a senior developer in combination with writing tests** would be the optimal situation. If the more experienced developer in the pair is leading, the testing will just be part of it. Writing tests alone leaves room for improvement. Writing tests in a pair environment is the best of both worlds and therefore should build the confidence quicker.
How can I help junior members gain confidence in their ability to refactor code?
[ "", "c#", "refactoring", "" ]
I've just done a test with bitfields, and the results are surprising me. ``` class test1 { public: bool test_a:1; bool test_b:1; bool test_c:1; bool test_d:1; bool test_e:1; bool test_f:1; bool test_g:1; bool test_h:1; }; class test2 { public: int test_a:1; int test_b:1; int test_c:1; int test_d:1; int test_e:1; int test_f:1; int test_g:1; int test_h:1; }; class test3 { public: int test_a:1; bool test_b:1; int test_c:1; bool test_d:1; int test_e:1; bool test_f:1; int test_g:1; bool test_h:1; }; ``` The results were:- ``` sizeof(test1) = 1 // This is what I'd expect. 8 bits in a byte sizeof(test2) = 4 // Reasonable. Maybe padded out to the size of an int. sizeof(test3) = 16 // What??? ``` Is this what you'd expect, or a compiler bug? (Codegear C++ Builder 2007, btw...)
your compiler has arranged all of the members of test3 on integer size boundaries. Once a block has been used for a given type (integer bit-field, or boolean bit-field), the compiler does not allocate any further bit fields of a different type until the next boundary. I doubt it is a bug. It probably has something to do with the underlying architecture of your system. **edit:** c++ compilers will allocate bit-fields in memory as follows: several consecutive bit-field members *of the same type* will be allocated sequentially. As soon as a new type needs to be allocated, it will be aligned with the beginning of the next logical memory block. The next logical block will depend on your processor. Some processors can align to 8-bit boundaries, while others can only align to 16-bit boundaries. In your test3, each member is of a different type than the one before it, so the memory allocation will be 8 \* (the minimum logical block size on your system). In your case, the minimum block size is two bytes (16-bit), so the size of test3 is 8\*2 = 16. On a system that can allocate 8-bit blocks, I would expect the size to be 8.
Be careful with bitfields as much of its behavior is implementation (compiler) defined: From C++03, 9.6 Bitfields (pg. 163): > Allocation of bit-fields within a > class object is > implementation-defined. Alignment of > bit-fields is implementation-defined. > Bit-fields are packed into some > addressable allocation unit. > [Note:bit-fields straddle allocation > units on some machines and not on > others. Bit-fields are assigned > right-to-left on some machines, > left-to-right on others. ] That is, it is not a bug in the compiler but rather lack of a standard definition of how it should behave.
C++ bitfield packing with bools
[ "", "c++", "bit-fields", "" ]
I am looking in the Collections framework of Java for a LIFO Structure (Stack) without any success. Basically I want a really simple stack; my perfect option would be a Deque, but I am in Java 1.5. I would like not to have to add another class to my structure but I am wondering if that is possible: 1. Is there any class in the Collections framework (1.5) that does the job? 2. If not, is there any way to turn a Queue in a LIFO Queue (aka Stack) without reimplementation? 3. If not, which Interface or class should I extend for this task? I guess that keep the way that the guys of Sun have made with the Deque is a good start. Thanks a lot. EDIT: I forgot to say about the Stack class: I have my doubts about this class when I saw that it implements the Vector class, and the Vector class is a little bit obsolete, isn't it?
There's actually a Stack class: <http://java.sun.com/j2se/1.5.0/docs/api/java/util/Stack.html> If you don't want to use that, the LinkedList class (<http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html>) has `addFirst` and `addLast` and `removeFirst` and `removeLast` methods, making it perfect for use as a stack or queue class.
I realize I'm late to the party here, but java.util.Collections (Java 7) has a static 'asLifoQueue' that takes a Deque argument and returns (obviously) a LIFO queue view of the deque. I'm not sure what version this was added. <http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#asLifoQueue(java.util.Deque)>
Java Collections (LIFO Structure)
[ "", "java", "collections", "stack", "queue", "" ]
For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines. One quick way is to do this: ``` lines = len(list(open(fname))) ``` However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to keep the current line in memory). This doesn't work: ``` lines = len(line for line in open(fname)) ``` as generators don't have a length. Is there any way to do this short of defining a count function? ``` def count(i): c = 0 for el in i: c += 1 return c ``` To clarify, I understand that the whole file will have to be read! I just don't want it in memory all at once
Short of iterating through the iterable and counting the number of iterations, no. That's what makes it an iterable and not a list. This isn't really even a python-specific problem. Look at the classic linked-list data structure. Finding the length is an O(n) operation that involves iterating the whole list to find the number of elements. As mcrute mentioned above, you can probably reduce your function to: ``` def count_iterable(i): return sum(1 for e in i) ``` Of course, if you're defining your own iterable object you can always implement `__len__` yourself and keep an element count somewhere.
If you need a count of lines you can do this, I don't know of any better way to do it: ``` line_count = sum(1 for line in open("yourfile.txt")) ```
Is there any built-in way to get the length of an iterable in python?
[ "", "python", "iterator", "" ]
I am using SQL Advantage and need to know what the SQL is to identify the triggers associated with a table. I don't have the option to use another tool so the good old fashioned SQL solution is the ideal answer.
I also found out that ``` sp_depends <object_name> ``` will show you a lot of information about a table, including all triggers associated with it. Using that, along with Ray's query can make it much easier to find the triggers. Combined with this query from Ray's linked article: ``` sp_helptext <trigger_name> ``` and you can see the definition of the trigger: ``` sp_depends <trigger_name> ``` will also show you all tables related to a trigger
``` select * from sysobjects where type = 'TR' ``` Taken from [here](https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1061431.html).
How do you identify the triggers associated with a table in a sybase database?
[ "", "sql", "triggers", "sybase", "advantage-database-server", "" ]
I'm starting out with wxPython and have been working my way through every tutorial and example I can get my hands on. I've run into a slight problem, however, and it has to do with the wx.App versus the wx.Frame and which should contain specific methods. Just about every example I've seen don't go much beyond layouts/sizers and event handling, none really tackle project organization of a wxPython project. For example, I have a method that gets a list of folders. The way most examples would deal with this would be to stick the method right in the frame class. This method has the potential to be used in several other parts of the application, so it would make more sense to store it at the application class level. How should I organize and call "universal" methods like these so that I don't clutter up my frame classes. **UPDATE:** To clarify, the "list of folders" was just an example, my actual method does a lot more work. What I'm saying is I have code that isn't Frame-specific. If I had this in the application class, what is the best way to call it from and event method in my frame. I'm looking for actual project organization techniques, not programming fundamentals.
Your classes that inherit from wxWidgets/wxPython data types should not implement any business logic. wxWidgets is a GUI library, so any subclasses of wxApp or wxFrame should remain focused on GUI, that is on displaying the interface and being responsive to user actions. The code that does something useful should be separated from wx, as you can decide later to use it in some web or console application and you don't want to create wxApp object in such case. You can also decide later on to move some computations to separate 'worker threads', while your GUI will be the 'main thread' - responsive, and repainted properly during long lasting computations. Last but not least - the classes that encapsulate your logic might tend to grow during projects lifetime. If they're mixed with your GUI classes they will grow faster, and finally they become so complex that you're almost unable to debug them... While having them separated leads to clean code when you don't mix bugs in logic with bugs in GUI (refreshing/layout/progress bar etc.). Such approach has another nice feature - ability to split work among GUI-people and logic-people, which can do their work without constant conflicts.
As Mark stated you should make a new class that handles things like this. The ideal layout of code when using something like wxWidgets is the model view controller where the wxFrame class only has the code needed to display items and all the logic and business rules are handled by other class that interact with the wxFrame. This way you can change logic and business rules with out having to change your interface and change (or swap) your interface with out having to change your logic and business rules.
Calling Application Methods from a wx Frame Class
[ "", "python", "wxpython", "wxwidgets", "model-view-controller", "project-organization", "" ]
C#, .NET 3.5 I am trying to get all of the properties of an object that have BOTH a getter and a setter for the instance. The code I *thought* should work is ``` PropertyInfo[] infos = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty); ``` However, the results include a property that does not have a setter. To give you a simple idea of my inheritance structure that might be affecting this (though I don't know how): ``` public interface IModel { string Name { get; } } public class BaseModel<TType> : IModel { public virtual string Name { get { return "Foo"; } } public void ReflectionCopyTo(TType target) { PropertyInfo[] infos = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty); foreach (PropertyInfo info in infos) info.SetValue(target, info.GetValue(this, null), null); } } public class Child : BaseModel<Child> { // I do nothing to override the Name property here } ``` I end up with the following error when working with Name: ``` System.ArgumentException: Property set method not found. ``` EDIT: I would like to know why this does *not* work, as well as what I should be doing to not get the error.
Call [`GetGetMethod`](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getgetmethod.aspx) and [`GetSetMethod`](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getsetmethod.aspx) on the property - if both results are non-null, you're there :) (The parameterless versions only return public methods; there's an overload with a boolean parameter to specify whether or not you also want non-public methods.)
You can check the `PropertyInfo.CanRead` and `PropertyInfo.CanWrite` properties.
How do you find only properties that have both a getter and setter?
[ "", "c#", ".net", "reflection", "" ]
According to the documentation of the `==` operator in [MSDN](http://msdn.microsoft.com/en-us/library/53k8ybth.aspx), > For predefined value types, the > equality operator (==) returns true if > the values of its operands are equal, > false otherwise. For reference types > other than string, == returns true if > its two operands refer to the same > object. For the string type, == > compares the values of the strings. > User-defined value types can overload > the == operator (see operator). So can > user-defined reference types, although > **by default == behaves as described > above for both predefined and > user-defined reference types.** So why does this code snippet fail to compile? ``` bool Compare<T>(T x, T y) { return x == y; } ``` I get the error *Operator '==' cannot be applied to operands of type 'T' and 'T'*. I wonder why, since as far as I understand the `==` operator is predefined for all types? **Edit:** Thanks, everybody. I didn't notice at first that the statement was about reference types only. I also thought that bit-by-bit comparison is provided for all value types, which I now know is *not* correct. But, in case I'm using a reference type, would the `==` operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one? **Edit 2:** Through trial and error, we learned that the `==` operator will use the predefined reference comparison when using an unrestricted generic type. Actually, the compiler will use the best method it can find for the restricted type argument, but will look no further. For example, the code below will always print `true`, even when `Test.test<B>(new B(), new B())` is called: ``` class A { public static bool operator==(A x, A y) { return true; } } class B : A { public static bool operator==(B x, B y) { return false; } } class Test { void test<T>(T a, T b) where T : A { Console.WriteLine(a == b); } } ```
"...by default == behaves as described above for both predefined and user-defined reference types." Type T is not necessarily a reference type, so the compiler can't make that assumption. However, this will compile because it is more explicit: ``` bool Compare<T>(T x, T y) where T : class { return x == y; } ``` **Follow up to additional question, "But, in case I'm using a reference type, would the the == operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one?"** I would have thought that == on the Generics would use the overloaded version, but the following test demonstrates otherwise. Interesting... I'd love to know why! If someone knows please share. ``` namespace TestProject { class Program { static void Main(string[] args) { Test a = new Test(); Test b = new Test(); Console.WriteLine("Inline:"); bool x = a == b; Console.WriteLine("Generic:"); Compare<Test>(a, b); } static bool Compare<T>(T x, T y) where T : class { return x == y; } } class Test { public static bool operator ==(Test a, Test b) { Console.WriteLine("Overloaded == called"); return a.Equals(b); } public static bool operator !=(Test a, Test b) { Console.WriteLine("Overloaded != called"); return a.Equals(b); } } } ``` **Output** Inline: Overloaded == called Generic: Press any key to continue . . . **Follow Up 2** I do want to point out that changing my compare method to ``` static bool Compare<T>(T x, T y) where T : Test { return x == y; } ``` causes the overloaded == operator to be called. I guess without specifying the type (as a *where*), the compiler can't infer that it should use the overloaded operator... though I'd think that it would have enough information to make that decision even without specifying the type.
As others have said, it will only work when T is constrained to be a reference type. Without any constraints, you can compare with null, but only null - and that comparison will always be false for non-nullable value types. Instead of calling Equals, it's better to use an `IComparer<T>` - and if you have no more information, `EqualityComparer<T>.Default` is a good choice: ``` public bool Compare<T>(T x, T y) { return EqualityComparer<T>.Default.Equals(x, y); } ``` Aside from anything else, this avoids boxing/casting.
Can't operator == be applied to generic types in C#?
[ "", "c#", "generics", "operators", "equals-operator", "" ]
If I'm using an ArrayList in C#.NET, is the order guaranteed to stay the same as the order I add items to it?
Yes, elements are always added to the end (unless you specify otherwise, e.g. with a call to [Insert](http://msdn.microsoft.com/en-us/library/system.collections.arraylist.insert.aspx)). In other words, if you do: ``` int size = list.Count; int index = list.Add(element); Assert.AreEqual(size, index); // Element is always added at the end Assert.AreEqual(element, list[index]); // Returned index is position in list ``` The position will change if you remove any earlier elements or insert new elements ahead of it, of course. Is there any good reason for you to use `ArrayList` rather than `List<T>` by the way? Non-generic collections are *so* 2003... (The order is stable in `List<T>` as well, by the way.)
Yes, it is, unless some piece of your code changes the order by e.g. swapping.
Is the order of an arraylist guaranteed in C#.NET?
[ "", "c#", ".net", "arraylist", "" ]
I just installed the FindBugs plugin for Eclipse, with the hope that it will help me find SQL injection vulnerabilities in my code. However, it doesn't seem to be finding anything, even when I deliberately put some in. In the following examples, assume `staticFinalBaseQuery` is declared as follows: public static final String staticFinalBaseQuery = "SELECT foo FROM table where id = '"; and assume `userInputfilterString` is an argument to the method wrapping the example snippets. It comes direct from user input, and is not sanitized. For example, the following snippet will not trigger a warning: ``` String query = staticFinalBaseQuery + userInputfilterString; pstmt = dbConnection.prepareStatement(query); ``` Where `staticFinalBaseQuery` is a static final string, and `userInputfilterString` is a string direct from user input, available only at runtime, not scrubbed at all. Clearly, this is a vulnerability. I expect the "[A prepared statement is generated from a nonconstant String](http://findbugs.sourceforge.net/bugDescriptions.html#SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING)" warning to be triggered. The following snippet also does not cause a warning (not surprising, since the compiled forms of these are probably identical): ``` pstmt = dbConnection.prepareStatement(staticFinalBaseQuery + userInputfilterString); ``` However, this will cause a warning: ``` pstmt = dbConnection.prepareStatement(staticFinalBaseQuery + userInputfilterString + "'"); ``` If I append an empty string, or a space, no warning is triggered. **So, my question is,** how can I get FindBugs to trigger on my first example? I am also curious **why** the first doesn't cause a warning, but the last does? Thanks in advance! **EDIT**: I [submitted a bug](https://sourceforge.net/tracker2/?func=detail&aid=2475589&group_id=96405&atid=614693) to FindBugs's bug tracking system, as it seems this might be a bug. However, if anyone has any tips, I'd love to hear them.
It is hard to distinguish between safe code and unsafe code here. Sure, userInputfilterString *may* be unsafe, but it is impossible to determine this at compile time. However, the single-quote character in a string concatenation is a tell-tale sign of using inject-able code. That's why FindBugs is triggering on the line containing this character, but not on the line with mere string concatenation. Basically, this isn't a bug, but a limitation of how much can be done by software to check for SQL injection. Since the string may contain *anything* (i.e. it could have the vulnerable concatenation in another function) it is impossible to have the tool determine with any certainty that a problem exists.
I don't think [PMD](http://pmd.sourceforge.net/) or [Checkstyle](http://checkstyle.sourceforge.net/) will catch it either, but you might give them a try (I use all 3 on a regular basis, good tools to use). EDIT: PMD was the correct link, but I called it findbugs... findbugs on the brain I guess...
Findbugs not finding potential SQL injection vulnerability
[ "", "java", "sql-injection", "findbugs", "" ]
I am looking for a small wiki engine that is easy to embed into an existing PHP application. Or perhaps a set of libraries to handle all the typical wiki functions. Currently I am using [ErfurtWiki](http://erfurtwiki.sourceforge.net/), but it is starting to show its age. It hasn't been updated since 2005, and several of the pages on sourceforge appear to have been [hacked](http://erfurtwiki.sourceforge.net/MailingList). I will be including it with a GPLv2 application so a GPL compatible license is important. Edit: To update, mostly I am just looking for text formatting/parser functionality. I want to deal with the storage, security, rev history, etc on my own.
[Pear::Text\_Wiki](http://pear.php.net/package/Text_Wiki) is another option, albeit it only handles the case of text formatting. It has not been updated since June of 2007, but includes several Wiki formats (all of which have other latest release dates). The formats that Text\_Wiki supports are: * BBCode: latest release: 2006-12-23 * CoWiki: latest release: 2007-01-02 * Creole: latest release: 2007-08-01 * Doku: latest release: 2005-10-14 * MediaWiki: latest release: 2006-04-10 * Tiki: latest release: 2005-10-14 It has an LGPL license, so there should be no licensing problems with including in a GPL project.
I highly recommend [MediaWiki](http://www.mediawiki.org/wiki/MediaWiki), the wiki engine that runs wikipedia. EDIT: As per your comment, MediaWiki is highly embeddable. I've integrated it in numerous projects over the years.
Suggest a good PHP wiki engine
[ "", "php", "wiki", "wiki-engine", "" ]
[I was trying to get my Netbeans to autocomplete with PHP](https://stackoverflow.com/questions/390192), and I learned that this code is valid in PHP: ``` function blah(Bur $bur) {} ``` A couple of questions: 1. **Does this actually impose any limits** on what type of variable I can pass to the blah method? 2. If this is just to help the IDE, that's fine with me. **How can I declare the type of a variable in PHP if I'm not in a function?**
This type-hinting only works for validating function arguments; you can't declare that a PHP variable must always be of a certain type. This means that in your example, $bur must be of type Bur when "blah" is called, but $bur could be reassigned to a non-Bur value inside the function. Type-hinting only works for class or interface names; you can't declare that an argument must be an integer, for example. One annoying aspect of PHP's type-hinting, which is different from Java's, is that NULL values aren't allowed. So if you want the option of passing NULL instead of an object, you must remove the type-hint and do something like this at the top of the function: ``` assert('$bur === NULL || $bur instanceof Bur'); ``` **EDIT:** This last paragraph doesn't apply since PHP 5.1; you can now use NULL as a default value, even with a type hint. **EDIT:** You can also install the [SPL Type Handling](http://php.net/manual/en/book.spl-types.php) extension, which gives you wrapper types for strings, ints, floats, booleans, and enums. **EDIT:** You can also use "array" since PHP 5.1, and "callable" since PHP 5.4. **EDIT:** You can also use "string", "int", "float" and "bool" since PHP 7.0. **EDIT:** **As of PHP 7.4, you can declare member variables of a class/interface/trait as a specific type** like `public int $a;`, and variables that are declared this way cannot be assigned to a value of another type. You can also use [union types](https://php.watch/versions/8.0/union-types) such as `string|int` as of PHP 8.0, and you can use classes in the union types as of PHP 8.1. <https://www.php.net/manual/en/language.types.declarations.php>
1. Specifying a data type for a function parameter will cause PHP to throw a catchable fatal error if you pass a value which is not of that type. Please note though, you can only specify types for classes, and not primitives such as strings or integers. 2. Most IDE's can infer a data type from a PHPDoc style comment if one is provided. e.g. ``` /** * @var string */ public $variable = "Blah"; ``` **UPDATE 2021:** As of PHP 7 (which is several years old at this point) primitive types can also be declared for function arguments. Nullability can also be indicated with a ? in front of the type from 7.1 onward. You can declare return types now too. So this is valid PHP these days: ``` public function hasFoo(?int $numFoos) :bool { ``` phpStorm (my current preferred IDE) is happy to use all of these types for code completion, so I don't need as many phpDoc comments for typing as I used to.
Declaring Variable Types in PHP?
[ "", "php", "variable-types", "" ]
I'm using .Net 2.0 and this is driving me crazy but there's probably some easy thing I'm not doing that I am now too confused to see. I have an application that has a bespoke collection of objects in it, only the main form should be able to change the contents of that collection and all other forms should be able to read from it. Actually there's only one other form but I need it to have the capability of being called multiple times as it edits different items in the bespoke collection. To make the child form a dialog is therefore impractical. The ability to open multiple instances of this form containing different items from the collection is necessary. I just can't seem to think of a way of making all forms revolve around the same instance of the collection. Like I say I'm probably missing something obvious but I have ceased to be able to think about the problem properly. EDIT: Yikes! I can't have explained myself very well. All subforms should be able to read and write collection items, but I want to only use one instance of the collection at a time whilst the programme is running. EDIT 2: It turned out that what I needed was a singleton. I have implemented a similar solution in a different project now. Thanks to the commenter below who didn't actually leave an answer I can mark as the correct one, even though they nailed it.
If the main form needs read/write access but other forms don't, then I would make the collection a property of your main form that is read/write from within your form, but read only from outside your form. You can do this using something like: C# ``` private myCollection _MyCollection; public myCollection MyCollection { get { return _MyCollection.AsReadOnly(); } private set { _MyCollection = value; } } ``` VB ``` Private _MyCollection As myCollection Public Property MyCollection() As myCollection Get Return _MyCollection.AsReadOnly End Get Private Set(ByVal value As myCollection) _MyCollection = value End Set End Property ``` Then you can reference your collection from inside your form by referencing either MyCollection or \_MyCollection as you choose, but from outside your form, the collection will be ReadOnly and therefore not editable. ***Edit:*** After your edit, it does look like what you're after is a singleton as previously suggested does this mean that all instances of your forms should be able to edit this collection or not? If so, then put your collection into a static class: ``` Private _MyCollection as myCollection = Nothing Public Shared ReadOnly Property MyCollection() As myCollection Get If _MyCollection is Nothing Then _MyCollection = New myCollection Return _MyCollection End Get End Property ``` Now the first time the collection is referenced from within one of your forms it will instantiate a new collection which you can then add/remove items from. Every time you reference the collection from this or one of your other forms, it will already have been instantiated, so it will return the collection that was originally instantiated. None of the forms however will have the ability to set a new collection, just reference the one instantiated by the singleton pattern.
Check out the method `List<T>.AsReadOnly()` This allows you to return a read-only wrapper for the list. e.g. ``` private LIst<Foo> fooList; public ReadOnlyCollection<Foo> Foo { get { return fooList.AsReadOnly(); } ```
C# Forms App Collections
[ "", "c#", "winforms", "collections", "" ]
Pretty straightforward stuff, here -- I'm just not good enough with mysql to understand what it wants from me. I've got a short java test-case that opens a connection on mysql on my dev system but, when I try to put it to my server, it fails. Any help in tracking this down would be most appreciated. Thanks! **Test Code** ``` import java.util.*; import java.sql.*; public class mysqltest { static public void getDBConnection() { System.out.println ("Start of getDBConnection."); Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "magnets_development"; String driver = "com.mysql.jdbc.Driver"; String userName = "*****"; // blanked for publication String password = "*****"; try { Class.forName (driver).newInstance(); System.out.println ("driver.newInstance gotten."); conn = DriverManager.getConnection (url+dbName, userName, password); System.out.println ("Connection gotten: " + conn + "."); Statement sql = conn.createStatement (); ResultSet results = sql.executeQuery ("use " + dbName + ";"); } catch (Exception ex) { System.out.println ("*** Got exception."); ex.printStackTrace(); } } public static void main(String args[]) { System.out.println ("Main started."); mysqltest.getDBConnection(); } } ``` **Dev System Output** *(Expected/correct response)* ``` olie$ java mysqltest Main started. Start of getDBConnection. Properties set. driver.newInstance gotten. Connection gotten: com.mysql.jdbc.Connection@c980c9. olie$ ``` **Server Output** *(Error I'm trying to track-down)* (Some blank lines removed.) ``` mini$ java mysqltest Main started. Start of getDBConnection. Properties set. driver.newInstance gotten. *** Got exception. com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.net.ConnectException MESSAGE: Connection refused STACKTRACE: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432) at java.net.Socket.connect(Socket.java:520) at java.net.Socket.connect(Socket.java:470) at java.net.Socket.<init>(Socket.java:367) at java.net.Socket.<init>(Socket.java:209) at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256) at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:271) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2771) at com.mysql.jdbc.Connection.<init>(Connection.java:1555) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285) at java.sql.DriverManager.getConnection(DriverManager.java:525) at java.sql.DriverManager.getConnection(DriverManager.java:140) at mysqltest.getDBConnection(mysqltest.java:34) at mysqltest.main(mysqltest.java:49) ** END NESTED EXCEPTION ** Last packet sent to the server was 3 ms ago. at com.mysql.jdbc.Connection.createNewIO(Connection.java:2847) at com.mysql.jdbc.Connection.<init>(Connection.java:1555) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285) at java.sql.DriverManager.getConnection(DriverManager.java:525) at java.sql.DriverManager.getConnection(DriverManager.java:140) at mysqltest.getDBConnection(mysqltest.java:34) at mysqltest.main(mysqltest.java:49) mini$ ```
Bah! My apologies -- I just had "local connections only" set up. I was confused by the fact that the java app was running locally (so seemed a "local connection" but, because it is connecting via TCP, it's a "remote" connection, even though it originates on localhost. I will eventually learn how to administer these things. In the mean time, I hope someone else can learn from my mistakes. Thank you to all who put time into trying to help me. I have since allowed "remote" connections, but all of my user-accounts are 'username'@'localhost" only (*i.e.*, there is no 'username'@'%', which would allow any machine to connect.) Hopefully, I got that part right, at least. Thanks again!
Just a helpful note on this subject. I spent at least 30 minutes trying to debug the same error and this was my mistake. In my MySQL conf file I happened to set the *BIND ADDR* to the IP of the machine. I did not set it to `127.0.0.1`, or `0.0.0.0`. So MySQL would accept JDBC connections from outside, but not internally. I was getting Connection Refused only when connecting from the local machine. Changing that address to `0.0.0.0` allowed it to listen for requests to any IP. This allowed for both internal and external IPs. Hopefully this helps somebody who made the same dumb mistake I did. Check it with the above comment about `netstat -an | grep 3306`.
Java Driver.getConnection() yields "Connection Refused" from mysql on live system, not dev
[ "", "java", "mysql", "jdbc", "" ]
I have an HTML (not XHTML) document that renders fine in Firefox 3 and IE 7. It uses fairly basic CSS to style it and renders fine in HTML. I'm now after a way of converting it to PDF. I have tried: * [DOMPDF](https://github.com/dompdf/dompdf): it had huge problems with tables. I factored out my large nested tables and it helped (before it was just consuming up to 128M of memory then dying--thats my limit on memory in php.ini) but it makes a complete mess of tables and doesn't seem to get images. The tables were just basic stuff with some border styles to add some lines at various points; * [HTML2PDF and HTML2PS](https://github.com/spipu/html2pdf): I actually had better luck with this. It rendered some of the images (all the images are Google Chart URLs) and the table formatting was much better but it seemed to have some complexity problem I haven't figured out yet and kept dying with unknown node\_type() errors. Not sure where to go from here; and * [Htmldoc](http://www.msweet.org/projects.php?Z1): this seems to work fine on basic HTML but has almost no support for CSS whatsoever so you have to do everything in HTML (I didn't realize it was still 2001 in Htmldoc-land...) so it's useless to me. I tried a Windows app called Html2Pdf Pilot that actually did a pretty decent job but I need something that at a minimum runs on Linux and ideally runs on-demand via PHP on the Webserver. What am I missing, or how can I resolve this issue?
**Important:** Please note that this answer was written in 2009 and it might not be the most cost-effective solution today in 2019. Online alternatives are better today at this than they were back then. Here are some online services that you can use: * [PDFShift](https://pdfshift.io) * [Restpack](https://restpack.io/html2pdf) * [PDF Layer](https://pdflayer.com) * [DocRaptor](https://docraptor.com) * [HTMLPDFAPI](https://htmlpdfapi.com) * [HTML to PDF Rocket](https://www.html2pdfrocket.com) --- Have a look at [PrinceXML](http://princexml.com). It's definitely the best HTML/CSS to PDF converter out there, although it's not free (But hey, your programming might not be free either, so if it saves you 10 hours of work, you're home free (since you also need to take into account that the alternative solutions will require you to setup a dedicated server with the right software)) Oh yeah, did I mention that this is the first (and probably only) HTML2PDF solution that does full [ACID2](http://princexml.com/samples/acid2/acid2.pdf)? [PrinceXML Samples](http://princexml.com/samples/)
Have a look at [`wkhtmltopdf`](http://wkhtmltopdf.org/) . It is open source, based on webkit and free. We wrote a small tutorial [here](http://beebole.com/blog/general/convert-html-to-pdf-with-full-css-support-an-opensource-alternative-based-on-webkit/). **EDIT( 2017 ):** If it was to build something today, I wouldn't go that route anymore. But would use <http://pdfkit.org/> instead. Probably stripping it of all its nodejs dependencies, to run in the browser.
How Can I add HTML And CSS Into PDF
[ "", "php", "html", "css", "pdf", "pdf-generation", "" ]
Is it possible to display the text in a TextBlock vertically so that all letters are stacked upon each other (not rotated with LayoutTransform)?
Nobody has yet mentioned the obvious and trivial way to stack the letters of an arbitrary string vertically (without rotating them) using pure XAML: ``` <ItemsControl ItemsSource="Text goes here, or you could use a binding to a string" /> ``` This simply lays out the text vertically by recognizing the fact that the string is an IEnumerable and so ItemsControl can treat each character in the string as a separate item. The default panel for ItemsControl is a StackPanel, so the characters are laid out vertically. Note: For precise control over horizontal positioning, vertical spacing, etc, the ItemContainerStyle and ItemTemplate properties can be set on the ItemsControl.
Just in case anybody still comes across this post... here is a simple 100% xaml solution. ``` <TabControl TabStripPlacement="Left"> <TabItem Header="Tab 1"> <TabItem.LayoutTransform> <RotateTransform Angle="-90"></RotateTransform> </TabItem.LayoutTransform> <TextBlock> Some Text for tab 1</TextBlock> </TabItem> <TabItem Header="Tab 2"> <TabItem.LayoutTransform> <RotateTransform Angle="-90"></RotateTransform> </TabItem.LayoutTransform> <TextBlock> Some Text for tab 2</TextBlock> </TabItem> </TabControl> ```
Vertical Text in Wpf TextBlock
[ "", "c#", "wpf", "" ]
I'm asking for a suitable architecture for the following Java web application: The goal is to build several web applications which all operate on the same data. Suppose a banking system in which account data can be accessed by different web applications; it can be accessed by customers (online banking), by service personal (mostly read) and by the account administration department (admin tool). These applications run as separate web applications on different machines but they use the same data and a set of common data manipulation and search queries. A possible approach is to build a core application which fits the common needs of the clients, namely data storage, manipulation and search facilities. The clients can then call this core application to fulfil their requests. The requirement is the applications are build on top of a Wicket/Spring/Hibernate stack as WARs. To get a picture, here are some of the possible approaches we thought of: A The monolithic approach. Build one huge web application that fits all needs (this is not really an option) B The API approach. Build a core database access API (JAR) for data access/manipulation. Each web application is build as a separate WAR which uses the API to access a database. There is no separate core application. C RMI approach. The core application runs as a standalone application (possibly a WAR) and offers services via RMI (or HttpInvoker). D WS approach. Just like C but replace RMI with Web Services E OSGi approach. Build all the components as OSGi modules and which run in an OSGi container. Possibly use SpringSource dm Server or ModuleFusion. This approach was not an option for us for some reasons ... Hope I could make clear the problem. We are just going the with option B, but I'm not very confident with it. What are your opinions? Any other solutions? What are the drawbacks of each solution?
B, C, and D are all just different ways to accomplish the same thing. My first thought would be to simply have all consumer code connecting to a common database. This is certainly doable, and would eliminate the code you don't want to place in the middle. The drawback, of course, is that if the schema changes, all consumers need to be updated. Another solution you may want to consider is giving each consumer its own database, using some sort of replication to keep them in sync.
I think that you have to go in the oppposite direction - from the bottom up. Of course, you have to go forth and back to verify that everything is playing, but here is the general direction: Think about your data - DB scheme, how transactions are important (for example in banking systems everything is about transactions) etc. Then define common access method - from set of stored procedures to distributed transaction engine... Next step is a business logic/presentation - what could be generalized and what is a subject of customization. And the final stage are the interfaces, visualisation and reports
Architecture - Multiple web apps operating on the same data
[ "", "java", "architecture", "" ]
I need to randomly 'sort' a list of integers (0-1999) in the most efficient way possible. Any ideas? Currently, I am doing something like this: ``` bool[] bIndexSet = new bool[iItemCount]; for (int iCurIndex = 0; iCurIndex < iItemCount; iCurIndex++) { int iSwapIndex = random.Next(iItemCount); if (!bIndexSet[iSwapIndex] && iSwapIndex != iCurIndex) { int iTemp = values[iSwapIndex]; values[iSwapIndex] = values[iCurIndex]; values[iCurIndex] = values[iSwapIndex]; bIndexSet[iCurIndex] = true; bIndexSet[iSwapIndex] = true; } } ```
A good linear-time shuffling algorithm is the [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher-Yates_shuffle). One problem you'll find with your proposed algorithm is that as you near the end of the shuffle, your loop will spend a lot of time looking for randomly chosen elements that have not yet been swapped. This may take an indeterminate amount of time once it gets to the last element to swap. Also, it looks like your algorithm will never terminate if there are an odd number of elements to sort.
``` static Random random = new Random(); public static IEnumerable<T> RandomPermutation<T>(IEnumerable<T> sequence) { T[] retArray = sequence.ToArray(); for (int i = 0; i < retArray.Length - 1; i += 1) { int swapIndex = random.Next(i, retArray.Length); if (swapIndex != i) { T temp = retArray[i]; retArray[i] = retArray[swapIndex]; retArray[swapIndex] = temp; } } return retArray; } ``` modified to handle lists or other objects implementing IEnumerable
Most efficient way to randomly "sort" (Shuffle) a list of integers in C#
[ "", "c#", "random", "shuffle", "" ]
I work on a database driven website. Most pages' titles are the names of partners we have, and served from a database using php. For example one page might be called "Experian". The problem is that some of the values for partner names don't work because the values are things like ``` $partnername22 = Discover<sup>tm</sup> Magazine ``` I can't use this for a title because superscript can't show up in a title, and I can't change the value because many other things depend on it. Is there a trick I can pull to make the browser ignore the superscript tags if they are in the title?
For: ``` <title><?php echo $offer22name ?>is a magazine</title> ``` change to: ``` <title><?php echo preg_replace('|<sup>(.*?)</sup>|', '($1)', $offer22name) ?> is a magazine</title> ``` But like Bryan mentioned, you should use PHP's strip\_tags() in this scenario. So: ``` <title><?php echo strip_tags($offer22name) ?> is a magazine</title> ```
It would be very simple (and probably advisable) to use PHP's strip\_tags() command to remove all of the html from your string before posting it as a title.
Ignoring superscript in title tags
[ "", "php", "html", "css", "superscript", "" ]
I'm making a php web application which stores user specific information that is not shared with other users. Would it be a good idea to store some of this information in the $\_SESSION variable for caching? For example: cache a list of categories the user has created for their account.
This would be an appropriate use of the session mechanism as long as you keep this in mind: * Session does not persist for an indefinite amount of time. * When pulling from session, ensure you actually got a result (ASP.NET will return NULL if the Session has expired/cleared) * Server restarts may wipe the session cache. * Do this for convenience, not performance. For high-performance caching, choose an appropriate mechanism (i.e. [memcached](http://www.danga.com/memcached/)) A good usage pattern would be like this (ether cookies or session): * User logs in * Store preferences (background color, last 10 records looked at, categories) in session/cookie. * On rendering of a page, refer to the Session/Cookie values (ensuring they are valid values and not null). Things not to do in a cookie * Don't store anything sensitive (use session). * A cookie value should not grant/deny you access to anything (use session). * Trap errors, assume flags and strings may not be what you expect, may be missing, may be changed in transit. I'm sure there is other things to consider too, but this is just off the top of my head here.
That could work well for relatively small amounts of data but you'll have to take some things into consideration: 1. $\_SESSION is stored somewhere between requests, file on disk or database or something else depending on what you choose to use (default to file) 2. $\_SESSION is local to a single user on a single machine. 3. sessions have a TTL (time to live), they dissapear after a set amount of time (which you control) 4. Under certain circumstances, sessions can block (rarely an issue, but i've run into it streaming flash) If the data you mean to cache is to be accessed by multiple users you're quickly better off caching it seperately.
Caching variables in the $_SESSION variable?
[ "", "php", "session", "caching", "" ]
In a web application I am working on, the user can click on a link to a CSV file. There is no header set for the mime-type, so the browser just renders it as text. I would like for this file to be sent as a .csv file, so the user can directly open it with calc, excel, gnumeric, etc. ``` header('Content-Type: text/csv'); echo "cell 1, cell 2"; ``` This code works as expected on my computer (Isn't that how it always is?) but does not work on another computer. My browser is a nightly build of FF 3.0.1 (on linux). The browsers it did not work in were IE 7 and FF 3.0 (on windows) Are there any quirks I am unaware of?
You could try to force the browser to open a "Save As..." dialog by doing something like: ``` header('Content-type: text/csv'); header('Content-disposition: attachment;filename=MyVerySpecial.csv'); echo "cell 1, cell 2"; ``` Which should work across most major browsers.
You are not specifying a language or framework, but the following header is used for file downloads: ``` "Content-Disposition: attachment; filename=abc.csv" ```
How to use the CSV MIME-type?
[ "", "php", "csv", "http-headers", "mime", "" ]
Is there a way to avoid row deletion on an specific table using constrains? I'd like to (for example) deny row deletion if the id is 0,1 or 2 This is in order to avoid users deleting master accounts for an application, and I'd like to avoid it even if someone tries it (by mistake) using sql directly. Thanks! **EDIT:** The whole idea of this question is not to touch the application. It's not a matter of security, I just need to know if It's possible to do what I asked with constrains or any other thing that SQL Server has (It does not need to be an standard db solution). **EDIT 2:** Code samples are very, very appreciated :D
As far as enforcing this in a *constraint*, my solution would be to create a dependent table, so referenced rows cannot be deleted. ``` CREATE TABLE NoKillI ( id INT NOT NULL, FOREIGN KEY (id) REFERENCES Accounts(id) ON DELETE RESTRICT ); INSERT INTO NoKillI (id) VALUES (0); INSERT INTO NoKillI (id) VALUES (1); INSERT INTO NoKillI (id) VALUES (2); ``` Now no one can delete rows in `Accounts` with id values 0, 1, or 2, unless they first delete the corresponding rows in `NoKillI`. You can restrict deletions against the dependent table using SQL privileges.
You do this by writing a database trigger that fires on DELETE for the table in question. All it needs to do is throw an exception if the ID is invalid.
Is there a way to avoid row deletion on an specific table using constrains or triggers?
[ "", "sql", "sql-server", "database", "constraints", "" ]
On Stackers' recommendation, I have been reading Crockford's excellent *Javascript: The Good Parts*. It's a great book, but since so much of it is devoted to describing the best way to use Javascript's basic functionality, I'm not sure how I can put his advice into practice without duplicating the efforts of many other Javascript programmers. Take this passage, for example: > When you make a new object, you can select the object that should be its prototype. The mechanism that Javascript provides to do this is messy and complex, but it can be significantly simplified. We will add a `create` method to the `Object` function. The `create` method creates a new object that uses an old object as its prototype. > > ``` > if (typeof Object.create !== 'function') { > Object.create = function(o) { > var F = function () {}; > F.prototype = o; > return new F(); > } > ``` I could manually add this code to all my Javascript projects, but keeping track of everything would be a huge pain. **Are there any libraries that implement *The Good Part*'s recommendations and thereby save me the trouble of having to keep track of them (/ physically type them all out)?**
[Prototype](http://prototypejs.org/) has many great features, including a [Class helper](http://prototypejs.org/api/class) that handles the details of JS "inheritance" via the object prototype. Edit: damn, I keep forgetting that jQuery (my own library of choice) has [jQuery.extend](http://docs.jquery.com/Utilities/jQuery.extend)
Doesn't he work for Yahoo? You could always use the [Yahoo User Interface libraries](http://developer.yahoo.com/yui/). Personally, I'm partial to [JQuery](http://jquery.com/), as it strikes me as more concise, but you know: horses for courses.
Best way to use Javascript's "good parts"
[ "", "javascript", "abstraction", "" ]
If I type the command: ``` mvn dependency:list ``` The [docs](http://maven.apache.org/plugins/maven-dependency-plugin/) suggest that I'll get a list of my project's dependencies. Instead though, I get this: ``` [INFO] Searching repository for plugin with prefix: 'dependency'. [INFO] ----------------------------------------------------------- [ERROR] BUILD FAILURE [INFO] ----------------------------------------------------------- [INFO] Required goal not found: dependency:list ``` Call me a hopeful naive, but I had hoped maven would download any plugins it didn't have. Does anyone know what might be leading to this error? Does anyone know where maven stores information about what plugins it has installed, and where they're stored in the maven repository?
To answer my own question, thanks to some comments that were made on it, the settings.xml file had been customized and did not list the central maven repository. Oops.
Have you tried `mvn -cpu dependency:list` (or: `mvn --check-plugin-updates dependency:list`)? Probably, you have older version of dependency plugin which does not have goal `list` If this does not help, try upgrading Maven. Since 2.0.9 default versions are provided by the Super POM for most important plugins (dependency plug-in included), so 2.0 version will be downloaded (which has `list` goal). Or you can try removing the cached version of the plug-in from the repository (`~/.m2/repository/org/apache/maven/plugins/maven-dependency-plugin/`, where `~` is the user home directory).
Why can't maven find a plugin?
[ "", "java", "maven-2", "dependencies", "maven-plugin", "" ]
I have this html... ``` <select id="View" name="View"> <option value="1">With issue covers</option> <option value="0">No issue covers</option> </select> ``` It won't let me insert code like this... ``` <select id="View" name="View"> <option value="1" <% ..logic code..%> >With issue covers</option> <option value="0" <% ..logic code..%> >No issue covers</option> </select> ``` So whats the best way to set one to selected? Update: Without using the HTML Helpers.
I would agree with Marc on using helpers but if you must avoid them then you could try something like the following: ``` <select id="View" name="View"> <option value="1" <% if (something) { %> selected <% } %> >With issue covers</option> <option value="0" <% if (!something) { %> selected <% } %> >No issue covers</option> </select> ```
The "best" approach is probably to *use* the helpers: ``` var selectList = new SelectList(data, "ValueProp", "TextProp", data[1].ValueProp); ... Html.DropDownList("foo", selectList) ``` Where "data" could be an array of anonymous types, such as: ``` var data = new[] { new {Key=1, Text="With issue covers"}, new {Key=0, Text="No issue covers"} }; // todo: pick the selected index or value based on your logic var selectList = new SelectList(data, "Key", "Text", data[1].Key); Writer.Write(Html.DropDownList("foo", selectList)); ``` Another approach might be to select the correct item client-side through script, but obviously that only works with script enabled. Note it was missing comma and semicolon in data declaration, stopped it from working
Whats the best way to set a dropdown to selected in ASP.NET MVC markup?
[ "", "c#", "html", "asp.net-mvc", "" ]
How to (programmatically, without xml config) configure multiple loggers with Log4Net? I need them to write to different files.
[This thread at the log4net Dashboard details an approach](http://mail-archives.apache.org/mod_mbox/logging-log4net-user/200602.mbox/%3CDDEB64C8619AC64DBC074208B046611C769745@kronos.neoworks.co.uk%3E). To summarize a little, hopefully without ripping off too much code: ``` using log4net; using log4net.Appender; using log4net.Layout; using log4net.Repository.Hierarchy; // Set the level for a named logger public static void SetLevel(string loggerName, string levelName) { ILog log = LogManager.GetLogger(loggerName); Logger l = (Logger)log.Logger; l.Level = l.Hierarchy.LevelMap[levelName]; } // Add an appender to a logger public static void AddAppender(string loggerName, IAppender appender) { ILog log = LogManager.GetLogger(loggerName); Logger l = (Logger)log.Logger; l.AddAppender(appender); } // Create a new file appender public static IAppender CreateFileAppender(string name, string fileName) { FileAppender appender = new FileAppender(); appender.Name = name; appender.File = fileName; appender.AppendToFile = true; PatternLayout layout = new PatternLayout(); layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n"; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); return appender; } // In order to set the level for a logger and add an appender reference you // can then use the following calls: SetLevel("Log4net.MainForm", "ALL"); AddAppender("Log4net.MainForm", CreateFileAppender("appenderName", "fileName.log")); // repeat as desired ```
``` using System; using Com.Foo; using System.Collections.Generic; using System.Text; using log4net.Config; using log4net; using log4net.Appender; using log4net.Layout; using log4net.Repository.Hierarchy; public class MyApp { public static void SetLevel(string loggerName, string levelName) { ILog log = LogManager.GetLogger(loggerName); Logger l = (Logger)log.Logger; l.Level = l.Hierarchy.LevelMap[levelName]; } // Add an appender to a logger public static void AddAppender(string loggerName, IAppender appender) { ILog log = LogManager.GetLogger(loggerName); Logger l = (Logger)log.Logger; l.AddAppender(appender); } // Add an appender to a logger public static void AddAppender2(ILog log, IAppender appender) { // ILog log = LogManager.GetLogger(loggerName); Logger l = (Logger)log.Logger; l.AddAppender(appender); } // Create a new file appender public static IAppender CreateFileAppender(string name, string fileName) { FileAppender appender = new FileAppender(); appender.Name = name; appender.File = fileName; appender.AppendToFile = true; PatternLayout layout = new PatternLayout(); layout.ConversionPattern = "%d [%t] %-5p %c [%logger] - %m%n"; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); return appender; } private static readonly ILog log = LogManager.GetLogger(typeof(MyApp)); static void Main(string[] args) { BasicConfigurator.Configure(); SetLevel("Log4net.MainForm", "ALL"); AddAppender2(log, CreateFileAppender("appenderName", "fileName.log")); log.Info("Entering application."); Console.WriteLine("starting........."); log.Info("Entering application."); Bar bar = new Bar(); bar.DoIt(); Console.WriteLine("starting........."); log.Error("Exiting application."); Console.WriteLine("starting........."); } } namespace Com.Foo { public class Bar { private static readonly ILog log = LogManager.GetLogger(typeof(Bar)); public void DoIt() { log.Debug("Did it again!"); } } } ```
Log4Net: Programmatically specify multiple loggers (with multiple file appenders)
[ "", "c#", "log4net", "" ]
I am using tinyMCE and, rather annoyingly, it replaces all of my apostrophes with their HTML numeric equivalent. Now most of the time this isn't a problem but for some reason I am having a problem storing the apostrophe replacement. So i have to search through the string and replace them all. Any help would be much appreciated
did you try: ``` $string = str_replace("&#39;", "<replacement>", $string); ```
Is it just apostrophes that you want decoded from HTML entities, or everything? ``` print html_entity_decode("Hello, that&#39;s an apostophe.", ENT_QUOTE); ``` will print ``` Hello, that's an apostrophe. ```
Searching through a string trying to find &#39; in PHP
[ "", "php", "" ]
I'm currently working on a pet project and need to do C++ development on Windows, Mac, Linux, and Solaris, and I've narrowed it down to Netbeans and Eclipse, so I was wonderig which is more solid as a C++ editor. I just need solid editing, good autocompletion for templated code ad external libraries, and project file management, the build tools are external, so thats irrelevant here, for my comparison. Thus which is a better choice? Note: I know I should be using emacs or vim, but the issue is, my theory at least, that I'm left handed, so I use my right side (design,creativity) of the brain more than the left side (logic, memory), so I just simply cannot use emacs or vim, my brain simply isn't compatible, I tried them many times too, even used emacs for a few months but it drove me crazy... Thanks
I haven't used NetBeans, but Eclipse CDT (C Developer Tools, which includes C++), especially with the latest version, is really quite excellent: * Syntax checking and spell checking * Syntax highlighting that distinguishes between library calls and your function calls and between local and member variables and is even applied to code that's #ifdef'ed out * Macro expansion that can step you through each level of macro application or show the final result even of very complex Boost Preprocessor macros * A file and class outline view that updates dynamically to show where you are in a file. (Commercial IDE's I've used fail to do this.) * Powerful, flexible Find/Replace and Find in Files features with complete Perl-style regex support. It's also supposed to be able to do a C/C++ Find in Files that can search based on language semantics (e.g., only find references, not declarations), although this sometimes doesn't work for me. * Automatic tracking of TODO and other comment tags * Mouseover tips that show the exact declaration of a variable or function, including any comments, instead of just where a variable or function is declared. (Again, commercial IDE's I've used fail to do this.) * Support via plugins for Subversion, Doxygen, etc. * Some refactoring support - rename, extract constant, extract function, a few others * Code reformatter, based on user-definable code styles You'd asked specifically about its editor; the Eclipse editor is good enough that I use it in preference to the commercial IDE for our product whenever I don't need the commercial IDE's forms designer. Eclipse's debugger integration (using gdb) is tolerable but not great, and its memory usage is high. A few features (like the C/C++ Find in Files) don't work reliably or require reindexing (which is time consuming) for no apparent reason, but the latest version seems more reliable in this regard. Can someone who's used NetBeans fill in how it compares?
I'm using Netbeans from time to time on Solaris and the latest (6.5) version is pretty neat. It has all the features that you need, perhaps autocompletion could work better, but I have a really bad code base so it might be the result of it. Keep in mind that you need strong machine for that, if it's your PC it's ok but Netbeans on a remote server (like I tried) is really slow unless you have a decent hardware. There are few simple refactorings for C++ with nice preview option, definitely worth a try. You can get a whole Sun C++ pack from here: <http://developers.sun.com/sunstudio/downloads/express/>
Netbeans or Eclipse for C++?
[ "", "c++", "eclipse", "netbeans", "" ]
I have a table containing the runtimes for generators on different sites, and I want to select the most recent entry for each site. Each generator is run once or twice a week. I have a query that will do this, but I wonder if it's the best option. I can't help thinking that using WHERE x IN (SELECT ...) is lazy and not the best way to formulate the query - any query. The table is as follows: ``` CREATE TABLE generator_logs ( id integer NOT NULL, site_id character varying(4) NOT NULL, start timestamp without time zone NOT NULL, "end" timestamp without time zone NOT NULL, duration integer NOT NULL ); ``` And the query: ``` SELECT id, site_id, start, "end", duration FROM generator_logs WHERE start IN (SELECT MAX(start) AS start FROM generator_logs GROUP BY site_id) ORDER BY start DESC ``` There isn't a huge amount of data, so I'm not worried about optimizing the query. However, I do have to do similar things on tables with 10s of millions of rows, (big tables as far as I'm concerned!) and there optimisation is more important. So is there a better query for this, and are inline queries generally a bad idea?
I would use joins as they perform much better then "IN" clause: ``` select gl.id, gl.site_id, gl.start, gl."end", gl.duration from generator_logs gl inner join ( select max(start) as start, site_id from generator_logs group by site_id ) gl2 on gl.site_id = gl2.site_id and gl.start = gl2.start ``` Also as [Tony pointed out](https://stackoverflow.com/questions/308456/are-inline-queries-a-bad-idea#308505) you were missing correlation in your original query
Should your query not be correlated? i.e.: ``` SELECT id, site_id, start, "end", duration FROM generator_logs g1 WHERE start = (SELECT MAX(g2.start) AS start FROM generator_logs g2 WHERE g2.site_id = g1.site_id) ORDER BY start DESC ``` Otherwise you will potentially pick up non-latest logs whose start value happens to match the latest start for a different site. Or alternatively: ``` SELECT id, site_id, start, "end", duration FROM generator_logs g1 WHERE (site_id, start) IN (SELECT site_id, MAX(g2.start) AS start FROM generator_logs g2 GROUP BY site_id) ORDER BY start DESC ```
Are inline queries a bad idea?
[ "", "sql", "postgresql", "" ]
I have to delete some rows from a data table. I've heard that it is not ok to change a collection while iterating through it. So instead of a for loop in which I check if a row meets the demands for deletion and then mark it as deleted, I should first iterate through the data table and add all of the rows in a list, then iterate through the list and mark the rows for deletions. What are the reasons for this, and what alternatives do I have (instead of using the rows list I mean)?.
You can remove elements from a collection if you use a simple `for` loop. Take a look at this example: ``` var l = new List<int>(); l.Add(0); l.Add(1); l.Add(2); l.Add(3); l.Add(4); l.Add(5); l.Add(6); for (int i = 0; i < l.Count; i++) { if (l[i] % 2 == 0) { l.RemoveAt(i); i--; } } foreach (var i in l) { Console.WriteLine(i); } ```
Iterating Backwards through the List sounds like a better approach, because if you remove an element and other elements "fall into the gap", that does not matter because you have already looked at those. Also, you do not have to worry about your counter variable becoming larger than the .Count. ``` List<int> test = new List<int>(); test.Add(1); test.Add(2); test.Add(3); test.Add(4); test.Add(5); test.Add(6); test.Add(7); test.Add(8); for (int i = test.Count-1; i > -1; i--) { if(someCondition){ test.RemoveAt(i); } } ```
How to modify or delete items from an enumerable collection while iterating through it in C#
[ "", "c#", "collections", "iteration", "" ]
What is the fastest way to find out whether two `ICollection<T>` collections contain precisely the same entries? Brute force is clear, I was wondering if there is a more elegant method. We are using C# 2.0, so no extension methods if possible, please! Edit: the answer would be interesting both for ordered and unordered collections, and would hopefully be different for each.
use C5 <http://www.itu.dk/research/c5/> [ContainsAll](http://www.itu.dk/research/c5/Release1.1/c5doc/types/C5.ICollection_1.htm#T:C5.ICollection%601|M:C5.ICollection%601.ContainsAll%60%601(System.Collections.Generic.IEnumerable%7B%60%600%7D)) > " Check if all items in a > supplied collection is in this bag > (counting multiplicities). > The > items to look for. > > True if all items are > found." ``` [Tested] public virtual bool ContainsAll<U>(SCG.IEnumerable<U> items) where U : T { HashBag<T> res = new HashBag<T>(itemequalityComparer); foreach (T item in items) if (res.ContainsCount(item) < ContainsCount(item)) res.Add(item); else return false; return true; } ```
First compare the .**Count** of the collections if they have the same count the do a brute force compare on all elements. Worst case scenarios is O(n). This is in the case the order of elements needs to be the same. The second case where the order is not the same, you need to use a dictionary to store the count of elements found in the collections: Here's a possible algorithm * Compare collection Count : return false if they are different * Iterate the first collection + If item doesn't exist in dictionary then add and entry with Key = Item, Value = 1 (the count) + If item exists increment the count for the item int the dictionary; * Iterate the second collection + If item is not in the dictionary the then return false + If item is in the dictionary decrement count for the item - If count == 0 the remove item; * return Dictionary.Count == 0;
Fastest way to find out whether two ICollection<T> collections contain the same objects
[ "", "c#", "performance", "collections", "c#-2.0", "equality", "" ]
How much do using smart pointers, particularly boost::shared\_ptr cost more compared to bare pointers in terms of time and memory? Is using bare pointers better for performance intensive parts of gaming/embedded systems? Would you recommend using bare pointers or smart pointers for performance intensive components?
Dereferencing smart pointers is typically trivial, certainly for boost in release mode. All boost checks are at compile-time. (Smart pointers could in theory do smart stuff across threads). This still leaves a lot of other operations. Nicola mentioned construction, copying and destruction. This is not the complete set, though. Other important operations are swapping, assignment and resetting to NULL. Basically, any operation that requires smartness. Note that some of these operations are excluded by some smart pointers. E.g. `boost::scoped_ptr` cannot even be copied, let alone be assigned. As this leaves less operations, the implementation can be optimized for these fewer methods. In fact, with TR1 coming up, it's quite likely that compilers can do better with smart pointers than raw pointers. E.g. it's possible that a compiler can prove that a smart non-copyable pointer is not aliased in some situations, merely because it's non-copyable. Think about it: aliasing occurs when two pointers are created pointing to the same object. If the first pointer cannot be copied, how would a second pointer end up pointing to the same object? (There are ways around that, too - operator\* has to return an lvalue)
Boost provide different smart pointers. Generally both the memory occupation, which varies in accordance to the kind of smart pointer, and the performance should not be an issue. For a performance comparison you can check this <http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/smarttests.htm>. As you can see only construction, copy and destruction are taken into account for the performance comparison, which means that dereferencing a smart pointer has supposedly the same cost as that of a raw pointer. The following snippet demonstrates that there's no performance loss by using a `shared_ptr<>` in place of a raw pointer: ``` #include <iostream> #include <tr1/memory> int main() { #ifdef USE_SHARED_PTR std::tr1::shared_ptr<volatile int> i(new int(1)); #else volatile int * i = new int(1); #endif long long int h = 0; for(long long int j=0;j < 10000000000LL; j++) { h += *i; } std::cout << h << std::endl; return 0; } ```
C++ Smart Pointer performance
[ "", "c++", "boost", "smart-pointers", "" ]
I often use this recursive 'visitor' in F# ``` let rec visitor dir filter= seq { yield! Directory.GetFiles(dir, filter) for subdir in Directory.GetDirectories(dir) do yield! visitor subdir filter} ``` Recently I've started working on implementing some F# functionality in C#, and I'm trying to reproduce this as IEnumerable, but I'm having difficulty getting any further than this: ``` static IEnumerable<string> Visitor(string root, string filter) { foreach (var file in Directory.GetFiles(root, filter)) yield return file; foreach (var subdir in Directory.GetDirectories(root)) foreach (var file in Visitor(subdir, filter)) yield return file; } ``` What I don't understand is why I have to do a double foreach in the C# version for the recursion, but not in F#... Does the seq {} implicitly do a 'concat'?
`yield!` does a 'flatten' operation, so it integrates the sequence you passed it into the outer sequence, implicitly performing a `foreach` over each element of the sequence and `yield` on each one.
There is no simple way to do this. You could workaround this by defining a C# type that can store either one value or a sequence of values - using the F# notation it would be: ``` type EnumerationResult<'a> = | One of 'a | Seq of seq<'a> ``` (translate this to C# in any way you like :-)) Now, you could write something like: ``` static IEnumerable<EnumerationResult<string>> Visitor (string root, string filter) { foreach (var file in Directory.GetFiles(root, filter)) yield return EnumerationResult.One(file); foreach (var subdir in Directory.GetDirectories(root)) yield return EnumerationResult.Seq(Visitor(subdir, filter)) } } ``` To use it, you'd have to write a function that flattens EnumerationResult, which could be an extension method in C# with the following signature: ``` IEnumerable<T> Flatten(this IEnumerable<EnumerationResult<T>> res); ``` Now, this is a part where it gets tricky - if you implemented this in a straighforward way, it would still contain "forach" to iterate over the nested "Seq" results. However, I believe that you could write an optimized version that wouldn't have quadratic complexity. Ok.. I guess this is a topic for a blog post rather than something that could be fully described here :-), but hopefully, it shows an idea that you can try following! *[EDIT: But of course, you can also use naive implementation of "Flatten" that would use "SelectMany" just to make the syntax of your C# iterator code nicer]*
Writing the F# recursive folder visitor in C# - seq vs IEnumerable
[ "", "c#", "f#", "" ]
I want to check that two passwords are the same using Dojo. Here is the HTML I have: > `<form id="form" action="." dojoType="dijit.form.Form" /`> > > `<p`>Password: `<input type="password" > name="password1" > id="password1" > dojoType="dijit.form.ValidationTextBox" > required="true" > invalidMessage="Please type a password" /`>`</p`> > > `<p`>Confirm: `<input type="password" > name="password2" > id="password2" > dojoType="dijit.form.ValidationTextBox" > required="true" > invalidMessage="This password doesn't match your first password" /`>`</p`> > > `<div dojoType="dijit.form.Button" onClick="onSave"`>Save`</div`> > > `</form`> Here is the JavaScript I have so far: > `var onSave = function() { > if(dijit.byId('form').validate()) { alert('Good form'); } > else { alert('Bad form'); } > }` Thanks for your help. I could do this in pure JavaScript, but I'm trying to find the Dojo way of doing it.
This will get you a lot closer * setting intermediateChanges=false keeps the validator running at every keystroke. * the validation dijit's constraint object is passed to its validator. Use this to pass in the other password entry * dijit.form.Form automatically calls isValid() on all its child dijits when it's submitted, and cancels submittion if they don't all validate. I though the invalid ones would get their error message, but they don't. That's left as an exercise for the reader ;-) the validation function: ``` function confirmPassword(value, constraints) { var isValid = false; if(constraints && constraints.other) { var otherInput = dijit.byId(constraints.other); if(otherInput) { var otherValue = otherInput.value; console.log("%s == %s ?", value, otherValue); isValid = (value == otherValue); } } return isValid; } function onsubmit() { var p1 = dijit.byId('password1').value; var p2 = dijit.byId('password2').value; return p1 == p2; } ``` and the input objects: ``` <p>Password: <input type="password" name="password1" id="password1" dojoType="dijit.form.ValidationTextBox" required="true" intermediateChanges=false invalidMessage="Please type a password" /></p> <p>Confirm: <input type="password" name="password2" id="password2" dojoType="dijit.form.ValidationTextBox" required="true" constraints="{'other': 'password1'}" validator=confirmPassword intermediateChanges=false invalidMessage="This password doesn't match your first password" /></p> ```
Even easier, use the pre-written Dojox widget, **dojox.form.PasswordValidator**. <http://docs.dojocampus.org/dojox/form/PasswordValidator> It does everything you want straight out of the box!
Password checking in dojo
[ "", "javascript", "security", "dojo", "" ]
In Firefox when you add an `onclick` event handler to a method an event object is automatically passed to that method. This allows, among other things, the ability to detect which specific element was clicked. For example ``` document.body.onclick = handleClick; function handleClick(e) { // this works if FireFox alert(e.target.className); } ``` Is there any way to approximate this in IE? I need to be able to detect which element is clicked from an event handler on the body element.
Here is how would I do it in case I cannot use jQuery ``` document.body.onclick = handleClick; function handleClick(e) { //If "e" is undefined use the global "event" variable e = e || event; var target = e.srcElement || e.target; alert(target.className); } ``` And here is a jQuery solution ``` $(document.body).click(function(e) { alert($(this).attr("class")); }); ```
That is not the approved notation to add events to dom nodes. ``` if (el.addEventListener){ el.addEventListener('click', modifyText, false); } else if (el.attachEvent){ el.attachEvent('onclick', modifyText); } ``` Is the recommended Notation for binding click events cross-browser friendly. See: * <http://www.quirksmode.org/js/events_advanced.html> * <http://developer.mozilla.org/En/DOM/Element.addEventListener> Also, when an event is clicked, the callback function that is executed contains an object "this" which is the entity that was clicked. ``` function foo() { window.open(this.src, '_blank'); } ```
Firefox style onclick arguments in IE
[ "", "javascript", "dom-events", "" ]
Given the below XML snippet I need to get a list of name/value pairs for each child under DataElements. XPath or an XML parser cannot be used for reasons beyond my control so I am using regex. ``` <?xml version="1.0"?> <StandardDataObject xmlns="myns"> <DataElements> <EmpStatus>2.0</EmpStatus> <Expenditure>95465.00</Expenditure> <StaffType>11.A</StaffType> <Industry>13</Industry> </DataElements> <InteractionElements> <TargetCenter>92f4-MPA</TargetCenter> <Trace>7.19879</Trace> </InteractionElements> </StandardDataObject> ``` The output I need is: [{EmpStatus:2.0}, {Expenditure:95465.00}, {StaffType:11.A}, {Industry:13}] The tag names under DataElements are dynamic and so cannot be expressed literally in the regex. The tag names TargetCenter and Trace are static and could be in the regex but if there is a way to avoid hardcoding that would be preferable. ``` "<([A-Za-z0-9]+?)>([A-Za-z0-9.]*?)</" ``` This is the regex I have constructed and it has the problem that it erroneously includes {Trace:719879} in the results. Relying on new-lines within the XML or any other apparent formatting is not an option. Below is an approximation of the Java code I am using: ``` private static final Pattern PATTERN_1 = Pattern.compile(..REGEX..); private List<DataElement> listDataElements(CharSequence cs) { List<DataElement> list = new ArrayList<DataElement>(); Matcher matcher = PATTERN_1.matcher(cs); while (matcher.find()) { list.add(new DataElement(matcher.group(1), matcher.group(2))); } return list; } ``` How can I change my regex to only include data elements and ignore the rest?
This should work in Java, if you can assume that between the DataElements tags, everything has the form value. I.e. no attributes, and no nested elements. ``` Pattern regex = Pattern.compile("<DataElements>(.*?)</DataElements>", Pattern.DOTALL); Matcher matcher = regex.matcher(subjectString); Pattern regex2 = Pattern.compile("<([^<>]+)>([^<>]+)</\\1>"); if (matcher.find()) { String DataElements = matcher.group(1); Matcher matcher2 = regex2.matcher(DataElements); while (matcher2.find()) { list.add(new DataElement(matcher2.group(1), matcher2.group(2))); } } ```
XML is not a regular language. You **cannot** parse it using a regular expression. An expression you think will work will break when you get nested tags, then when you fix that it will break on XML comments, then CDATA sections, then processor directives, then namespaces, ... It cannot work, use an XML parser.
Parsing XML with REGEX in Java
[ "", "java", "xml", "regex", "" ]
My Java application is saving stuff in 'user.home' but on windows this does not seem to be the correct path to save application information (as a friend told me). An other option is using the preferences api but it's not possible to set up the hsqldb location using the preferences api. Also, I want all files to be available in the same folder (local database, config, cache, ...). I'm looking for some example code or a framework that takes care of os-specific stuff.
On my WinXP Pro SP3 system, user.home points to `C:\Documents and settings\<username>` Lot of applications just store their data there (instead of this path + Application data, but some others go down to there), creating a directory in Unix style, ie. dot + application name (examples: .antexplorer, .sqlworkbench, .squirrel-sql, .SunDownloadManager, .p4qt, .gimp-2.4, etc.). Looks like a decent, common practice...
It's unusual for a window app to save data in user.home but not "wrong". Windows applications love to spread their data all over the place (a bit in the registry, a bit in the application's install directory, a bit in the Windows directory, a bit in System32, a bit here and a bit there). In the end, this makes it impossible to cleanly backup or remove something which results in the famous "Windows rot" (i.e. you have to reinstall every few months). Anyway. If you really don't want to use user.home (and I see no reason not to), use code like [this from Apache commons-lang](http://commons.apache.org/lang/xref/org/apache/commons/lang/SystemUtils.html#1007) to figure out if you're running on Windows. If this yields true, pop up a directory selection dialog where the user can specify where they want to save their data. Save this information in Preferences and use this path the next time when your app is started. This way, users can specify where they want their data and you only have to leave one bit of information in the prefs.
Saving user settings/database/cache... in Java (On every OS)
[ "", "java", "operating-system", "settings", "configuration-files", "" ]
I am using a custom validator to compare value in two text box. This is comparing the values fine. But it says "025" and "25" are different.. can this do a float comparision. the custom validator i am using is ``` <asp:CompareValidator id="compval" runat="server" ControlToValidate="txtBox1" ErrorMessage="There values are not equal." Enabled="False" ControlToCompare="txtBox2">*</asp:CompareValidator></TD> ``` Please let me know if this is possible.
Use System.Double.Parse(value) to convert both to a floating point number, and compare those numbers. You can also use TryParse if you don't want to handle exceptions if the value is not a valid floating point number. See also: * <http://msdn.microsoft.com/en-us/library/system.double.parse.aspx> * <http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx>
The only thing I can think of without seeing your validation code is that 025 is being interpreted as an octal number (in C, putting a zero before an integer means it's in base 8). Then 025 would be 21 in base-10 and your two numbers wouldn't be the same. I'm not sure how you'd come up with that, though. I tested out a few of the Parse() functions and they all convert the string "025" to base-10 25.
custom validation to compare the float value of two text box
[ "", "c#", ".net", "asp.net", "vb.net", "" ]