Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
In my code I loop though `raw_input()` to see if the user has requested to quit. My app can quit before the user quits, but my problem is the app is still alive until I enter a key to return from the blocking function `raw_input()`. Can I do to force `raw_input()` to return by maybe sending it a fake input? Could I terminate the thread that it's on? (the only data it has is a single variable called `wantQuit`).
You can use this time out function that wraps your function. Here's the recipe from: <http://code.activestate.com/recipes/473878/> ``` def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None): '''This function will spwan a thread and run the given function using the args, kwargs and return the given default value if the timeout_duration is exceeded ''' import threading class InterruptableThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.result = default def run(self): try: self.result = func(*args, **kwargs) except: self.result = default it = InterruptableThread() it.start() it.join(timeout_duration) if it.isAlive(): return it.result else: return it.result ```
Why don't you just mark the thread as daemonic? From the [docs](http://docs.python.org/library/threading.html#id1): > A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon attribute.
python exit a blocking thread?
[ "", "python", "multithreading", "raw-input", "" ]
Sometimes I've made a namespace in C# (I don't know if the problem is the same in VB.NET) containing 'System' and when I include it from a different DLL it goes crazy and conflicts with everything containing 'System'. This leads to crazy errors such as the following : > The type or namespace name > 'ServiceModel' does not exist in the > namespace 'RR.System' > > The type or namespace name 'Runtime' > does not exist in the namespace > 'RR.System' > > The type or namespace name > 'SerializableAttribute' does not exist > in the namespace 'RR.System' If you don't know what I'm talking about then good for you :) I'm sure many have seen this issue. I'm not completely sure why it does this. It will occur even in files, such as generated code for web services that doesn't contain any reference to `RR.System`. This all occurs just because I'm including `RR.System` the DLL in a different project. How can I avoid this happening? Or fix it?
I still don't see why a *child* namespace conflicts with a *root* namespace? All types under a namespace can be fully qualified, and the fully qualified names refer to different types. e.g. ``` System.Abc.Xyz.Type ``` has nothing in relation to ``` Abc.Xyz.System.Type ``` The `System` in the first case refers to a completely different concept (The Company name under the guidelines), whereas the `System` in the second case could refer to the product or subsystem name. If root namespaces can cause this kind of interference then surely that's a big problem because I may choose to call my new rainforest monitoring product `Amazon` and put all my types under `MyCompany.Amazon`. Then later on I may choose to store my data using the S3 storage and suddenly the namespace Amazon causes a conflict. We've just run into the same issue as our project is split into 3 major sub-systems - Database, User and System. These seem like obvious child namespaces under our MyCompany root namespace. Remember, this has nothing to do with Using statements as Simon said "It will occur even in files, such as generated code for web services that doesn't contain any reference to RR.System" **UPDATE:** The following Stack Overflow question is along the same lines. However the MSDN article it points to discusses a class name called System hiding a namespace (fair enough) and also using System as a top-level namespace (fair enough). However it does not discuss why a child namespace conflicts with a root one. Stack Overflow Q: [Is global:: a bad code smell in C#?](https://stackoverflow.com/questions/1548242/is-global-a-bad-code-smell-in-c) MSDN Article: [How to: Use the Namespace Alias Qualifier](http://msdn.microsoft.com/en-us/library/c3ay4x3d%28VS.80%29.aspx)
To avoid confusion, you can fully qualify your namespace references: ``` global::System.ServiceModel ``` etc.
How do I make a namespace containing 'System' in .NET without it conflicting?
[ "", "c#", ".net", "" ]
I asked a question about "How to read a text file reversely with iterator in C#" sometime ago. [Please see the link](https://stackoverflow.com/questions/452902/how-to-read-a-text-file-reversely-with-iterator-in-c) Jon Skeet was very kind to provide a solution for me. But I still have a question how to close the data file when it is read? It seemed that Jon used a delegate to handle the iterator, which was very interesting. But How I can call something like "file.Close()" to release it when the file was processed? Thanks,
It was just a very regrettable oversight. The answer is - as normal - to use `try`/`finally` or a `using` statement. That way the file will be closed even if an exception is thrown, and even if the caller doesn't iterate all the way back to the start of the file. However, it *does* rely on the caller calling `Dispose` on the `IEnumerator<T>`. Fortunately that's handled automatically by a `foreach` loop in C#, but if you ever use `GetEnumerator()`/`MoveNext()`/`Current` explicitly, you should be careful and write code like this: ``` using (IEnumerator<string> iterator = foo.GetEnumerator()) { while (iterator.MoveNext()) { string bar = iterator.Current; // etc } } ``` Fortunately there aren't very many times when you need to do this :) I've got more details as to how all of this works under the covers in my [iterator implementation article](http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx) which you may find useful.
Jon's code has a call to Dispose method when the file cannot be read further. Is this what you are looking for? Dispose will call Close & release the file handle.
How to close the File after it is read from backward?
[ "", "c#", "" ]
I am calling a web Method from javascript. The web method returns an array of customers from the northwind database. The example I am working from is here: [Calling Web Services with ASP.NET AJAX](http://www.asp.net/learn/ajax/tutorial-05-cs.aspx) I dont know how to write this javascript method: **CreateCustomersTable** This would create the html table to display the data being returned. Any help would be appreciated. My javascript ``` function GetCustomerByCountry() { var country = $get("txtCountry").value; AjaxWebService.GetCustomersByCountry(country, OnWSRequestComplete, OnWSRequestFailed); } function OnWSRequestComplete(results) { if (results != null) { CreateCustomersTable(results); //GetMap(results); } } function CreateCustomersTable(result) { alert(result); if (document.all) //Filter for IE DOM since other browsers are limited { // How do I do this? } } else { $get("divOutput").innerHTML = "RSS only available in IE5+"; } } ``` My web Method ``` [WebMethod] public Customer[] GetCustomersByCountry(string country) { NorthwindDALTableAdapters.CustomersTableAdapter adap = new NorthwindDALTableAdapters.CustomersTableAdapter(); NorthwindDAL.CustomersDataTable dt = adap.GetCustomersByCountry(country); if (dt.Rows.Count <= 0) { return null; } Customer[] customers = new Customer[dt.Rows.Count]; for (int i = 0; i < dt.Rows.Count; i++) { NorthwindDAL.CustomersRow row = (NorthwindDAL.CustomersRow)dt.Rows[i]; customers[i] = new Customer(); customers[i].CustomerId = row.CustomerID; customers[i].Name = row.ContactName; } return customers; } ```
Try to look what is the result variable value in debug mode. If the structure seems the structure that i'm imagining, something like this could work: ``` function CreateCustomersTable(result) { var str = '<table>'; str += '<tr><th>Id</th><th>Name</th></tr>'; for ( var i=0; i< result.length; i++){ str += '<tr><td>' + result[i].CustomerId + '</td><td>' + result[i].Name + '</td></tr>'; } str += '</table>'; return str; } ``` And then You can do somethig like this: ``` var existingDiv = document.getElementById('Id of an existing Div'); existingDiv.innerHTML = CreateCustomersTable(result); ``` I wish this help you.
Something like this, assuming you have JSON returned in the "result" value. The "container" is a div with id of "container". I'm cloning nodes to save memory, but also if you wanted to assign some base classes to the "base" elements. ``` var table = document.createElement('table'); var baseRow = document.createElement('tr'); var baseCell = document.createElement('td'); var container = document.getElementById('container'); for(var i = 0; i < results.length; i++){ //Create a new row var myRow = baseRow.cloneNode(false); //Create a new cell, you could loop this for multiple cells var myCell = baseCell.cloneNode(false); myCell.innerHTML = result.value; //Append new cell myRow.appendChild(myCell); //Append new row table.appendChild(myRow); } container.appendChild(table); ```
Create HTML table out of object array in Javascript
[ "", "asp.net", "javascript", "web-services", "asp.net-ajax", "asmx", "" ]
I have an application that opens a new window on clicking a link. This spawns a page that holds a Java applet. The problem I am having is that clicking the same link reloads the page, which resets the Java application. Is there any way to trap this? Two solutions that would be acceptable are: 1. Allow multiple windows to be opened from the click handler 2. Ignore subsequent requests if the window is already open Apologies for being a Javascript newbie - it's not really my main thing. The code attached to the handler is ``` function launchApplication(l_url, l_windowName) { var l_width = screen.availWidth; var l_height = screen.availHeight; var l_params = 'status=1' + ',resizable=1' + ',scrollbars=1' + ',width=' + l_width + ',height=' + l_height + ',left=0' + ',top=0'; winRef = window.open(l_url, l_windowName, l_params); winRef.moveTo(0,0); winRef.resizeTo(l_width, l_height); } ``` EDIT: Thanks for the replies - I modified the suggestions slightly so that I could have more than one URL opened via the function. EDIT2: There is another version of this code at [Check for a URL open on another window](https://stackoverflow.com/questions/528941/how-can-i-check-for-an-open-url-in-another-window) ``` var g_urlarray = []; Array.prototype.has = function(value) { var i; for (var i in this) { if (i === value) { return true; } } return false; }; function launchApplication(l_url, l_windowName) { var l_width = screen.availWidth; var l_height = screen.availHeight; var winRef; var l_params = 'status=1' + ',resizable=1' + ',scrollbars=1' + ',width=' + l_width + ',height=' + l_height + ',left=0' + ',top=0'; if (g_urlarray.has(l_url)) { winRef = g_urlarray[l_url]; } alert(winRef); if (winRef == null || winRef.closed) { winRef = window.open(l_url, l_windowName, l_params); winRef.moveTo(0,0); winRef.resizeTo(l_width, l_height); g_urlarray[l_url] = winRef; } } ```
I'd do it like this - basically store all the referenced opened windows on the function itself. When the function fires, check if the window doesn't exist or has been close - of so, launch the popup. Otherwise, focus on the existing popup window for that request. ``` function launchApplication(l_url, l_windowName) { if ( typeof launchApplication.winRefs == 'undefined' ) { launchApplication.winRefs = {}; } if ( typeof launchApplication.winRefs[l_windowName] == 'undefined' || launchApplication.winRefs[l_windowName].closed ) { var l_width = screen.availWidth; var l_height = screen.availHeight; var l_params = 'status=1' + ',resizable=1' + ',scrollbars=1' + ',width=' + l_width + ',height=' + l_height + ',left=0' + ',top=0'; launchApplication.winRefs[l_windowName] = window.open(l_url, l_windowName, l_params); launchApplication.winRefs[l_windowName].moveTo(0,0); launchApplication.winRefs[l_windowName].resizeTo(l_width, l_height); } else { launchApplication.winRefs[l_windowName].focus() } } ```
You need to perform 2 tests... 1 check if the popup window is defined, and 2 check if it was closed. ``` if(typeof(winRef) == 'undefined' || winRef.closed){ //create new winRef = window.open(....); } else { //it exists, load new content (if necs.) winRef.location.href = 'your new url'; //give it focus (in case it got burried) winRef.focus(); } ```
JavaScript window.open only if the window does not already exist
[ "", "javascript", "popup", "window", "" ]
I am studying for my midterm exam. There is going to be a question about setting up an array dynamically, and maybe doing a copy constructor, a destructor and overloading the assignment operator. Can you please verify if I am correct. Also I don't understand what overloading the assignment operator means. Can you help me out with this? ``` class A { int* myArray; //basically I created a pointer called myArray, A() //are my copy constructors correct? A(), and A(int size)? { myArray = 0; } A(int size) { myArray = new int[size]; } ~A() // I think my destructor is correct { delete [] myArray; } ``` Can you check my code please? Also how do I overload assignment operator? Thanks in advance.
The copy constructor is used for creation of object based on another's instance of the same type. You don't have such. You can define it using code like this: ``` A(const A &other) { myArray = new int[other._size]; _size = other._size; memcpy(myArray, other.myArray, sizeof(int) * _size); } ``` You should change your class, so it will store \_size of array, you also need to change visibility of your constructors and destructor to public. The overloaded assignment operator should look like this: ``` const A &operator=(const A &other) { if(this == &other) return *this; // handling of self assignment, thanks for your advice, arul. delete[] myArray; // freeing previously used memory myArray = new int[other._size]; _size = other._size; memcpy(myArray, other.myArray, sizeof(int) * _size); return *this; } ``` You also can add a check of equality of array sizes in this assignment operator, so you will reuse your dynamic array without unnecessary reallocations of memory.
You have correctly defined 2 overloaded constructors and a destructor. However, you haven't defined an **explicit copy constructor** properly. Normally the compiler will generate one for you, and this is called an **implicit copy constructor**. The problem with the auto-generated implicit copy constructor in your particular case is that it will only perform a shallow copy of *myArray*, where it shares the same pointer value but hasn't allocated its own section of memory for myArray. This means if you delete myArray in the original object, it will affect the copy which is most likely not what you want. Defining an explicit copy constructor like this will help: ``` A(const A& copy) : _size(copy.size), myArray(new int[copy.size]) { // #include <algorithm> for std::copy std::copy(copy.data, copy.data + copy.size, data); } ``` (Source: Copied from [Wikipedia](http://en.wikipedia.org/wiki/Copy_constructor)) If you define the copy constructor like this, you should not need to overload the assignment operator. If you create a new object, and assign it to the first object you created, you will successfully create an independent copy of the first object. **Edit:** From [this article](http://en.wikipedia.org/wiki/Assignment_operator_in_C%2B%2B): > The copy assignment operator differs > from the copy constructor in that it > must clean up the data members of the > assignment's target (and correctly > handle self-assignment) whereas the > copy constructor assigns values to > uninitialized data members.
Dynamic array... copy constructor, destructor, overloaded assignment operator
[ "", "c++", "constructor", "" ]
I'm a Python newbie, so bear with me :) I created a file called test.py with the contents as follows: ``` test.py import sys print sys.platform print 2 ** 100 ``` I then ran `import test.py` file in the interpreter to follow an example in my book. When I do this, I get the output with the import error on the end. ``` win32 1267650600228229401496703205376 Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named py ``` Why do I get this error and how do I fix it? Thanks!
Instead of: ``` import test.py ``` simply write: ``` import test ``` This assumes test.py is in the same directory as the file that imports it.
This strange-looking error is a result of how Python imports modules. **Python sees**: ``` import test.py ``` **Python thinks** (simplified a bit): > import module test. > > * search for a test.py in the module search paths > * execute test.py (where you get your output) > * import 'test' as name into current namespace > > import test.py > > * search for file test/py.py > * throw ImportError (no module named 'py') found. Because python allows dotted module names, it just thinks you have a submodule named `py` within the `test` module, and tried to find that. It has no idea you're attempting to import a file.
Why am I getting the following error in Python "ImportError: No module named py"?
[ "", "python", "" ]
I'm currently using this regex `^[A-Z0-9 _]*$` to accept letters, numbers, spaces and underscores. I need to modify it to require at least one number or letter somewhere in the string. Any help would be appreciated! This would be for validating usernames for my website. I'd actually like to support as many characters as I can, but just want to ensure that I prevent code injection and that characters will display fine for all users. So I'm definitely open to regex validation suggestions that would support a wider set of characters.
You simply need to specify your current RE, followed by a letter/number followed by your current RE again: ``` ^[A-Z0-9 _]*[A-Z0-9][A-Z0-9 _]*$ ``` Since you've now stated they're Javascript REs, there's a useful site [here](http://www.regular-expressions.info/javascriptexample.html) where you can test the RE against input data. If you want lowercase letters as well: ``` ^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$ ```
To go ahead and get a point out there, instead of repeatedly using these: ``` [A-Za-z0-9 _] [A-Za-z0-9] ``` I have two (hopefully better) replacements for those two: ``` [\w ] [^\W_] ``` The first one matches any word character (alphanumeric and `_`, as well as Unicode) and the space. The second matches anything that *isn't* a non-word character or an underscore (alphanumeric only, as well as Unicode). If you don't want Unicode matching, then stick with the other answers. But these just look easier on the eyes (in my opinion). Taking the "preferred" answer as of this writing and using the shorter regexes gives us: ``` ^[\w ]*[^\W_][\w ]*$ ``` Perhaps more readable, perhaps less. Certainly shorter. Your choice. EDIT: Just as a note, I am assuming Perl-style regexes here. Your regex engine may or may not support things like \w and \W. EDIT 2: Tested mine with the JS regex tester that someone linked to and some basic examples worked fine. Didn't do anything extensive, just wanted to make sure that \w and \W worked fine in JS. EDIT 3: Having tried to test some Unicode with the JS regex tester site, I've discovered the problem: that page uses ISO instead of Unicode. No wonder my Japanese input didn't match. Oh well, that shouldn't be difficult to fix: ``` <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> ``` Or so. I don't know what should be done as far as JavaScript, but I'm sure it's not hard.
Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)
[ "", "javascript", "regex", "" ]
Basically I am storing millions of vector3 values in a list. But right now the vector3s are defined like so: ``` [5,6,7] ``` which I believe is a list. The values will not be modified nor I need any vector3 functionality. Is this the most performant way to do this?
If you are storing millions of them, the best way (both for speed and memory use) is to use [numpy](https://numpy.org/). If you want to avoid numpy and use only built-in python modules, using tuples instead of lists will save you some overhead.
The best way is probably using tuples rather than a list. Tuples are faster than lists, and cannot be modified once defined. <http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences> edit: more specifically, probably a list of tuples would work best: [(4,3,2), (2,4,5)...]
Huge collections in Python
[ "", "python", "performance", "collections", "" ]
I am using MSSQL Server 2005. In my db, I have a table "customerNames" which has two columns "Id" and "Name" and approx. 1,000 results. I am creating a functionality where I have to pick 5 customers randomly every time. Can anyone tell me how to create a query which will get random 5 rows (Id, and Name) every time when query is executed?
``` SELECT TOP 5 Id, Name FROM customerNames ORDER BY NEWID() ``` That said, everybody seems to come to this page for the more general answer to your question: ## [Selecting a random row in SQL](http://www.petefreitag.com/item/466.cfm) ### Select a random row with MySQL: ``` SELECT column FROM table ORDER BY RAND() LIMIT 1 ``` ### Select a random row with PostgreSQL: ``` SELECT column FROM table ORDER BY RANDOM() LIMIT 1 ``` ### Select a random row with Microsoft SQL Server: ``` SELECT TOP 1 column FROM table ORDER BY NEWID() ``` ### Select a random row with IBM DB2 ``` SELECT column, RAND() as IDX FROM table ORDER BY IDX FETCH FIRST 1 ROWS ONLY ``` ### Select a random record with Oracle: ``` SELECT column FROM ( SELECT column FROM table ORDER BY dbms_random.value ) WHERE rownum = 1 ``` ### Select a random row with sqlite: ``` SELECT column FROM table ORDER BY RANDOM() LIMIT 1 ```
``` SELECT TOP 5 Id, Name FROM customerNames ORDER BY NEWID() ```
How to randomly select rows in SQL?
[ "", "sql", "database", "random", "" ]
I'd like to implement a WebService containing a method whose reply will be delayed for less than 1 second to about an hour (it depends if the data is already cached or neeeds to be fetched). Basically my question is what would be the best way to implement this if you are only able to connect from the client to the WebService (no notification possible)? *AFAIK this will only be possible by using some kind of polling. But polling is bad and so I'd rather like to avoid using it. The other extreme could be to just let the connection stay open as long as the method isn't done. But i guess this could end up in slowing down the webserver and the network. I considerd to combine these two technics. Then the client would call the method and the server will return after at least 10 seconds either with the message that the client needs to poll again or the actual result.* What are your thoughts?
You probably want to have a look at [comet](http://en.wikipedia.org/wiki/Comet_(programming))
I would suggest a sort of intelligent polling, if possible: * On first request, return a token to represent the request. This is what gets presented in future requests, so it's easy to check whether or not that request has really completed. * On future requests, hold the connection open for a certain amount of time (e.g. a minute, possibly specified on the client) and return *either* the result *or* a result of "still no results; please try again at X " where X is the best guess you have about when the response will be completed. Advantages: * You allow the client to use the "hold a connection open" model which is relatively expensive (in terms of connections) but allows the response to be served as soon as it's ready. Make sure you don't hold onto a thread each connection though! (And have some kind of time limit...) * By saying when the client should come back, you can implement a backoff policy - even if you don't know when it will be ready, you could have a "backoff for 1, 2, 4, 8, 16, 30, 30, 30, 30..." minutes policy. (You should potentially check that the client isn't ignoring this.) You don't end up with masses of wasted polls for long misses, but you still get quick results quickly.
WebService and Polling
[ "", "c#", ".net", "web-services", "c#-2.0", "" ]
I want to have my ASP C# application to be multi-language. I was planned to do this with a XML file. The thing is, i don't have any experience with this. I mean how, do i start? Is it a good idea to store the languages in an xml file? And how in the code do i set the values for ie my menu buttons? I'd like to work with XML because i never worked before with XML, i want to learn how to deal with cases like this.
You want to look into RESX resource files. These are XML files that can contain texts (and images) and they have standardized handling of localization/translations. Support for this is built right into ASP.NET. There is a guide for how to use it and set it up at: <http://msdn.microsoft.com/en-us/library/fw69ke6f(VS.80).aspx>. The walkthough is pretty detailed and should help you to understand the concepts. My preferred is method described a bit down in the document in the section "Explicit Localization with ASP.NET". Using this you will get a set of XML files with your texts and translations in a fully standardized format.
Do you know about the .Net From automatic translatation (based on .resx) resources ?
C# XML language file
[ "", "c#", "xml", "" ]
I am responding to MouseLeftButtonDown events on elements added to a WPF canvas. It all works fine when clicked (i.e. the eventhandler fires off correctly), but it requires too much precision from the mouse pointer. You have to be perfectly on top of the circle to make it work. I need it to be a little more forgiving; maybe at least 1 or 2 pixles forgiving. The elements on the canvas are nice big circles (about the size of a quarter on the screen), so the circles themselves are not too small, but the StrokeWidth of each one is 1, so it is a thin line. You can see a screenshot here: <http://twitpic.com/1f2ci/full> Most graphics app aren't this picky about the mouse picking, so I want to give the user a familiar experience. How can I make it a little more forgiving.
You can hook up to the MouseLeftButtonDown event of your root layout object instead, and check which elements is in range of a click by doing this: ``` List<UIElement> hits = System.Windows.Media.VisualTreeHelper.FindElementsInHostCoordinates(Point, yourLayoutRootElement) as List<UIElement>; ``` <http://msdn.microsoft.com/en-us/library/cc838402(VS.95).aspx> For the Point parameter, you can use the MouseEventArgs parameter e, and call its GetPosition method like this: ``` Point p = e.GetPosition(null) ``` I can't remember whether to use HitTest instead of the FindElementsInHostCoordinates. Try both. <http://msdn.microsoft.com/en-us/library/ms608752.aspx> You could create 4 Point objects from the mouse position to create a fake tolerence effect, and call either FindElementsInHostCoordinates or HitTest for all 4 points.
You might want to try to fill the circle with the Transparent colour to make the whole circle clickable... If that fails, you can also draw helper circles on the same location as the other circles. Make the circle foreground colour Transparent, and make the thickness of the brush a few pixels wider for a more acceptable clickable region around the circle.. Hope this helps!
MouseLeftButtonDown on canvas requires too much precision
[ "", "c#", "wpf", "canvas", "mouse", "precision", "" ]
After my application creates a thread using a `ParameterizedThreadStart` delegate, that thread performs some initialization and runs to completion. Later on, I can observe that this thread is no longer active because its `IsAlive` property is false and `ThreadState` property is `ThreadState.Stopped`. Once a thread reaches this state they remain in my application, still existing as thread objects until my application shuts down. Are there any steps I can take to dispose of them once they're no longer active? I would like to delete the object and deallocate any resources so that any given moment the only thread objects I have are active threads. Thread doesn't implement IDisposable, though, so I'm not sure how I should do this.
You're holding onto the reference to the thread in your code. If you have written code that will check the state of the thread, then that code inherently will keep the thread object alive until the GC collects it. Once you are finished with a thread, or ideally if you don't need to access it, make sure you null all references to it. Thread doesn't implement IDisposable because as you've made clear this wouldn't make sense for a thread. Threads are native in .Net so you don't have to worry about leaks. If you're certain they will stop then just delete them from your list once you are sure it has finished.
It sounds like you need to let go of your reference to the `Thread` object, so the garbage collector can discard it. Just set the reference you have to `null`, and let the GC do its job when it's ready. Depending on your situation, you may wish to use a `WeakReference` (or my friend Cyrus' [`WeakReference<T>`](http://blogs.msdn.com/jaybaz_ms/archive/2004/05/07/127700.aspx)).
C# Managed Thread Cleanup
[ "", "c#", ".net", "multithreading", "" ]
I have SQL SELECT statement that returns: ``` Error: ORA-00600: internal error code, arguments: [qerpfAllocateR], [], [], [], [], [], [], [] ``` If I narrow my results by adding one more condition in WHERE clause everything is ok. Anyone knows what is happening? EDIT: ``` select * from ( select tbl1.col1, ..., tbl1.points from table1 tbl1, table2 tbl2 where tbl1.tbl2FK = tbl2.PK and tbl2.col1 = someNumber and tbl1.dateColumn = to_date('27-10-2008','dd-mm-yyyy') order by tbl1.points desc ) s where rownum <= 3 ``` EDIT2: My DB admin suggested solution that works: ``` select * from (select rank() over (order by tbl1.points desc) rank, tbl1.col1, ..., tbl1.points from table1 tbl1, table2 tbl2 where tbl1.tbl2FK = tbl2.PK and tbl2.col1 = someNumber and tbl1.dateColumn = to_date('27-10-2008','dd-mm-yyyy')) s where s.rank <= 3 ```
Good luck with getting support from Oracle... Seriously though, every time I hit this problem, rearranging the query a little bit usually helps. Maybe fiddling around with the indexes a bit.
The ORA-0600 error indicates an internal error in Oracle itself. You're most likely hitting an Oracle bug. If you go to <http://metalink.oracle.com>, you can look up the exact bug, if it is known, by pasting the "arguments" and full stack trace into the ORA-0600 lookup tool. See metalink note 153788.1. If there's a known bug with that description, it's likely that there's already a patch available for you to download and install. If it's not a known bug, contact support.
Oracle ORA-00600
[ "", "sql", "oracle", "plsql", "ora-00600", "" ]
What JavaScript do I need to use to redirect a parent window from an iframe? I want them to click a hyperlink which, using JavaScript or any other method, would redirect the parent window to a new URL.
``` window.top.location.href = "http://www.example.com"; ``` Will redirect the top most parent Iframe. ``` window.parent.location.href = "http://www.example.com"; ``` Will redirect the parent iframe.
I found that `<a href="..." target="_top">link</a>` works too
Redirect parent window from an iframe action
[ "", "javascript", "iframe", "dhtml", "" ]
I have a website that consists of 2 applications: 1. Front end application 2. Backend application The front end has the www domain, whereas the backend has the job subdomain. For example, my front end application has the domain `www.example.com/*`, whereas my backend as the `job.example.com/*`. **My front end application can locate on one server, whereas the back end can locate on another server**. Or they are both stored on the same server. The question now is whether the session variables I stored in the super global \_Session ( PHP) can work across different sub domain. If I set `_Sesssion["SessionID"]` in `www.example.com/*`, can I retrieve the same \_Sesssion["SessionID"] from `job.example.com/*`? Do I need to do special configuration to work?
For using the same sessions on multiple domains/servers, you have to take care of two aspects: * where the session data is stored so that both domains/servers can access it, and * how the session identifier is carried along both domains/servers so that. **Storage** For different servers you could write your own [session save handler](http://docs.php.net/session_set_save_handler) that both servers can use. This could for example be a database that both have access to. **Session ID sharing** If you want to share a session ID for multiple domains (might be on the same server or different) and want to use cookies to transport the session ID, you have to [modify the session ID cookie settings](http://docs.php.net/session_set_cookie_params) so that the cookie is valid for both domains. But this is only possible if both domains share the same higher level domain. For `www.example.com` and `jobs.example.com` that share `example.com`, the `$domain` parameter for `session_set_cookie_params()` has to be set to `.example.com`.
Session data is saved in the path given by the [`session_save_path`](http://www.php.net/manual/en/function.session-save-path.php) function, so you need to make that directory accessible to both applications. If they're on the same server, you probably don't need to do anything, but if they're on different servers, you'll have to use some kind of networked filesystem like NFS and mount it such that the session save path is on the networked filesystem for both servers.
Configure _Session to work on applications that are deployed over multiple servers, different subdomain
[ "", "php", "session", "" ]
As a part of our build process we want to execute SQL Scripts consisting of DDL and DML statements against a fresh database instance. ADO.NET Connection/Command can't handle this without parsing and splitting the scripts. The `sqlplus` command line utility can execute scripts only interactively, and isn't suited for batch usage. What am I missing? How can one execute sql scripts when using oracle?
Why do you believe that the SQL*Plus utility isn't suited for batch usage? It's pretty common to use it for running these sorts of scripts-- you can pass the script to SQL*Plus when you invoke it if you'd like, i.e. ``` sqlplus scott/tiger@someDatabase @someScript.sql ``` That is a pretty common way of deploying builds. If the problem is with the way SQL\*Plus is handling errors, you can simply add the line ``` WHENEVER SQLERROR EXIT SQL.SQLCODE ``` to abort and throw the Oracle error number that was encountered. The documentation for the [WHENEVER SQLERROR command](http://download.oracle.com/docs/cd/B19306_01/server.102/b14357/ch12052.htm#i2700066) provides a number of other options as well.
Devdimi, I agree with Erik K. And yes you can include DDL in an anonymous block. ``` DECLARE BEGIN EXECUTE IMMEDIATE 'TRUNCATE TABLE foo'; END; ``` Remember DDL does a commit BEFORE and AFTER it runs. So as part of a transaction it kinda sucks.
How can I execute multiple Oracle SQL statements with .NET
[ "", ".net", "sql", "oracle", "" ]
Where I work we're *finally* coming around to the idea of using strongly typed datasets to encapsulate some of our queries to sqlserver. One of the idea's I've been touting is the strength of the strongly typed column's, mainly for not needing to cast any data. Am I wrong in thinking that strongly-typed-datasets would improve performance in the following situation where there could be potentially thousands of rows? old way: ``` using(DataTable dt = sql.ExecuteSomeQuery()) { foreach (DataRow dr in dt.Rows) { var something = (string)dr["something"]; var somethingelse = (int)dr["somethingelse"]; } } ``` new way: ``` MyDataAdapter.Fill(MyDataset); foreach (DataRow dr in MyDataset.MyDT.Rows) { var something = dr.Something; var somethingelse = dr.SomethingElse; } ``` If the properties are really just doing the casting behind the scenes, I can see how there wouldn't be any speedup at all; perhaps it would take even longer then before with the overhead of the function call in the first place. Are there any other performance strengths / weaknesses of using DataSets we should know about? Thanks!
I'm not sure if there will be any performance improvements using the strongly typed datasets, however you get the added type safety, and with it compiler errors when you mistype a field name, for example. There's an article in [MSDN magazine](http://msdn.microsoft.com/en-us/magazine/cc163877.aspx) about them, to quote a line in it: > The speed in accessing a typed DataSet is comparable to the faster techniques in accessing an untyped DataSet (since a typed DataSet is just a layer over an untyped DataSet) and the readability of the typed DataSet is the best Also, as Stuart B pointed out, the Intellisense alone makes it worthwhile.
If you look at the code generated for a typed dataset, you can see that under each typed call is a call made with the string indexed name. So, they really offer no performance gains, only type safety. I do have a major gripe with nullable fields in typed datasets however. Specifically, if you access an int field which is null, it throws an exception.. you have to call the IsMyfieldNull() call first to determine if it is a null, and avoid referencing it if it is. A real solution for this would be allow nullable type fields, so you do not risk the chance of throwing an exception just for touching a field. This flaw in my mind almost negates the benefits of the stong typing.
Do Strongly Typed Datasets improve performance?
[ "", "c#", ".net", "performance", "dataset", "strongly-typed-dataset", "" ]
I'm looking to convert a string of html entities specifying ASCII codes (ie: &#97;) to the ASCII characters they represent (ie: a). I'm using a property of an object and trying to assign a value. For instance: ``` object.Text(""); ``` When I pass is the string representing the entity, I get the same string back. I can't find the function to convert entities to the characters they represented.
Try the [String.fromCharCode()](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/fromCharCode) function. ``` alert(String.fromCharCode(97)); ``` As you can see, you'll have to strip out the ampersand and pound sign. Best regards...
To convert all numerical character entities in a string to their character equivalents you can do this: ``` str.replace(/&#(\d+);/g, function (m, n) { return String.fromCharCode(n); }) ```
Convert escaped html ASCII codes to plain text using JavaScript
[ "", "javascript", "ascii", "" ]
My web application parses data from an uploaded file and inserts it into a database table. Due to the nature of the input data (bank transaction data), duplicate data can exist from one upload to another. At the moment I'm using hideously inefficient code to check for the existence of duplicates by loading all rows within the date range from the DB into memory, and iterating over them and comparing each with the uploaded file data. Needless to say, this can become very slow as the data set size increases. So, I'm looking to replace this with a SQL query (against a MySQL database) which checks for the existence of duplicate data, e.g. ``` SELECT count(*) FROM transactions WHERE desc = ? AND dated_on = ? AND amount = ? ``` This works fine, but my real-world case is a little bit more complicated. The description of a transaction in the input data can sometimes contain erroneous punctuation (e.g. "BANK 12323 DESCRIPTION" can often be represented as "BANK.12323.DESCRIPTION") so our existing (in memory) matching logic performs a little cleaning on this description before we do a comparison. Whilst this works in memory, my question is can this cleaning be done in a SQL statement so I can move this matching logic to the database, something like: ``` SELECT count(*) FROM transactions WHERE CLEAN_ME(desc) = ? AND dated_on = ? AND amount = ? ``` Where CLEAN\_ME is a proc which strips the field of the erroneous data. Obviously the cleanest (no pun intended!) solution would be to store the *already cleaned* data in the database (either in the same column, or in a separate column), but before I resort to that I thought I'd try and find out whether there's a cleverer way around this. Thanks a lot
> can this cleaning be done in a SQL statement Yes, you can write a [stored procedure](http://dev.mysql.com/doc/refman/5.0/en/stored-programs-views.html) to do it in the database layer: ``` mysql> CREATE FUNCTION clean_me (s VARCHAR(255)) -> RETURNS VARCHAR(255) DETERMINISTIC -> RETURN REPLACE(s, '.', ' '); mysql> SELECT clean_me('BANK.12323.DESCRIPTION'); BANK 12323 DESCRIPTION ``` This will perform very poorly across a large table though. > Obviously the cleanest (no pun intended!) solution would be to store the already cleaned data in the database (either in the same column, or in a separate column), but before I resort to that I thought I'd try and find out whether there's a cleverer way around this. No, as far as databases are concerned the cleanest way is always the cleverest way (as long as performance isn't awful). Do that, and add indexes to the columns you're doing bulk compares on, to improve performance. If it's actually intrinsic to the type of data that desc/dated-on/amount are always unique, then express that in the schema by making it a UNIQUE index constraint.
The easiest way to do that is to add a unique index on the appropriate columns and to use [ON DUPLICATE KEY UPDATE](http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html). I would further recommend transforming the file into a csv and [loading it into a temporary table](http://dev.mysql.com/doc/refman/5.1/en/load-data.html) to get the most out of mysql's builtin functions, which are surely faster than anything that you could write yourself - if you consider that you would have to pull the data into your own application, while mysql does everything in place.
MySQL SELECT statement using Regex to recognise existing data
[ "", "sql", "mysql", "" ]
I am using different analytics tags in one of our web applications. Most of them call a javascript code for tracking. Some tags have url of gif image with querystrings. Example : <http://www.google-analytics.com/__utm.gif?utmwv=45.542> What exactly does this url do? How do they get the values from querystring? Update: (After reading some answers) I know every browser will load the gif which is 1x1 pixel. But how are they getting the values from query string? in the above case how can they retrieve the value of utmwv? Any code samples ?
Basically, you write a script in your preferred language, and map that script to *yourtrackingscript.gif*. ..jpg, png even. Have done this in asp.net using a http handler. The script reads the querystring like any other dynamic page (aspnet, asp, php, anything really), then writes it to a db or log file, or does whatever else you want to do with it. Then set the content-type header appropriately e.g "image/gif", and send back a 1 pixel image, or any other sized image you like. For just a 1 pixel image, I have opened up a 1 pixel spacer.gif type image in a hex editor, and hard coded it as a byte array to send out as the response, will save a little IO overhead if it gets hit a lot, alernatively, you can read a file from disk or DB and send that back instead. This is a commonly used trick in email newsletters to track open rates etc. Often the hardest bit about it is when you don't have enough rights to map the url to the script on a shared machine, but you can develop it as a normal script/program, then get the mapping sorted out once you have it working. Most modern browsers will respond to a an aspx or php (.etc...) url as an image if it sends the right headers, it's older browsers, browser nanny plugins, and email clients that are the most pernickety about it.
Just like you can pass query strings to ASP.NET pages, you can actually pass query strings to any URL; if you use a MVC-based framework like ASP.NET MVC or Rails, capturing the parameters from a URL like this is easy. Then, all you have to do is return a GIF image.
What exactly does this url mean?
[ "", "javascript", "seo", "query-string", "" ]
I have a Subject which offers `Subscribe(Observer*)` and `Unsubscribe(Observer*)` to clients. Subject runs in its own thread (from which it calls `Notify()` on subscribed Observers) and a mutex protects its internal list of Observers. I would like client code - which I don't control - to be able to safely delete an Observer after it is unsubscribed. How can this be achieved? * Holding the mutex - even a recursive mutex - while I notify observers isn't an option because of the deadlock risk. * I could mark an observer for removal in the Unsubscribe call and remove it from the Subject thread. Then clients could wait for a special 'Safe to delete' notification. This looks safe, but is onerous for clients. **Edit** Some illustrative code follows. The problem is how to prevent Unsubscribe happening while Run is at the 'Problem here' comment. Then I could call back on a deleted object. Alternatively, if I hold the mutex throughout rather than making the copy, I can deadlock certain clients. ``` #include <set> #include <functional> #include <boost/thread.hpp> #include <boost/bind.hpp> using namespace std; using namespace boost; class Observer { public: void Notify() {} }; class Subject { public: Subject() : t(bind(&Subject::Run, this)) { } void Subscribe(Observer* o) { mutex::scoped_lock l(m); observers.insert(o); } void Unsubscribe(Observer* o) { mutex::scoped_lock l(m); observers.erase(o); } void Run() { for (;;) { WaitForSomethingInterestingToHappen(); set<Observer*> notifyList; { mutex::scoped_lock l(m); notifyList = observers; } // Problem here for_each(notifyList.begin(), notifyList.end(), mem_fun(&Observer::Notify)); } } private: set<Observer*> observers; thread t; mutex m; }; ``` **Edit** I can't Notify observers while holding the mutex because of the deadlock risk. The most obvious way this can happen - the client calls Subscribe or Unsubscribe from inside Notify - is easily remedied by making the mutex recursive. More insidious is the risk of intermittent deadlock on different threads. I'm in a multithreaded environment, so at any point in a thread's execution, it will typically hold a sequence of locks L1, L2, ... Ln. Another thread will hold locks K1, K2, ... Km. A properly written client will ensure that different threads will always acquire locks in the same order. But when clients interact with my Subject's mutex - call it X - this strategy will be broken: Calls to Subscribe / Unsubscribe acquire locks in the order L1, L2, ... Ln, X. Calls to Notify from my Subject thread acquire locks in the order X, K1, K2, ... Km. If any of the Li or Kj can coincide down any call path, the client suffers an intermittent deadlock, with little prospect of debugging it. Since I don't control the client code, I can't do this.
The "ideal" solution would involve using `shared_ptr` and `weak_ptr`. However, in order to be generic, it also has to account for the issue of `Subject` being dropped before some of its `Observer` (yes, that can happen too). ``` class Subject { public: void Subscribe(std::weak_ptr<Observer> o); void Unsubscribe(std::weak_ptr<Observer> o); private: std::mutex mutex; std::set< std::weak_ptr<Observer> > observers; }; class Observer: boost::noncopyable { public: ~Observer(); void Notify(); private: std::mutex; std::weak_ptr<Subject> subject; }; ``` With this structure, we create a cyclic graph, but with a judicious use of `weak_ptr` so that both `Observer` and `Subject` can be destroyed without coordination. *Note: I have assumed, for simplicity, that an `Observer` observes a single `Subject` at a time, but it could easily observe multiple subjects.* --- Now, it seems that you are stuck with unsafe memory management. This is a quite difficult situation, as you can imagine. In this case, I would suggest an experiment: *an asynchronous `Unsubscribe`*. Or at least, the call to `Unsubscribe` will be synchronous from the outside, but be implemented asynchronously. The idea is simple: we will use the event queue to achieve synchronization. That is: * the call to `Unsubscribe` posts an event in the queue (payload `Observer*`) and then waits * when the `Subject` thread has processed the `Unsubscribe` event(s), it wakes up the waiting thread(s) You can use either busy-waiting or a condition variable, I would advise a condition variable unless performance dictates otherwise. *Note: this solution completely fails to account for `Subject` dying prematurely.*
Unsubscribe() should be synchronous, so that it does not return until Observer is guaranteed not to be in Subject's list anymore. That's the only way to do it safely. ETA (moving my comment to the answer): Since time doesn't seem to be an issue, take and release the mutex between notifying each observer. You won't be able to use for\_each the way you are now, and you'll have to check the iterator to ensure that it's still valid. ``` for ( ... ) { take mutex check iterator validity notify release mutex } ``` That will do what you want.
How do I tear down observer relationship in multithreaded C++?
[ "", "c++", "multithreading", "design-patterns", "oop", "" ]
I'm working on a social network web application, and I got a situation where I need to resend reminder emails to users who haven't activated their emails. The problem is when I investigated the DB I found that many emails are duplicated (there was no validation on the email uniqueness apparently. So what I need to do know is to retrieve these fields from the DB the username, email activation code, email, so that I can resend the activation emails, and for the case of the duplicated emails I need to return only one of them (i.e if I have user john with email john@hotmail.com and user john1 with email john@hotmail.com too, I want to retrieve only one of these johns no matter john1 or two) so I thought of tailing the SQL query by (Group By Email). The thing is that I can't select other fields that are not in the group by clause. the solution that I have here is one that I don't like; I created a List and every time when I need to send an email to a user I iterate all over the entire list to make sure that this email is not existing, if it's not there, I send to it and then add the email to the list. Something like the following: ``` if(!EmailIsInList(email)){ SendActivationEmail(email); AddEmailToList(email) } else { DoNotSend); } ``` Actually I got the problem solved this way, still, I don't like my solution. Any ideas?
If we assume that the same email address could be both activated against usera and not activated against userb then the following query would return you one userid for each email address that has never been activated ``` SELECT MAX(userid), email FROM users AS u1 WHERE activated = 'False' AND NOT EXISTS ( SELECT 1 FROM users AS u2 WHERE u2.email = u1.email AND u2.activated = 'True' ) GROUP BY email ``` You really do want to make sure the email field is indexed, and if it was indexed with a unique composite key of (email, userid) then this would be an indexed scan and should be pretty quick.
Income testing data: ``` DECLARE @User TABLE (UserId int, UserName varchar(100), Email varchar(40), IsActivated bit) INSERT INTO @User SELECT 1, 'John', 'john@hotmail.com', 0 UNION SELECT 2, 'Ann', 'ann@hotmail.com', 0 UNION SELECT 3, 'John2', 'john@hotmail.com', 1 UNION SELECT 4, 'Bill', 'bill@hotmail.com', 0 UNION SELECT 5, 'Bill', 'john@hotmail.com', 0 DECLARE @Email TABLE (EmailId int, UserId int, Date datetime, Message varchar(1000)) INSERT INTO @Email SELECT 1, 1, GETDATE(), '' UNION SELECT 2, 2, GETDATE(), '' UNION SELECT 3, 3, GETDATE(), '' UNION SELECT 4, 4, GETDATE(), '' UNION SELECT 5, 5, GETDATE(), '' SELECT * FROM @User SELECT * FROM @Email ``` You see, we have john@hotmail.com already activated once, so we don't need him in result set. Now, implementation with RANK OVER: ``` SELECT M.UserID, M.UserName, M.Email, M.IsActivated, M.EmailId, M.Date, M.Message FROM ( SELECT RANK() OVER (PARTITION BY U.Email ORDER BY U.IsActivated Desc, U.UserID ASC) AS N, U.UserID, U.UserName, U.Email, U.IsActivated, E.EmailId, E.Date, E.Message FROM @User U INNER JOIN @Email E ON U.UserID = E.UserID )M WHERE M.N = 1 AND M.IsActivated = 0 ```
A work around Group By Clause Limitation
[ "", "asp.net", "sql", "sql-server", "aggregate", "" ]
We're debugging a GWT app. Runs ok in Firefox, in IE6.0 starts working ok but after some time, it gets on its knees and starts to crawl. After doing some tests we're suspecting some memory problems ( too much memory used, memory leaks, etc ) Besides using taskmanager and processxp to watch the memory usage grow :)....¿do you recommend any other memory monitoring tool? Like jprobe for jscript? :)
I have answered the similar question earlier regarding JS memory leak detection in IE[Here](https://stackoverflow.com/questions/1469841/how-to-check-if-memory-leak-occurs-when-removing-an-element-out-of-dom/1470092#1470092) these are the tools am using * [sIEve](http://home.orange.nl/jsrosman/) * [IEJSLeaksDetector2.0.1.1](http://blogs.msdn.com/gpde/pages/javascript-memory-leak-detector-v2.aspx)
<http://sourceforge.net/projects/ieleak/>
What do you use to monitor jscript memory usage in Internet Explorer
[ "", "javascript", "internet-explorer", "gwt", "memory-management", "" ]
If you look at the source of Google pages with JavaScript, you'll find that the JavaScript is clearly not readable -- or maintainable. For example, all variables and functions are one-letter named (at least, the first 26 are...); there are no extraneous white-spaces or linebreaks; there are no comments; and so on. The benefits of this compiler are clear: pages load faster, JavaScript execution is faster, and as a bonus, competitors will have a hard time understanding your obfuscated code. Clearly, Google is using some sort of a JavaScript-to-JavaScript compacting compiler. I am wondering if what they're using is an in-house tool? If not, what *are* they using? Are there any publicly available (ideally, free/open-source) tools of that sort?
[YUI Compressor](http://developer.yahoo.com/yui/compressor/) is a Java app that will compact and obfuscate your Javascript code. It is a Java app that you run from the command line (and would probably be part of a build process). Another one is [PHP Minify](http://code.google.com/p/minify/), which does a similar thing.
Another one is ShrinkSafe that is part of Dojo but may be used stand-alone (either in a build script, command line or at the website): <http://shrinksafe.dojotoolkit.org/>
Is there a free/open-source JavaScript-to-JavaScript compacting compiler (like Google's)?
[ "", "javascript", "optimization", "compiler-construction", "obfuscation", "" ]
I've got an XML document with a default namespace. I'm using a XPathNavigator to select a set of nodes using Xpath as follows: ``` XmlElement myXML = ...; XPathNavigator navigator = myXML.CreateNavigator(); XPathNodeIterator result = navigator.Select("/outerelement/innerelement"); ``` I am not getting any results back: I'm assuming this is because I am not specifying the namespace. How can I include the namespace in my select?
First - you don't need a navigator; SelectNodes / SelectSingleNode should suffice. You may, however, need a namespace-manager - for example: ``` XmlElement el = ...; //TODO XmlNamespaceManager nsmgr = new XmlNamespaceManager( el.OwnerDocument.NameTable); nsmgr.AddNamespace("x", el.OwnerDocument.DocumentElement.NamespaceURI); var nodes = el.SelectNodes(@"/x:outerelement/x:innerelement", nsmgr); ```
You might want to try an XPath Visualizer tool to help you through. [XPathVisualizer](http://xpathvisualizer.codeplex.com) is free, easy to use. [![alt text](https://i.stack.imgur.com/2iZl8.png)](https://i.stack.imgur.com/2iZl8.png) IMPORTANT: If you are using Windows 7/8 and don't see File, Edit and Help Menu items, please press ALT key.
Using Xpath With Default Namespace in C#
[ "", "c#", "xml", "xpath", "namespaces", "xpathnavigator", "" ]
I see various frameworks being launched that promise Rich Ui and better User experience as they call it. Silverlight, Flash, Yahoo's new framework etc etc. Does this mean that over a period of time these frameworks will replace the existing HTML, JAVASCRIPT CSS based web applications? Wouldn't it be same as opening an application inside a browser window?
HTML won't be replaced as a standard any time soon. It's too wide spread a technology, and the amount of re-education required among people working with webapps and websites to switch technology completely would be massive and very costly. HTML will however, like any other technology, evolve. Look at HTML today compared to 10 years ago, it's the same language in the basics but the way we use it, and add-on technologies have changed it quite a lot. Even a high tech, premium site made 10 years ago will look feeble with todays standards. So, while HTML will like stay "the same" (i.e. follow the natural evolution of a standard), the technology behind the site (php, .NET, JAVA etc.) will probably be more likely to change.
I'm from the future, and no, it's still here.
Will HTML be replaced by any new technology?
[ "", "javascript", "html", "css", "flash", "silverlight", "" ]
I have a class that I wish to test via SimpleXMLRPCServer in python. The way I have my unit test set up is that I create a new thread, and start SimpleXMLRPCServer in that. Then I run all the test, and finally shut down. This is my ServerThread: ``` class ServerThread(Thread): running = True def run(self): self.server = #Creates and starts SimpleXMLRPCServer while (self.running): self.server.handle_request() def stop(self): self.running = False self.server.server_close() ``` The problem is, that calling ServerThread.stop(), followed by Thread.stop() and Thread.join() will not cause the thread to stop properly if it's already waiting for a request in handle\_request. And since there doesn't seem to be any interrupt or timeout mechanisms here that I can use, I am at a loss for how I can cleanly shut down the server thread.
Two suggestions. Suggestion One is to use a separate process instead of a separate thread. * Create a stand-alone XMLRPC server program. * Start it with `subprocess.Popen()`. * Kill it when the test is done. In standard OS's (not Windows) the kill works nicely. In Windows, however, there's no trivial kill function, but there are recipes for this. The other suggestion is to have a function in your XMLRPC server which causes server self-destruction. You define a function that calls `sys.exit()` or `os.abort()` or raises a similar exception that will stop the process.
I had the same problem and after hours of research i solved it by switching from using my own **handle\_request()** loop to **serve\_forever()** to start the server. **serve\_forever()** starts an internal loop like yours. This loop can be stopped by calling **shutdown()**. After stopping the loop it is possible to stop the server with **server\_close()**. I don't know why this works and the **handle\_request()** loop don't, but it does ;P Here is my code: ``` from threading import Thread from xmlrpc.server import SimpleXMLRPCServer from pyWebService.server.service.WebServiceRequestHandler import WebServiceRquestHandler class WebServiceServer(Thread): def __init__(self, ip, port): super(WebServiceServer, self).__init__() self.running = True self.server = SimpleXMLRPCServer((ip, port),requestHandler=WebServiceRquestHandler) self.server.register_introspection_functions() def register_function(self, function): self.server.register_function(function) def run(self): self.server.serve_forever() def stop_server(self): self.server.shutdown() self.server.server_close() print("starting server") webService = WebServiceServer("localhost", 8010) webService.start() print("stopping server") webService.stop_server() webService.join() print("server stopped") ```
Running SimpleXMLRPCServer in separate thread and shutting down
[ "", "python", "multithreading", "simplexmlrpcserver", "" ]
``` // Reads NetworkStream into a byte buffer. NetworkStream ns; System.Net.Sockets.TcpClient client = new TcpClient(); byte[] receiveBytes = new byte[client.ReceiveBufferSize]; ns.Read(receiveBytes, 0, (int)client.ReceiveBufferSize); String returndata = Encoding.UTF8.GetString(receiveBytes); ``` I am successfully reading from a client and storing the result into a string called returndata. However, when I try to concatenate returndata with anything, no concatenation occurs. Ex: String.Concat(returndata, "test") returns returndata, as does returndata + "test". Does anyone know why this is happening? Edit: Steve W is correct; i found out later that returndata.Length was always returning 8192.
I believe the problem is related to not keeping track of the total number of bytes read. Your byte buffer, set to ReceiveBufferSize, is more than likely larger than the actual number of bytes read. By taking into account the actual bytes read, and then passing it to the Encoding.UTF8.GetString() method, you should get a valid string that can be concatenated. Here's an example: ``` NetworkStream ns; System.Net.Sockets.TcpClient client = new TcpClient(); byte[] receiveBytes = new byte[client.ReceiveBufferSize]; int bytesRead = ns.Read(receiveBytes, 0, receiveBytes.Length); String returndata = Encoding.UTF8.GetString(receiveBytes,0,bytesRead); returndata = returndata.Trim(new char[] {'\0'}); ``` Note also the other suggestion about reading a null terminator and including it in the bytes read also could be an issue. I've included a Trim of the string to make sure null terminators are removed.
Are you assigning it to a string or back to itself? ``` returndata = string.Concat(returndata, "test"); returndata += "test"; ```
C# string won't concatenate
[ "", "c#", "string", "concatenation", "" ]
I have a class called Cal and it's .cpp and .h counterpart Headerfile has ``` class Cal { private: int wa[2][2]; public: void do_cal(); }; ``` .cpp file has ``` #include "Cal.h" void Cal::do_cal() { print(wa) // where print just itterates and prints the elements in wa } ``` My question is how do I initialize the array `wa` ? I just can't seem to get it to work. I tried with : ``` int wa[2][2] = { {5,2}, {7,9} }; ``` in the header file but I get errors saying I cant do so as it's against iso..something. Tried also to initialize the array `wa` in the constructor but that didnt work either.. What am I missing ? Thanks
If it can be static, you can initialize it in your .cpp file. Add the static keyword in the class declaration: ``` class Cal { private: static int wa[2][2]; public: void do_cal(); }; ``` and at file scope in the .cpp file add: ``` #include "Cal.h" int Cal::wa[2][2] = { {5,2}, {7,9} }; void Cal::do_cal() { print(wa) // where print just itterates and prints the elements in wa } ``` If you never change it, this would work well (along with making it const). You only get one that's shared with each instance of your class though.
You cannot initialize array elements in a class declaration. I recently tried to find a way to do just that. From what I learned, you have to do it in your initialize function, one element at a time. ``` Cal::Cal{ wa[0][0] = 5; wa[0][1] = 2; wa[1][0] = 7; wa[1][1] = 9; } ``` It's possible (and probable) that there's a much better way to do this, but from my research last week, this is how to do it with a multi dimensional array. I'm interested if anyone has a better method.
C/C++ private array initialization in the header file
[ "", "c++", "arrays", "header", "initialization", "" ]
I'm currently evaluating maven to improve our build process. The building and creating of normal jar files works so far, although I'm not entirely happy with the Maven IDE. I'm now at that point, where all libs I need for our project are built, and I'm moving on to the Eclipse RCP projects. And now I'm not sure how to go on. There are some plugins I need to build first, before moving on to the actual RCP part. Therefore I have actually 3 problems. I want to build those plugins, the only real solution for that seems to be the maven-bundle-plugin: <http://felix.apache.org/site/apache-felix-maven-bundle-plugin-bnd.html> But, For nice IDE integration I also need the appropriate files (plugin.xml, build.properties, etc ...) which should be generated automatically. For building the RCP parts, it seems so far the only solution is only the pde-maven-plugin <http://mojo.codehaus.org/pde-maven-plugin/> which, as far as I can tell, uses ant-pde. This is stupid, isn't it? The only other thing I could found was tycho (<http://www.sonatype.com/people/2008/11/building-eclipse-plugins-with-maven-tycho/>) , but this is till in a very early stage. and again, a nice Eclipse integration is necessary. I really, really, really don't want to specify dependencies twice. So How do you build your Eclipse RCP projects with maven? **Update** For now, it seems that there is no such solution available. Tycho looks very promising, but I wasted 2 days and didn't get it to run (the current version at this point). Maybe it will be ready in half a year or so.
No there is no such tool. Tycho is also the only approach I know of.
I use [m2eclipse](http://m2eclipse.codehaus.org/) and it fits well my needs. You specify your dependencies in the pom.xml and they are automatically taken into account in Eclipse's build path. Caveat: I cannot tell anything about RCP (never built anything for that platform). Best regards, Cyril
Is it currently possible to build Eclipse Plugins by Maven AND have nice IDE Integration?
[ "", "java", "eclipse", "maven-2", "build", "eclipse-rcp", "" ]
Here's what I'm trying to do: ``` public void init(ServletConfig config) { // ... URL url = new URL("http://myhost:port/path/to/otherservlet"); // ... do stuff with contents of url } ``` This works fine, but myhost and port are hardcoded and I want to avoid that. I want ``` URL url = new URL("/path/to/otherservlet"); ``` but that's not valid. I've also tried ``` config.getServletContext().getResource("/path/to/otherservlet"); ``` but that only works on static files. How can I use the result of getting one servlet to initialize another? I don't want to use RequestDispatcher's forward() or include() methods -- the results of otherservlet are intended for use in the init() method, not to be sent in the response.
I wouldn't be surprised to find that it can't be done. I think toby's answer (split the code out into a common class) is the best approach, but if that's really not possible, try encoding the host and port to be used for local requests as context parameters in the server's `web.xml` file: ``` <context-param> <param-name>localhost</param-name> <param-value>localhost</param-value> </context-param> <context-param> <param-name>localport</param-name> <param-value>8080</param-value> </context-param> ``` and get the values with `context.getInitParameter("localhost")` etc. You could also try to determine the values dynamically, but you might have to wait for a request to come in so you can use something like `HttpUtils.getRequestURL(req)` - I don't know any other way to do it.
If possible, I think the better approach is to refactor the code for the other servlet into a class somewhere that can be called directly for the output that you need.
How do you use the output of one servlet inside another servlet's init() method?
[ "", "java", "servlets", "jakarta-ee", "" ]
is it possible to read data from a **generic webcam** in C++ as you would from a stream object? Is there a common API or standard that works with all webcams? I'm talking about C++ in \*nix environment. Thanks in advance.
For linux, [V4L](http://linuxtv.org/v4lwiki/index.php/Main_Page). AFAIR, BSD uses the same codebase. I do not know about the others...
In Linux, webcams are supported using [Video4Linux](http://linuxtv.org/wiki/index.php/Main_Page). Take a look at the [userspace API](http://v4l2spec.bytesex.org/spec/book1.htm) and an [Video4Linux introduction](http://lwn.net/Articles/203924/).
How to read input from a webcam in C++?
[ "", "c++", "video", "stream", "webcam", "" ]
I create a servercontrol for ASP.Net. For being short and precise I just list the things I do: (1) Call EnsureChildControls in OnInit (2) Create a dynamic table in CreateChildControls: ``` Table aTable = new Table(); aTable.ID = this.ID + "$" + T; TableRow aRow = new TableRow(); aRow.ID = aTable.ID + "$R" + <COUNTER>.ToString(); TableCell aCell = new TableCell(); createLinkButton(row, col, caption, aCell, aRow.ID); this.Controls.Add(aTable); ``` (3) Have a function like: ``` void aLinkButton_Command(object sender, CommandEventArgs e) { // Some stuff return; } ``` (4) Have a function like: ``` void createLinkButton(int row, int col, string caption, TableCell aCell, string baseID) { LinkButton lb = new LinkButton(); lb.ID = baseID + "$" + row.ToString() + col.ToString(); lb.Command += new CommandEventHandler(aLinkButton_Command); lb.Text = caption; lb.CommandName = "<command>"; aCell.Controls.Add(lb); return; } ``` But: The event is never called. The href is redered for postback, but the wired event never gets triggered. No ideas anymore :( Any ideas
You will need to recreate the dynamically created LinkButton on Postback for it's associated EventHander to fire. Rather than explain the whole thing, I would highly recommend that you read Scott Mitchell's [classic article](https://web.archive.org/web/20211031102347/https://aspnet.4guysfromrolla.com/articles/092904-1.aspx) on the subject.
Look at the page (.aspx file) where you are using the server control. Make sure that you are adding the control to the page's control tree on both initial requests *and postback requests*. All events are handled on postback requests and if the control that generated an event is not present during the postback, the event handler will never fire.
ASP.NET EventHandling
[ "", "c#", "asp.net", "" ]
I'd like to initialize a map - object "id" with identities from 0 to n-1, i.e. ``` id[0] = 0 id[1] = 1 . . id[n-1] = n-1 ``` Is there a simple way - a one-liner, a method inside the map-object, simply something really simple - that does that?
You could use the ``` template <class InputIterator> map(InputIterator f, InputIterator l, const key_compare& comp) ``` form of the constructor, but you'd need to build an InputIterator that worked as a generator function over the range you want. That'd be a whole lot more typing than just using a for loop.
What is wrong with ``` for(unsigned int i = 0; i < n; ++i) id[i] = i; ```
What's the simplest way to create an STL - identity map?
[ "", "c++", "stl", "dictionary", "" ]
Is there a nice simple method of delaying a function call whilst letting the thread continue executing? e.g. ``` public void foo() { // Do stuff! // Delayed call to bar() after x number of ms // Do more Stuff } public void bar() { // Only execute once foo has finished } ``` I'm aware that this can be achieved by using a timer and event handlers, but I was wondering if there is a standard c# way to achieve this? If anyone is curious, the reason that this is required is that foo() and bar() are in different (singleton) classes which my need to call each other in exceptional circumstances. The problem being that this is done at initialisation so foo needs to call bar which needs an instance of the foo class which is being created... hence the delayed call to bar() to ensure that foo is fully instanciated.. Reading this back almost smacks of bad design ! ***EDIT*** I'll take the points about bad design under advisement! I've long thought that I might be able to improve the system, however, this nasty situation *only* occurs when an exception is thrown, at all other times the two singletons co-exist very nicely. I think that I'm not going to messaround with nasty async-patters, rather I'm going to refactor the initialisation of one of the classes.
Thanks to modern C# 5/6 :) ``` public void foo() { Task.Delay(1000).ContinueWith(t=> bar()); } public void bar() { // do stuff } ```
I've been looking for something like this myself - I came up with the following, although it does use a timer, it uses it only once for the initial delay, and doesn't require any `Sleep` calls ... ``` public void foo() { System.Threading.Timer timer = null; timer = new System.Threading.Timer((obj) => { bar(); timer.Dispose(); }, null, 1000, System.Threading.Timeout.Infinite); } public void bar() { // do stuff } ``` (thanks to [Fred Deschenes](https://stackoverflow.com/users/912440/fred-deschenes) for the idea of disposing the timer within the callback)
Delayed function calls
[ "", "c#", "function", "delay", "" ]
Is there any particular reason I should declare a class or a method final in day-to-day programming (web or otherwise)? Please provide a real-world example where it should be used. BTW, I'm asking because I'm trying to [pick an 'obscure' keyword and master it](http://www.secretgeek.net/6min_program.asp "8 ways to be a better programmer in 6 minutes.").
It prevents other programmers from doing stuff with your classes that you don't intend for them to do. So rather than making a comment saying "don't use this class to do XXX", you can design it in such a way that they won't be tempted to override it and abuse it in that manner. **Edit**: Since an example is requested, I'll describe a case where you might find this keyword handy... say you have a class which defines how two objects may communicate with each other, say, a listener and notifier. The listener class must obviously allow inheritance, but you might want to make the notifier class final so that it must be used in a "has-a" relationship. This way, you can make some assumptions from your listener objects about the nature of the messages they are receiving. Otherwise, it would be possible to inherit from that class, do all sorts of crazy stuff like extend the messages and so on. If you don't want other programmers to do that, then you could make the class final. Also, this might make a lot more sense in a widely-used public API, as it also allows other programmers to readily understand which classes are ok to subclass. Another example -- say you have a buffer-based stream processor, and inside of your read()/write() method, you maintain some data about the current state of your object (ie, the current byte or whatever). There is no way to guarantee that anyone subclassing this class would call the super's methods during processing -- and since such a class likely only contains a few methods, it's better to just make the whole thing final instead of each method. This again forces people using the class to "has-a", not "is-a", and thus, can control how you expect the code will be executed. I would agree with you in that making an entire *class* final is probably something which you'd need to do once in a blue moon, but it's nice that PHP has this capability should you choose to exercise it.
["Enforce Composition over Inheritance"](http://renaud.waldura.com/doc/java/final-keyword.shtml#classes) puts it rather succinctly. You guarantee a certain behavior of your class that nothing else can interfere with, which, as the next section explains, can have security benefits as well.
When should I use "final"?
[ "", "php", "final", "" ]
What's an efficient way of splitting a String into chunks of 1024 bytes in java? If there is more than one chunk then the header(fixed size string) needs to be repeated in all subsequent chunks.
Strings and bytes are two completely different things, so wanting to split a String into bytes is as meaningless as wanting to split a painting into verses. What is it that you actually want to do? To convert between strings and bytes, you need to specify an encoding that can encode all the characters in the String. Depending on the encoding and the characters, some of them may span more than one byte. You can either split the String into chunks of 1024 characters and encode those as bytes, but then each chunk may be more than 1024 bytes. Or you can encode the original string into bytes and then split them into chunks of 1024, but then you have to make sure to append them as bytes before decoding the whole into a String again, or you may get garbled characters at the split points when a character spans more than 1 byte. If you're worried about memory usage when the String can be very long, you should use streams (java.io package) to to the en/decoding and splitting, in order to avoid keeping the data in memory several times as copies. Ideally, you should avoid having the original String in one piece at all and instead use streams to read it in small chunks from wherever you get it from.
You have two ways, the fast and the memory conservative way. But first, you need to know what characters are in the String. ASCII? Are there umlauts (characters between 128 and 255) or even Unicode (s.getChar() returns something > 256). Depending on that, you will need to use a different encoding. If you have binary data, try "iso-8859-1" because it will preserve the data in the String. If you have Unicode, try "utf-8". I'll assume binary data: ``` String encoding = "iso-8859-1"; ``` The fastest way: ``` ByteArrayInputStream in = new ByteArrayInputStream (string.getBytes(encoding)); ``` Note that the String is Unicode, so every character needs *two* bytes. You will have to specify the encoding (don't rely on the "platform default". This will only cause pain later). Now you can read it in 1024 chunks using ``` byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) { ... } ``` This needs about three times as much RAM as the original String. A more memory conservative way is to write a converter which takes a StringReader and an OutputStreamWriter (which wraps a ByteArrayOutputStream). Copy bytes from the reader to the writer until the underlying buffer contains one chunk of data: When it does, copy the data to the real output (prepending the header), copy the additional bytes (which the Unicode->byte conversion may have generated) to a temp buffer, call buffer.reset() and write the temp buffer to buffer. Code looks like this (untested): ``` StringReader r = new StringReader (string); ByteArrayOutputStream buffer = new ByteArrayOutputStream (1024*2); // Twice as large as necessary OutputStreamWriter w = new OutputStreamWriter (buffer, encoding); char[] cbuf = new char[100]; byte[] tempBuf; int len; while ((len = r.read(cbuf, 0, cbuf.length)) > 0) { w.write(cbuf, 0, len); w.flush(); if (buffer.size()) >= 1024) { tempBuf = buffer.toByteArray(); ... ready to process one chunk ... buffer.reset(); if (tempBuf.length > 1024) { buffer.write(tempBuf, 1024, tempBuf.length - 1024); } } } ... check if some data is left in buffer and process that, too ... ``` This only needs a couple of kilobytes of RAM. [EDIT] There has been a lengthy discussion about binary data in Strings in the comments. First of all, it's perfectly safe to put binary data into a String as long as you are careful when creating it and storing it somewhere. To create such a String, take a byte[] array and: ``` String safe = new String (array, "iso-8859-1"); ``` In Java, ISO-8859-1 (a.k.a ISO-Latin1) is a 1:1 mapping. This means the bytes in the array will not be interpreted in any way. Now you can use substring() and the like on the data or search it with index, run regexp's on it, etc. For example, find the position of a 0-byte: ``` int pos = safe.indexOf('\u0000'); ``` This is especially useful if you don't know the encoding of the data and want to have a look at it before some codec messes with it. To write the data somewhere, the reverse operation is: byte[] data = safe.getBytes("iso-8859-1"); **Never use the default methods `new String(array)` or `String.getBytes()`!** One day, your code is going to be executed on a different platform and it will break. Now the problem of characters > 255 in the String. If you use this method, you won't ever have any such character in your Strings. That said, if there were any for some reason, then getBytes() would throw an Exception because there is no way to express all Unicode characters in ISO-Latin1, so you're safe in the sense that the code will not fail silently. Some might argue that this is not safe enough and you should never mix bytes and String. In this day an age, we don't have that luxury. A lot of data has no explicit encoding information (files, for example, don't have an "encoding" attribute in the same way as they have access permissions or a name). XML is one of the few formats which has explicit encoding information and there are editors like Emacs or jEdit which use comments to specify this vital information. This means that, when processing streams of bytes, you must always know in which encoding they are. As of now, it's not possible to write code which will always work, no matter where the data comes from. Even with XML, you must read the header of the file as bytes to determine the encoding before you can decode the meat. The important point is to sit down and figure out which encoding was used to generate the data stream you have to process. If you do that, you're good, if you don't, you're doomed. The confusion originates from the fact that most people are not aware that the same byte can mean different things depending on the encoding or even that there is more than one encoding. Also, it would have helped if Sun hadn't introduced the notion of "platform default encoding." Important points for beginners: * There is more than one encoding (charset). * There are more characters than the English language uses. There are even several [sets of digits](http://msdn.microsoft.com/en-us/library/w1c0s6bb.aspx) (ASCII, full width, Arabic-Indic, Bengali). * You must know which encoding was used to generate the data which you are processing. * You must know which encoding you should use to write the data you are processing. * You must know the correct way to specify this encoding information so the next program can decode your output (XML header, HTML meta tag, special encoding comment, whatever). The days of ASCII are over.
Split Java String in chunks of 1024 bytes
[ "", "java", "string", "split", "byte", "" ]
So far I've discovered I can convert incoming BSTRs to ANSI in two (of many?) ways, and I'm curious to know whether one is "better" than the other with respect to speed / efficiency etc. The way I've been using for a while is use the `USES_CONVERSION` and `W2A` macros, e.g. ``` BSTR __stdcall F(BSTR p1, BSTR p2 ) { USES_CONVERSION; LPSTR sNum1 = W2A( p1 ); LPSTR sNum2 = W2A( p2 ); ``` Recently, however, I came across another technique: ``` BSTR __stdcall F(BSTR p1, BSTR p2 ) { long amt = wcstombs( NULL, p1, 1 ); sNum1 = (char *) malloc( amt ); wcstombs( sNum1, p1, amt ); *(sNum1 + amt) = '\0'; amt = wcstombs( NULL, p2, 1 ); sNum2 = (char *) malloc( amt ); wcstombs( sNum2, p2, amt ); *(sNum2 + amt) = '\0'; ``` Now I grant you, it's wordier, and has two calls to `wcstombs` but for all I know the `USES_CONVERSION` and `W2A` macros may be hiding all sorts of fun and games. Which is the more efficient / faster code? Or, is there another technique I could use that would do the job better?
Note in the approved answer by Nick, which whilst correct shares the same problem there is with the MSDN documentation that describes the macros. The problem is that some of the macros such as the one listed by @Nick - COLE2A, don't actually exist. However further down the MSDN page there is some text that clues you into this fact and leads you to be able to figure out the correct macro! The text is listed in the table under the following text: > There are several important differences between the older string conversion macros and the new string conversion classes: In the New ATL 7.0 Conversion Classes column. Which says: > OLE is always equivalent to W So the macro in @Nick's example is actually **CW2A**
From [MSDN](http://msdn.microsoft.com/en-us/library/87zae4a3(vs.71).aspx): > [...]The recommended way of converting to and from BSTR strings is to use the [CComBSTR](http://msdn.microsoft.com/en-us/library/zh7x9w3f(VS.71).aspx) class. To convert to a BSTR, pass the existing string to the constructor of CComBSTR. To convert from a BSTR, use COLE2[C]DestinationType[EX], such as COLE2T. From the CComBSTR page: > [...]The CComBSTR class provides a number of members (constructors, assignment operators, and comparison operators) that take either ANSI or Unicode strings as arguments. The ANSI versions of these functions are less efficient than their Unicode counterparts because temporary Unicode strings are often created internally. For efficiency, use the Unicode versions where possible.
Which is better code for converting BSTR parameters to ANSI in C/C++?
[ "", "c++", "c", "string", "cstring", "bstr", "" ]
I am working on a Drupal based site and notice there are a lot of seperate CSS and js files. Wading though some of the code I can also see quite a few cases where many queries are used too. What techniques have you tried to improve the performance of Drupal and what modules (if any) do you use to improve the performance of Drupal 'out of the box'?
Going to the admin/settings/performance page, turning on CSS and JS aggregation, and page caching with a minimum lifetime of 1 minute, will give you an immediate boost on a high traffic site. If you're writing your own code and doing any queries, consider writing your own discrete [caching for expensive functions](http://www.lullabot.com/articles/a_beginners_guide_to_caching_data). The linked article covers Drupal 5, not 6, but the only change in d6 is the elimiation of the serialization requirement and the function signature for the cache\_set() and cache\_get() functions. (Both noted in comments on the article) On large scale sites also consider dropping a memcached server onto the network: Using the [memcached](http://drupal.org/project/memcache) module, you can entirely bypass the drupal database for cached data. If you have huge amounts of content and search is a hot spot, you can also consider using lucene/solr as your search indexer instead of drupal's built-in search indexer. It's nice for a built-in indexer but it's not designed for heavy loads (hundreds or thousands of new pieces of content an hour, say, with heavy faceted searching). The [apache solr](http://drupal.org/project/apachesolr) module can tie in with that. If you're making heavy use of Views, be sure that you've checked the queries it generates for unindexed fields; sorting and filtering by CCK fields in particular can be slow, because CCK doesn't automatically add indexes beyond the primary keys. In D6, preview the View in the admin screen, copy the text of the query, and run it through EXPLAIN in mysql or whatever query analysis tools you have. Tools like YSlow and Firebug can also help you spot slow stuff like massive image files, JS hosted on remote servers, and so on.
Drupal 6, out-of-the-box, provides css and javascript aggregation --- most css and js files will be combined into a single file (and thus a single HTTP request), and are also whitespace-shortened (to reduce bandwidth consumption). You can enable this under /admin/settings/performance . Also on that screen are controls for Drupal's (very effective) cache, which helps reduce the number of database queries. Additionally, because Drupal (and all the modules you'll probably have installed) has a ton of PHP source, using a PHP opcode cache such as [APC](http://pecl.php.net/package/APC) helps significantly decrease the request time.
Scaling Drupal
[ "", "php", "mysql", "performance", "drupal", "" ]
I have a simple web form which has a couple list boxes and a search button. When the button is clicked, it returns a DataSet. If the dataset contains records, I set the asp:label which is initially set to false to true, but this is not happening. If the dataset has records and the visible property is set to true, the label still does not show up. I have also tried putting the label and a couple other controls in an html table and setting a runat="server" attribute on the table and changing the visibility on that, but it does not show either. Here is aspx code: ``` <table> <tr> <td> <asp:Label ID="lblSortBy" runat="server" Text="Sort By:" Visible="false"> </asp:Label> <asp:DropDownList ID="ddlSortBy" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlSortBy_SelectedIndexChanged"> <asp:ListItem Value="Gross">Gross</asp:ListItem> <asp:ListItem Value="Population">Population</asp:ListItem> </asp:DropDownList> </td> </tr> </table> ``` Here is simplified code behind when a button is clicked: ``` public void GetData() { DataView dv = GetReportData().DefaultView; if(dv.ToTable().Rows.Count > 0) { lblSortBy.Visible = true; } else { lblSortBy.Visible = false; } } ``` I have a couple Update Panels around some ListBoxes and a GridView, but not the Label and Dropdown. Would this cause an issue? I did a test, I set a label that was in an update panel to false if records were found and the label disappeared, so it is working if it is in an update panel.
If I'm not mistaken, your label should exist on an updatepanel, because as far as the static HTML page is concerned, the one and only time that your current label exists, it's set to be not visible. You would have to reload the whole page to make it visible again.
If the button is inside an UpdatePanel, then the Table, Label, etc. also have to be inside an UpdatePanel to get updated. Otherwise only the contents of the UpdatePanel get updated when clicking the button (this is what's called [partial page-rendering](http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.aspx)). So if the button is in an UpdatePanel, you have two possibilities to solve the problem: 1. put the table, Label, DropDownList etc. into the same UpdatePanel 2. or put them in another UpdatePanel and set the UpdateMode of that property to Always, so that it gets updated, even if a Postback was initiated by a control within another UpdatePanel. See [this page in MSDN](http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.aspx) for details.
Asp:Label is not shown when visible is set to true?
[ "", "c#", "asp.net", "" ]
How can I format my output in C++? In other words, what is the C++ equivalent to the use of `printf` like this: ``` printf("%05d", zipCode); ``` I know I could just use `printf` in C++, but I would prefer the output operator `<<`. Would you just use the following? ``` std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl; ```
This will do the trick, at least for non-negative numbers(a) such as the ZIP codes(b) mentioned in your question. ``` #include <iostream> #include <iomanip> using namespace std; cout << setw(5) << setfill('0') << zipCode << endl; // or use this if you don't like 'using namespace std;' std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl; ``` The most common IO manipulators that control padding are: * `std::setw(width)` sets the width of the field. * `std::setfill(fillchar)` sets the fill character. * `std::setiosflags(align)` sets the alignment, where align is ios::left or ios::right. And just on your preference for using `<<`, I'd strongly suggest you look into the `fmt` library (see <https://github.com/fmtlib/fmt>). This has been a great addition to our toolkit for formatting stuff and is much nicer than massively length stream pipelines, allowing you to do things like: ``` cout << fmt::format("{:05d}", zipCode); ``` And it's currently being targeted by LEWG toward C++20 as well, meaning it will hopefully be a base part of the language at that point (or almost certainly later if it doesn't quite sneak in). --- (a) If you *do* need to handle negative numbers, you can use `std::internal` as follows: ``` cout << internal << setw(5) << setfill('0') << zipCode << endl; ``` This places the fill character *between* the sign and the magnitude. --- (b) This ("all ZIP codes are non-negative") is an assumption on my part but a reasonably safe one, I'd warrant :-)
In C++20 you can do: ``` std::cout << std::format("{:05}", zipCode); ``` On older systems you can use [the {fmt} library](https://github.com/fmtlib/fmt), `std::format` is based on. **Disclaimer**: I'm the author of {fmt} and C++20 `std::format`.
Print leading zeros with C++ output operator?
[ "", "c++", "formatting", "numbers", "" ]
I am using Visual Studio 2008 with the .NET Framework (v3.5). I cannot seem to use System.Windows.Shapes, or anything System.Windows.\* besides Forms. Here is the link to the class description: [System.Windows.Shapes (MSDN Library)](http://msdn.microsoft.com/en-us/library/system.windows.shapes.aspx) Is there some special thing I need to do to use it? I checked in all of the framework folders, and the only dll/xml files I have for System.Windows is System.Windows.Forms. What do I need to do to get this to work?
This class is part of WPF, from [MSDN](http://msdn.microsoft.com/en-us/library/system.windows.shapes.shape.aspx): > Shape Class > > Assembly: PresentationFramework (in presentationframework.dll)
You need to add a reference to the PresentationFramework library. In VisualStudio, right click on your project in the "Solution Explorer". Select "Add Reference". The "PresentationFramework" library will be under the ".NET" tab. You may also need to add "PresentationCore" and "WindowsBase". You can see your project's current library references by going to the "Solution Explorer" and expanding the "References" item.
How do I include System.Windows.Shapes?
[ "", "c#", "windows", "visual-studio-2008", "shapes", "" ]
I'd like to have a ActiveRecord implementation in Java and before crafting my own, I'd like to know if there is an open source implementation of it. I am aware of other successful java OR maping tools like Hibernate, Castor, etc... and that is not what i want, i want a ActiveRecord like in RoR: * [RoR ActiveRecord](http://api.rubyonrails.org/classes/ActiveRecord/Base.html) * [.NET Castle ActiveRecord](http://www.castleproject.org/ActiveRecord/) Anyone?
After "Googling" for a answer I've found the project [arjava](http://arjava.sourceforge.net/). It implements the Active Record pattern kind of similar to the Ruby way.
I released this ActiveJDBC project: <http://javalite.io/activejdbc> This is an implementation of ActiveRecord in Java
Is there an implementation of the ActiveRecord pattern in Java like the one from Ruby?
[ "", "java", "open-source", "activerecord", "" ]
We are working on many products that are being published at our customers. But if you publish a C# application, all the dll's can be decompiled using reflector or some sort. I was wondering if there is an easy way to encrypt our dll's when publishing. This way we can publish our dll's without having to worry about our clients decompiling our code. ps: if it's possible to integrate this within visual studio that would be awesome. EDIT: Sorry about the double post, I didn't know it was called "obfuscation".
[Dotfuscator Community Edition](http://www.preemptive.com/dotfuscator-product-family.html) is installed along with Visual Studio Professional or higher versions. The Community edition, however, is a hobbyist or introductory version that only allows you to obfuscate the code to a degree by simple renaming of all members, is not integrated within VS and does not allow for robust features such as string encryption.
there are lots of obfuscators out there. i e.g. are quite confident with [smartassembly](http://www.smartassembly.com/)
Obfuscating source code when publishing (C#)
[ "", "c#", "obfuscation", "publish", "ddl", "" ]
I am curious as to what, if any, security concerns other develpers have in regards to the use of JQuery plugins. I have seen very little talk about security where JQuery is concerned. Is it really a non issue? Appreciate your thoughts!
Personally I am comfortable enough with Javascript to be able to swiff through the plugin code and understand possible misbehavior. What I look for is the most relevant security issue with javascript, cross-domain communication, which is usually done with the creation of `iframe`s, `script`/`img` tags etc.. Most of the times though, I trust the community, for example if it's up on <http://plugins.jquery.com/> it is usually a trusted source.
jQuery can't do anything that javascript itself can't do, so all the same security standards apply. Basically - never rely on it for security. Always validate all inputs on the server side. The best way to think of it is that from a security perspective, the client-side javascript is not actually a part of your application. Your application consists of all the possible http calls to your server. For good security, assume that hackers won't even be using a browser - they'll be making http requests directly to your server. Make sure that you aren't exposing any vulnerabilities in your http endpoints, and you should be ok. note: I made the assumption in this reply that you're talking about data and system security. User security (preventing your users from being phished, etc) is another kettle of fish, but I'm not sure it has to do with jQuery any more than javascript in general.
Do you have any security concerns when it comes to JQuery plugins?
[ "", "javascript", "jquery", "jquery-plugins", "" ]
*Edit : Accepted Chris Holmes response, but always ready to refactor if someone come up with a better way! Thanks!* Doing some winforms with MVP what is the best way to pass an entity to another view. Let say I have a `CustomerSearchView/Presenter`, on doubleClick I want to show the `CustomerEditView/Presenter`. I don't want my view to know about the model, so I can't create a ctor that take an `ICustomer` in parameters. my reflex would be, `CustomerSearchView` create a new `CustomerEditView`, which create it's own presenter. Then my `CustomerSearchView` would do something like : ``` var customerEditView = new CustomerEditView(); customerEditView.Presenter.Customer = this.Presenter.SelectedCustomer; ``` Other possible approach would be a `CustomerDTO` class, and make a `CustomerEditView` that accept one of those `CustomerDTO`, but I think it's a lot of work something simple. Sorry for basic question but all example I can find never reach that point, and it's a brownfield project, and the approach used so far is giving me headache...
I don't know exactly how you are showing your views, so it's a bit difficult to give you specific advice here. This is how I've done this sort of thing before: What we did was have the CustomerSearchViewPresenter fire an event like OpenCustomer(customerId). (That is assuming that your search view only has a few pieces of Customer data and the customerId would be one of them. If your search view has entire Customer objects listed then you could call OpenCustomer(customer). But I wouldn't build a search view and allow it to populate with entire objects... We keep our search views lightweight in terms of data.) Somewhere else in the application is an event handler that listens for the OpenCustomer() event and performs the task of creating a new CustomerEditView w/ Presenter (and I'm going to defer to my IoC container do this stuff for me, so I don't have to use the "new" keyword anywhere). Once the view is created we can pass along the id (or customer object) to the new CustomerEditView and then show it. This class that is responsible for listing the OpenCustomer() event and performs the creation of the CustomerEditView is typically some sort of Controller class in our app. To further simplify this situation, I've done this another way: I create both the CustomerSearchView (& presenter) and CustomerEditView (& presenter) when the application or module starts up. When the CustomerSearchView needs to open a Customer for editing, the CustomerEditView becomes the responder to the OpenCustomer event and loads the data into itself, and knows how to show itself in whatever container it is supposed to do. So there's multiple ways to do this.
How about: ``` //In CustomerSearchPresenter var presenter = new CustomerEditPresenter(); var customerEditView = new CustomerEditView(presenter); presenter.SetCustomer(customer); //In CustomerEditPresenter public void SetCustomer(customer) { View.Name = customer.Name; View.Id = customer.Id; ... } ``` In think your customer search view should just delegate to its presenter you need to have an action execute.
Model view presenter, how to pass entities between view?
[ "", "c#", "winforms", "mvp", "" ]
Over the years, I've dabbled in plain JavaScript a little, but have not yet used any JavaScript/AJAX libraries. For some new stuff I'm working on, I would like to use a js library to do client-side form validation, and want to know which would be best for that. By best, my criteria would be: quick and easy to learn, small footprint, compatible with all popular browsers. Edit: Thanks for the ASP suggestions, but they're not relevant to me. Sorry I didn't originally mention it, but the server is a Linux box running Apache and PHP. As I know I should, I plan to do server side validation of the input, but want the client side validation to improve the users' experience and to avoid as much as possible having the server reject invalid inputs. Edit 2: Sorry I didn't reply for months! Other priorities came up and diverted me from this. I ended up doing my own validation routines - in addition to the good points made in some of the answers, some of the items I'm validating are rarely used in other applications and I couldn't find a library with that sort of validation included.
I don't use libraries myself, but dived into some (like prototype, (yui-)ext, the seemingly omnipresent jquery, mootools) to learn from them and extract some of the functions or patterns they offer. The libraries (aka 'frameworks') contain a lot of functionallity I never need, so I wrote my own subset of functions. Form checking is pretty difficult to standardize (except perhaps for things like phone numbers or e-mail address fields), so I don't think a framework would help there either. My advice would be to check if one of the libraries offer the functionallity you look for, and/or use/rewrite/copy the functions you can use from them. For most open source libraries it is possible to download the uncompressed source. It needs to be said (by the way and perhaps well known allready) that client side form checking is regarded insufficient. You'll have to check the input server side too.
You could use [jQuery](http://jquery.com/) and it's [Validation plugin](http://docs.jquery.com/Plugins/Validation).
What JavaScript library to use for client-side form checking?
[ "", "javascript", "ajax", "validation", "client-side", "" ]
*I am developing a simple game in [PyGame](http://www.pygame.org/)... A rocket ship flying around and shooting stuff.* --- **Question:** Why does pygame stop emitting keyboard events when too may keys are pressed at once? **About the Key Handling:** The program has a number of variables like `KEYSTATE_FIRE, KEYSTATE_TURNLEFT`, etc... 1. When a `KEYDOWN` event is handled, it sets the corresponding `KEYSTATE_*` variable to True. 2. When a `KEYUP` event is handled, it sets the same variable to False. **The problem:** If `UP-ARROW` and `LEFT-ARROW` are being pressed at the same time, pygame DOES NOT emit a `KEYDOWN` event when `SPACE` is pressed. This behavior varies depending on the keys. When pressing letters, it seems that I can hold about 5 of them before pygame stops emitting `KEYDOWN` events for additional keys. **Verification:** In my main loop, I simply printed each event received to verify the above behavior. **The code:** For reference, here is the (crude) way of handling key events at this point: ``` while GAME_RUNNING: FRAME_NUMBER += 1 CLOCK.tick(FRAME_PER_SECOND) #---------------------------------------------------------------------- # Check for events for event in pygame.event.get(): print event if event.type == pygame.QUIT: raise SystemExit() elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_UP: KEYSTATE_FORWARD = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_UP: KEYSTATE_FORWARD = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_DOWN: KEYSTATE_BACKWARD = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_DOWN: KEYSTATE_BACKWARD = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_LEFT: KEYSTATE_TURNLEFT = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_LEFT: KEYSTATE_TURNLEFT = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_RIGHT: KEYSTATE_TURNRIGHT = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_RIGHT: KEYSTATE_TURNRIGHT = False elif event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_SPACE: KEYSTATE_FIRE = True elif event.type == pygame.KEYUP and event.dict['key'] == pygame.K_SPACE: KEYSTATE_FIRE = False # remainder of game loop here... ``` **For pressing this sequence:** * `a (down)` * `s (down)` * `d (down)` * `f (down)` * `g (down)` * `h (down)` * `j (down)` * `k (down)` * `a (up)` * `s (up)` * `d (up)` * `f (up)` * `g (up)` * `h (up)` * `j (up)` * `k (up)` **Here is the output:** * `<Event(2-KeyDown {'scancode': 30, 'key': 97, 'unicode': u'a', 'mod': 0})>` * `<Event(2-KeyDown {'scancode': 31, 'key': 115, 'unicode': u's', 'mod': 0})>` * `<Event(2-KeyDown {'scancode': 32, 'key': 100, 'unicode': u'd', 'mod': 0})>` * `<Event(2-KeyDown {'scancode': 33, 'key': 102, 'unicode': u'f', 'mod': 0})>` * `<Event(3-KeyUp {'scancode': 30, 'key': 97, 'mod': 0})>` * `<Event(3-KeyUp {'scancode': 31, 'key': 115, 'mod': 0})>` * `<Event(3-KeyUp {'scancode': 32, 'key': 100, 'mod': 0})>` * `<Event(3-KeyUp {'scancode': 33, 'key': 102, 'mod': 0})>` * `<Event(2-KeyDown {'scancode': 36, 'key': 106, 'unicode': u'j', 'mod': 0})>` * `<Event(2-KeyDown {'scancode': 37, 'key': 107, 'unicode': u'k', 'mod': 0})>` * `<Event(3-KeyUp {'scancode': 36, 'key': 106, 'mod': 0})>` * `<Event(3-KeyUp {'scancode': 37, 'key': 107, 'mod': 0})>` --- Is this a common issue? Is there a workaround? If not, what is the best way to handle multiple-key control issues when using pygame?
This sounds like a input problem, not a code problem - are you sure the problem isn't the keyboard itself? Most keyboards have limitations on the number of keys that can be pressed at the same time. Often times you can't press more than a few keys that are close together at a time. To test it out, just start pressing and holding letters on the keyboard and see when new letters stop appearing. My suggestion is to try mapping SPACE to a different key somewhere else and see what happens.
As others have eluded to already, certain (especially cheaper, lower-end) keyboards have a low quality [keyboard matrix](http://en.wikipedia.org/wiki/Keyboard_technology#Keyboard_switch_matrix). With these keyboards, certain key combinations will lead to the behavior you're experiencing. Another common side effect can be "ghost keys," where the an extra key press will appear in the input stream that was not actually pressed. The only solution (if the problem is related to the keyboard matrix) is to change your key mapping to use keys on different rows/columns of the matrix, or buy a keyboard with a better matrix.
PyGame not receiving events when 3+ keys are pressed at the same time
[ "", "python", "pygame", "keyboard-events", "" ]
Just starting out with Rhino Mocks and im having a very simple problem, how do I mock a class with a void which sets a property? ``` class SomeClass : ISomeClass { private bool _someArg; public bool SomeProp { get; set; } public SomeClass(bool someArg) { _someArg = someArg; } public void SomeMethod() { //do some file,wcf, db operation here with _someArg SomeProp = true/false; } } ``` Obviously this is a very contrived example, Thanks.
In your example you won't need RhinoMocks because you're apparently testing the functionality of the class under test. Simple unit testing will do instead: ``` [Test] public void SomeTest() { var sc = new SomeClass(); // Instantiate SomeClass as sc object sc.SomeMethod(); // Call SomeMethod in the sc object. Assert.That(sc.SomeProp, Is.True ); // Assert that the property is true... // or change to Is.False if that's what you're after... } ``` It's much more interesting to test mocks when you have a class that has dependencies on other classes. In your example you mention: > //do some file, wcf, db operation here with \_someArg I.e. you expect some other class to set `SomeClass`'s property, which makes more sense to mocktest. Example: ``` public class MyClass { ISomeClass _sc; public MyClass(ISomeClass sc) { _sc = sc; } public MyMethod() { sc.SomeProp = true; } } ``` The required test would go something like this: ``` [Test] public void MyMethod_ShouldSetSomeClassPropToTrue() { MockRepository mocks = new MockRepository(); ISomeClass someClass = mocks.StrictMock<ISomeClass>(); MyClass classUnderTest = new MyClass(someClass); someClass.SomeProp = true; LastCall.IgnoreArguments(); // Expect the property be set with true. mocks.ReplayAll(); classUndertest.MyMethod(); // Run the method under test. mocks.VerifyAll(); } ```
Depends on how much fidelity you'd like in your mock object. The easy way to do it is to not worry about it and write out some dumb expect statements. ``` [Test] public void SomeTest() { MockRepository mocks = new MockRepository(); ISomeClass mockSomeClass = mocks.StrictMock<ISomeClass>(); using(mocks.Record()) { using(mocks.Ordered()) { Expect.Call(MockSomeClass.SomeProp).Return(false); Expect.Call(delegate{MockSomeClass.SomeMethod();}); Expect.Call(MockSomeClass.SomeProp).Return(true); } } } ``` If you want something that acts more like the real object without a canned set of ordered responses you'll have to set up delegates with the do method on the expect. ``` delegate bool propDelegate(); delegate void methodDelegate(); private bool m_MockPropValue = false; [Test] public void SomeTest() { MockRepository mocks = new MockRepository(); ISomeClass mockSomeClass = mocks.StrictMock<ISomeClass>(); using(mocks.Record()) { SetupResult.For(MockSomeClass.SomeProp).Do(new propDelegate(delegate { return this.m_MockPropValue; })); Expect.Call(delegate{MockSomeClass.SomeMethod();}).Do(new methodDelegate(delegate { this.m_MockPropValue = true; })); } } ```
Rhino Mocks, void and properties
[ "", "c#", "tdd", "mocking", "rhino-mocks", "" ]
Inherited an app with a page that has a link that calls the javascript function addValueClick(), when I do this a dialog box pops up, I type in some text, and then the text gets put in the select box. Every time a new option is added to the select it gets about 5 pixels narrower. I can't figure out why this is happening, but it only happens in IE7 Here is the javascript: ``` function addValueClick() { var newValue = prompt("Please enter a new value.",""); if (newValue != null && newValue != "") { var lst = document.getElementById("lstValues"); var opt = document.createElement("option"); opt.setAttribute("selected", "true"); opt.appendChild(document.createTextNode(newValue)); lst.appendChild(opt); updateBtns(); copyValues(); } } function copyValues() { var frm = document.forms[0]; var lst = frm.elements["lstValues"]; var hid = frm.elements["hidValues"]; var xml = "<root>"; for (var i = 0; i < lst.options.length; i++) { xml += "<value seq_num=\"" + (i + 1) + "\">" + lst.options[i].text + "</value>"; } xml += "</root>"; hid.value = xml; } function updateBtns() { var lst = document.getElementById("lstValues"); var iSelected = lst.selectedIndex; var lnkEdit = document.getElementById("lnkEditValue"); var lnkDelete = document.getElementById("lnkDeleteValue"); var lnkUp = document.getElementById("lnkValueUp"); var lnkDown = document.getElementById("lnkValueDown"); if (iSelected == -1) { lnkEdit.style.visibility = "hidden"; lnkDelete.style.visibility = "hidden"; lnkUp.style.visibility = "hidden"; lnkDown.style.visibility = "hidden"; } else { lnkEdit.style.visibility = "visible"; lnkDelete.style.visibility = "visible"; if (iSelected == 0) lnkUp.style.visibility = "hidden"; else lnkUp.style.visibility = "visible"; if (iSelected == lst.options.length - 1) lnkDown.style.visibility = "hidden"; else lnkDown.style.visibility = "visible"; } } ``` EDIT: The HTML, it's actually ASP.NET. All the listValueChanged() method does is call updateButtons() above. ``` <tr> <TD class=body vAlign=top noWrap align=right><b>Values:</TD> <TD class=body vAlign=top noWrap align=left><asp:ListBox id="lstValues" runat="server" onchange="lstValuesChange();" Rows="9" onselectedindexchanged="lstValues_SelectedIndexChanged"></asp:ListBox></TD> <TD class=body vAlign=top noWrap align=left> <TABLE id="Table2" cellSpacing="2" cellPadding="2" border="0"> <TR> <TD noWrap> <asp:HyperLink id="lnkAddValue" runat="server" NavigateUrl="javascript:addValueClick();">Add</asp:HyperLink></TD> </TR> <TR> <TD noWrap> <asp:HyperLink id="lnkEditValue" runat="server" NavigateUrl="javascript:editValueClick();">Edit</asp:HyperLink></TD> </TR> <TR> <TD noWrap> <asp:HyperLink id="lnkDeleteValue" runat="server" NavigateUrl="javascript:deleteValueClick();">Delete</asp:HyperLink></TD> </TR> <TR> <TD noWrap>&nbsp;</TD> </TR> <TR> <TD noWrap> <asp:HyperLink id="lnkValueUp" runat="server" NavigateUrl="javascript:valueUpClick();">Up</asp:HyperLink></TD> </TR> <TR> <TD noWrap> <asp:HyperLink id="lnkValueDown" runat="server" NavigateUrl="javascript:valueDownClick();">Down</asp:HyperLink></TD> </TR> </TABLE> </TD> </TR> ```
The issue was where the Option was being added to the Select I changed it to the following and it works perfectly: ``` function addValueClick() { var newValue = prompt("Please enter a new value.",""); if (newValue != null && newValue != "") { var lst = document.getElementById("lstValues"); var opt = document.createElement("option"); opt.text = newValue; opt.value = newValue; try { lst.add(opt, null); // real browsers } catch (ex) { lst.add(opt); // IE } updateBtns(); copyValues(); } } ```
It may have more to do with the html than the script. What is the select contained in? Based on the JS, I don't think there are any problems here.
When I add an option to a select the select gets narrower
[ "", "asp.net", "javascript", "html", "" ]
``` <Document> <A> <B> <C></C> </B> </A> <E> <F> <C></C> </F> <G> <C></C> </G> </E> </Document> ``` If i load the above XML into an XmlDocument and do a SelectSingleNode on A using the XPath query //C ``` XmlNode oNode = oDocument.SelectSingleNode("E"); XmlNodeList oNodeList = oNode.SelectNodes("//C"); ``` why does it return nodes from Under B when what I would expect to happen would that it only return nodes from under E Make sense? Edit : How would i make it only return from that node onwards?
Simply: a leading // means "at any level" in the same *document* as the selected node. From the [spec](http://www.w3.org/TR/xpath): * //para selects all the para descendants of the document root and thus selects all para elements in the same document as the context node * .//para selects the para element descendants of the context node
Specifying `.//C` will achieve what you want, otherwise, the XPath starts from the document root rather than the current node. The confusion is in the definition of `//` from the [XPath standard](http://www.w3.org/TR/xpath#path-abbrev) as follows: > // is short for > /descendant-or-self::node()/. For > example, //para is short for > /descendant-or-self::node()/child::para > and so will select any para element in > the document (even a para element that > is a document element will be selected > by //para since the document element > node is a child of the root node); > div//para is short for > div/descendant-or-self::node()/child::para > and so will select all para > descendants of div children. Because `//` is short for `/descendant-or-self::node()/` it starts at the document level unless you specify a node at the start.
XPath SelectNodes in .NET
[ "", "c#", "xml", "xpath", "" ]
using firebug, where are the js errors shown when the page renders? (if you have any good js debugging links w/firebug send them my way please!)
Javascript errors will be listed in the Console of Firebug. You can also set Firebug to break on all errors, which is helpful for detecting why the error was thrown.
As you are asking for some links: 1. [Firebug Tutorial - Logging, Profiling and CommandLine (Part I)](http://michaelsync.net/2007/09/09/firebug-tutorial-logging-profiling-and-commandline-part-i) 2. [Firebug Tutorial - Logging, Profiling and CommandLine (Part II)](http://michaelsync.net/2007/09/10/firebug-tutorial-logging-profiling-and-commandline-part-ii) 3. [Firebug Tutorial - Using Commandline API in Firebug](http://michaelsync.net/2007/09/15/firebug-tutorial-commandline-api)
Using firebug, where are the js errors shown?
[ "", "javascript", "debugging", "firebug", "" ]
I'm working on a rails app. I have a dropdown with countries. Selecting a country would fill the city dropdown with the cities in that country. I know how to do this server-side, but I'd like to do it client-side if possible. I've used the RJS helpers, but I've no experience with jQuery (not *exactly* even sure what it is) or the other selector javascript libraries. Clarification: I'd like to do this **entirely** client-side. That is, send all the values in the initial page request. I'm not looking to call the server ajaxically, hit the database, then return those results. I'd like them loaded up with the page.
I used a combination of jQuery and the [jQuery calculations plugin](http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm) to get this working.
Maybe this can help (a simple google search did it): <http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/>
Fill select dropdown based on selected item
[ "", "javascript", "ruby-on-rails", "html-select", "" ]
I'm looking to monitor the end user experience of our website and link that with timing information already logged on the server side. My assumption is that this will require javascript to to capture time stamps at the start of request (window.onbeforeunload) and at the end of loading (window.onload). Basically this - "[Measuring Web application response time: Meet the client](http://www.javaworld.com/javaworld/jw-11-2008/jw-11-measuring-client-response.html)" 1. Is there a better approach? 2. What kind of performance penalty should I be expecting (order of magnitude)? 3. How good are the results?
EDIT (2013): try [Boomerang](https://github.com/SOASTA/boomerang) instead, like @yasei-no-umi suggests. It's actively maintained. -- old answer -- We use [Jiffy](http://code.google.com/p/jiffy-web/). It's very simple to use and modify - we wrote our own server-side code (instead of Jiffy's Apache + perl) and used Jiffy's JS. Regarding a performance penalty - there isn't one on the client side. The JS itself is trivially fast, and the reporting back to the server can be done with an XHR after page load, which affects nothing in the user experience. On the server side you'll get twice as many requests. If that's a bottleneck, you could set up a different server just for the timing responses.
There is also [Boomerang](http://yahoo.github.com/boomerang/doc/) from Yahoo. Has some advanced features not existing in Jiffy and Episodes. Also support [Navigation Timing](https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/NavigationTiming/Overview.html) API in browsers that support it (Chrome 6, IE 9)
What is the best way to measure Client Side page load times?
[ "", "javascript", "performance", "monitoring", "client-side", "timing", "" ]
I want to write a RegEx to pull out all the variable values and their names from the variable declaration statement. Say i have int i,k = 10,l=0 i want to write a regex something like int\s^,?|(^,?)\* but this will also accept k = 10 i.e. (without int preceding it) Basically idea is If string starts with int then get the variable list seperated by , i know to extract csv values, but here my string has some initial value as well. How can i resolve it?
Start thinking about the structure of a definition, say, ``` (a line can start with some spaces) followed by, (Type) followed by (at least one space) (variable_1) (optionally (comma // next var | '='number // initialization ) ...` ``` then try to convert each group: ``` ^ \s* \w+ \s+ \w+ ? (',' | '=' \d+ ) ... line some type at least var optionally more or init some start spaces (some chars) one space (some chars) vars val digits ``` Left as homework to remove spaces and fix up the final regex.
Here is some useful information which you can use <http://compsci.ca/v3/viewtopic.php?t=6712>
Regex for variable declaration and initialization in c#
[ "", "c#", "regex", "variables", "declaration", "" ]
I'm working on C++ framework and would like to apply automatic memory management to a number of core classes. So far, I have the standard approach which is ``` class Foo { public: static shared_ptr<Foo> init() { return shared_ptr<Foo>(new Foo); } ~Foo() { } protected: Foo() { } }; // Example of use shared_ptr<Foo> f = Foo::init(); ``` However, the above breaks when I subclass Foo, since even tho `init()` is inherited, it still returns `shared_ptr<Foo>` which contains a pointer to instance of `Foo`. Can anyone think of an elegant solution to this? Should I perhaps just stick with (semi-)manually wrapping instances of class with `shared_ptr`? This would also give ability to expose parameterized constructors without declaring new named constructors... Ie. ``` template <typename T> shared_ptr<T> make_shared(T* ptr) { return shared_ptr<T>(ptr) } // Example shared_ptr<T> f1 = make_shared(new Foo()), f2 = make_shared(new Foo(1,2)); ```
I don't understand what this achieves, you don't appear to be getting any extra memory management using this init function than by simply declaring a shared\_ptr. ``` int main( void ) { shared_ptr<foo> a = foo::init(); shared_ptr<foo> b( new foo ); } ``` What's the difference. shared\_ptr provides the memory management, not anything in init.
I would try something like this: ``` template<class T> class creator { public: static shared_ptr<T> init() { return(shared_ptr<T>(new T)); } }; class A : public creator<A> { }; class B : public A, public creator<B> { public: using make_shared<B>::init; }; // example use shared_ptr<A> a = A::init(); shared_ptr<B> b = B::init(); ``` But this isn't necessarily saving you a thing compared to standalone template you proposed. Edit: I missed previous answer, this seems to be the same idea.
Named constructor and inheritance
[ "", "c++", "inheritance", "constructor", "factory", "named", "" ]
``` List<PageInfo> subPages = new List<PageInfo>(); // ... // some code to populate subPages here... // ... List<Guid> subPageGuids = new List<Guid> {from x in subPages select x.Id}; //doesn't work ``` PageInfo has an Id field which is of type Guid. So x.Id is a System.Guid. 2nd line of code above does not work...I get errors: > The best overloaded Add method > 'System.Collections.Generic.List.Add(System.Guid)' > for the collection initializer has some invalid arguments And > Argument '1': cannot convert from 'System.Collections.Generic.IEnumerable' > to 'System.Guid' I've only been coding in C# for about a week, but I've done a similar pattern before and never had this problem.
I think you want: ``` List<Guid> subPageGuids = new List<Guid>(from x in subPages select x.Id); ``` (note the curly braces changed to regular braces) That will call the constructor of List that takes an IEnumerable (which is what the linq query returns) as a parameter. Right now you're trying to use the syntax for an [object initializer](http://msdn.microsoft.com/en-us/library/bb384062.aspx).
It looks like the `Add()` is called and not `AddRange()`. You could use this syntax instead: ``` List<Guid> subPageGuids = (from x in subPages select x.id).ToList(); ``` or ``` List<Guid> subPageGuids = new List<Guid>(); subPageGuids.AddRange(from x in subPages select x.id); ```
"The best overloaded Add method 'System.Collections.Generic.List.Add(System.Guid)' for the collection initializer has some invalid arguments"
[ "", "c#", ".net", "linq", "" ]
I am trying to take several RSS feeds, and put the content of them into a MySQL Database using PHP. After I store this content, I will display on my own page, and also combine the content into one single RSS Feed. (Probably after filtering) I haven't dealt with RSS Feeds before, so I am wondering the best Framework/Method of doing this is. I have read about DOM based parsing, but have heard that it takes a lot of memory, any suggestions?
[Magpie](http://magpierss.sourceforge.net/) is a reasonable RSS parser for PHP. Easy to use: ``` require('rss_fetch.inc'); $rss = fetch_rss($url); ``` An item like this for example: ``` <item rdf:about="http://protest.net/NorthEast/calendrome.cgi?span=event&ID=210257"> <title>Weekly Peace Vigil</title> <link>http://protest.net/NorthEast/calendrome.cgi?span=event&ID=210257</link> <description>Wear a white ribbon</description> <dc:subject>Peace</dc:subject> <ev:startdate>2002-06-01T11:00:00</ev:startdate> <ev:location>Northampton, MA</ev:location> <ev:enddate>2002-06-01T12:00:00</ev:enddate> <ev:type>Protest</ev:type> </item> ``` Would be turned into an array like this: ``` array( title => 'Weekly Peace Vigil', link => 'http://protest.net/NorthEast/calendrome.cgi?span=event&ID=210257', description => 'Wear a white ribbon', dc => array ( subject => 'Peace' ), ev => array ( startdate => '2002-06-01T11:00:00', enddate => '2002-06-01T12:00:00', type => 'Protest', location => 'Northampton, MA' ) ); ``` Then you can just pick out the bits you want to save in the DB and away you go!
The Best PHP parser out there is [SimplePie](http://simplepie.org/), IMHO. I've been using it for years. It's great at grabbing and parsing the following: RSS 0.90, RSS 0.91 (Netscape), RSS 0.91 (Userland), RSS 0.92, RSS 1.0, RSS 2.0, Atom 0.3, Atom 1.0; including the following namespaces: Dublin Core 1.0, Dublin Core 1.1, GeoRSS, iTunes RSS 1.0 (mostly complete), Media RSS 1.1.1, RSS 1.0 Content Module, W3C WGS84 Basic Geo, XML 1.0, XHTML 1.0 SimplePie 1.2 even has database caching, so it should have everything you need to do what you want. And if you need to parse raw XML files, try using XMLize -Trystian
What is the best way to get RSS Feeds into a MySQL Database
[ "", "php", "mysql", "rss", "" ]
My product is targeted to a Portuguese audience where the comma is the decimal symbol. I usually use CString::Format to input numbers into strings, and it takes into account the computer's regional settings. While in general this is a good approach, I'm having problems in formatting SQL queries, for instance: ``` CString szInsert; szInsert.Format("INSERT INTO Vertices (X, Y) VALUES (%f, %f)", pt.X, pt.Y); ``` When values are passed I get this string which is an incorrect query: ``` INSERT INTO Vertices (X, Y) VALUES (3,56, 4,67) ``` How do I enforce the dot as the decimal symbol in these strings, without changing the regional settings and without having to make specialized strings for each float value? Note: this is intended as a general question, not a SQL one.
Here's what I did. ``` CString FormatQuery(LPCTSTR pszFormat, ...) { CString szLocale = setlocale(LC_NUMERIC, NULL); setlocale(LC_NUMERIC, "English"); va_list args; va_start(args, pszFormat); CString szFormatted; int nSize = (_vscprintf(pszFormat, args) + 1) * sizeof(char); _vsnprintf_s(szFormatted.GetBuffer(nSize), nSize, nSize, pszFormat, args); szFormatted.ReleaseBuffer(); va_end(args); setlocale(LC_NUMERIC, szLocale); return szFormatted; } ``` You should use it like `sprintf`. You must `#include <locale.h>` in order for it to work. I'm a bit stubborn so I didn't use prepared statements/parametrized queries. If you have a similar problem, I suggest you do that. Meanwhile, if your problem is not SQL-related, my answer should help. **Edit:** Here's a thread safe version: ``` CString FormatQuery(LPCTSTR pszFormat, ...) { _locale_t locale = _create_locale(LC_NUMERIC, "English"); va_list args; va_start(args, pszFormat); CString szFormatted; int nSize = (_vscprintf_l(pszFormat, locale, args) + 1) * sizeof(char); _vsnprintf_s_l(szFormatted.GetBuffer(nSize), nSize, nSize, pszFormat, locale, args); szFormatted.ReleaseBuffer(); va_end(args); return szFormatted; } ```
Bad idea, you really should be using prepared statements. It's not really trivial to do SQL injection with just numbers, but CString::Format is just not the correct way to do parameter binding. (MFC and SQL has been a while - turns out this is bloody well hidden. I'm starting to see how we ended up with SQL injection bugs, thanks Microsoft. With raw ODBC you create a statement (once) with SQLPrepare. Pass ? for the 2 parameters you want to fill in. Subsequently, for each INSERT call `SQLBindParameter(stmt, 1, &X); SQLBindParameter(stmt, 2, &Y) /*extra parameters omitted, see http://msdn.microsoft.com/en-us/library/ms710963(VS.85).aspx */`. Finally, call SQLExecute to preform the operation. )
How to convert a float to a string regardless of regional settings?
[ "", "c++", "mfc", "formatting", "locale", "" ]
Is there a direct LINQ syntax for finding the members of set A that are absent from set B? In SQL I would write this ``` SELECT A.* FROM A LEFT JOIN B ON A.ID = B.ID WHERE B.ID IS NULL ```
See the MSDN documentation on the [Except operator](https://msdn.microsoft.com/en-us/library/vstudio/bb300779%28v=vs.100%29.aspx).
I believe your LINQ would be something like the following. ``` var items = A.Except( from itemA in A from itemB in B where itemA.ID == itemB.ID select itemA); ``` ### Update As indicated by [Maslow](https://stackoverflow.com/users/57883/maslow) in the comments, this may well not be the most performant query. As with any code, it is important to carry out some level of profiling to remove bottlenecks and inefficient algorithms. In this case, [chaowman's answer](https://stackoverflow.com/questions/507478/linq-exclusion/507605#507605) provides a better performing result. The reasons can be seen with a little examination of the queries. In the example I provided, there are at least two loops over the A collection - 1 to combine the A and B list, and the other to perform the `Except` operation - whereas in [chaowman's answer](https://stackoverflow.com/questions/507478/linq-exclusion/507605#507605) (reproduced below), the A collection is only iterated once. ``` // chaowman's solution only iterates A once and partially iterates B var results = from itemA in A where !B.Any(itemB => itemB.Id == itemA.Id) select itemA; ``` Also, in my answer, the B collection is iterated in its entirety for every item in A, whereas in [chaowman's answer](https://stackoverflow.com/questions/507478/linq-exclusion/507605#507605), it is only iterated upto the point at which a match is found. As you can see, even before looking at the SQL generated, you can spot potential performance issues just from the query itself. Thanks again to [Maslow](https://stackoverflow.com/users/57883/maslow) for highlighting this.
LINQ exclusion
[ "", "sql", "linq", "" ]
Can someone please explain the difference between the `protected` and `protected internal` modifiers in C#? It looks like their behavior is identical.
The "protected internal" access modifier is a *union* of both the "protected" and "internal" modifiers. From [MSDN, Access Modifiers (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/ms173121.aspx): **[protected](http://msdn.microsoft.com/en-us/library/bcd5672a.aspx)**: > The type or member can be accessed only by code in the same class or > struct, or in a class that is derived from that class. **[internal](http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx)**: > The type or member can be accessed by any code in the same assembly, > but not from another assembly. **protected internal**: > The type or member can be accessed by any code in the assembly in > which it is declared, **OR** from within a derived class in another > assembly. Access from another assembly must take place within a class > declaration that derives from the class in which the protected > internal element is declared, and it must take place through an > instance of the derived class type. **Note that**: `protected internal` means "`protected` OR `internal`" (any class in the same assembly, or any derived class - even if it is in a different assembly). ...and for completeness: **[private](https://msdn.microsoft.com/en-us/library/st6sy9xe.aspx)**: > The type or member can be accessed only by code in the same class or > struct. **[public](https://msdn.microsoft.com/en-us/library/yzh058ae.aspx)**: > The type or member can be accessed by any other code in the same > assembly or another assembly that references it. **[private protected](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private-protected)**: > Access is limited to the containing class or types derived from the > containing class within the current assembly. > (*Available since C# 7.2*)
This table shows the difference. `protected internal` is the same as `protected`, except it also allows access from other classes in the same assembly. [![Comparison of C# modifiers](https://i.stack.imgur.com/IXnye.png)](https://i.stack.imgur.com/IXnye.png)
What is the difference between 'protected' and 'protected internal'?
[ "", "c#", ".net", "access-modifiers", "" ]
I'm looking to develop a Silverlight application which will take a stream of data (not an audio stream as such) from a web server. The data stream would then be manipulated to give audio of a certain format (G.711 a-Law for example) which would then be converted into PCM so that additional effects can be applied (such as boosting the volume). I'm OK up to this point. I've got my data, converted the G.711 into PCM but my problem is being able to output this PCM audio to the sound card. I basing a solution on some C# code intended for a .Net application but in Silverlight there is a problem with trying to take a copy of a delegate (function pointer) which will be the topic of a separate question once I've produced a simple code sample. So, the question is... How can I output the PCM audio that I have held in a data structure (currently an array) in my Silverlight to the user? (Please don't say write the byte values to a text box) If it were a MP3 or WMA file I would play it using a MediaElement but I don't want to have to make it into a file as this would put a crimp on applying dynamic effects to the audio. I've seen a few posts from people saying low level audio support is poor/non-existant in Silverlight so I'm open to any suggestions/ideas people may have.
The simple answer is that there is no support for PCM playback from Silverlight in version 2. So unless you want to write a fully managed PCM to MP3 converter you are stuck. Even then I'm not sure you could get the MediaElement to play from isolated storage. Is there any chance you could use a web service to perform the conversion? See also this question: [Where's the sound API in Silverlight? Or, how do I write a music app to run in the browser?](https://stackoverflow.com/questions/347288/wheres-the-sound-api-in-silverlight-or-how-do-i-write-a-music-app-to-run-in-t) **Update:** Silverlight 3 supports your custom audio sources. However, it won't let you intercept samples to perform effects on WMA or MP3, presumably for DRM reasons, so you would still potentially need to write your own decoder.
Short answer is use a MediaElement + a MediaStreamSource Check out these: <http://blogs.msdn.com/gillesk/archive/2009/03/23/playing-back-wave-files-in-silverlight.aspx> <http://code.msdn.microsoft.com/wavmss/Release/ProjectReleases.aspx?ReleaseId=2417> Basically, write a decoder in managed code to convert G.711 a-Law to PCM, then do whatever modifications you want to the raw values, then pass those into a MediaStreamSource.
Audio output from Silverlight
[ "", "c#", "silverlight", "audio", "pcm", "" ]
Basically I need to get around max execution time. I need to scrape pages for info at varying intervals, which means calling the bot at those intervals, to load a link form the database and scrap the page the link points to. The problem is, loading the bot. If I load it with javascript (like an Ajax call) the browser will throw up an error saying that the page is taking too long to respond yadda yadda yadda, plus I will have to keep the page open. If I do it from within PHP I could probably extend the execution time to however long is needed but then if it does throw an error I don't have the access to kill the process, and nothing is displayed in the browser until the PHP execute is completed right? I was wondering if anyone had any tricks to get around this? The scraper executing by itself at various intervals without me needing to watch it the whole time. Cheers :)
> "nothing is displayed in the browser until the PHP execute is completed" You can use [`flush()`](http://uk.php.net/flush) to work around this: > `flush()` > > (PHP 4, PHP 5) > > Flushes the output buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This effectively tries to push all the output so far to the user's browser.
Use [`set_time_limit()`](https://www.php.net/manual/en/function.set-time-limit.php) as such: ``` set_time_limit(0); // Do Time Consuming Operations Here ```
How to execute a PHP spider/scraper but without it timing out
[ "", "php", "web-crawler", "" ]
**BACKGROUND:\*\*I am running \*\*MS2005**. I have a MASTER table (ID, MDESC) and a DETAIL table (MID, DID, DDESC) with data as follows ``` 1 MASTER_1 2 MASTER_2 1 L1 DETAIL_M1_L1 1 L2 DETAIL_M1_L2 1 L3 DETAIL_M1_L3 2 L1 DETAIL_M2_L1 2 L2 DETAIL_M2_L2 ``` If I join the tables with ``` SELECT M.*, D.DID FROM MASTER M INNER JOIN DETAIL D on M.ID = D.MID ``` I get a list like the following: ``` 1 MASTER_1 L1 1 MASTER_1 L2 1 MASTER_1 L3 2 MASTER_2 L1 2 MASTER_2 L2 ``` **QUESTION:** Is there any way to use a MS SQL select statement to get the detail records into a comma separated list like this: ``` 1 MASTER_1 "L1, L2, L3" 2 MASTER_2 "L1, L2" ```
Thanks to the concept in the link from Bill Karwin, it's the **CROSS APPLY** that makes it work ``` SELECT ID, DES, LEFT(DIDS, LEN(DIDS)-1) AS DIDS FROM MASTER M1 INNER JOIN DETAIL D on M1.ID = D.MID CROSS APPLY ( SELECT DID + ', ' FROM MASTER M2 INNER JOIN DETAIL D on M2.ID = D.MID WHERE M1.ID = M2.ID FOR XML PATH('') ) pre_trimmed (DIDS) GROUP BY ID, DES, DIDS ``` **RESULTS:** ``` ID DES DIDS --- ---------- --------------- 1 MASTER_1 L1, L2, L3 2 MASTER_2 L1, L2 ```
You need a function:- ``` CREATE FUNCTION [dbo].[FN_DETAIL_LIST] ( @masterid int ) RETURNS varchar(8000) AS BEGIN DECLARE @dids varchar(8000) SELECT @dids = COALESCE(@dids + ', ', '') + DID FROM DETAIL WHERE MID = @masterid RETURN @dids END ``` Usage:- ``` SELECT MASTERID, [dbo].[FN_DETAIL_LIST](MASTERID) [DIDS] FROM MASTER ```
Using MS SQL Server 2005, how can I consolidate detail records into a single comma separated list
[ "", "sql", "sql-server", "group-concat", "" ]
We code in C# using VS2008 SP1. We have a server that runs Team System Server 2008 which we use for source control, tasks etc. The **server** is also our build machine for **Team Build**. This has been working just fine for a long time. Untill now. We get these **error messages** when trying to build one of our projects that has a **reference** to one **external assembly** (this happens both via Team Build, and when logging on physically and doing a regular build via Visual Studio): > C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets > : warning MSB3246: *Resolved file has a > bad image, no metadata, or is > otherwise inaccessible. Could not load > file or assembly* 'C:\Program > Files\Syncfusion\Essential > Studio\7.1.0.21\Assemblies\3.5\Syncfusion.XlsIO.Base.dll' > or one of its dependencies. *The module > was expected to contain an assembly > manifest.* > > C:\Program > Files\MSBuild\Microsoft\VisualStudio\v9.0\ReportingServices\Microsoft.ReportingServices.targets(24,2): > error MSB4062: The > "Microsoft.Reporting.RdlCompile" task > could not be loaded from the assembly > Microsoft.ReportViewer.Common, > Version=9.0.0.0, Culture=neutral, > PublicKeyToken=b03f5f7f11d50a3a. Could > not load file or assembly > 'Microsoft.ReportViewer.Common, > Version=9.0.0.0, Culture=neutral, > PublicKeyToken=b03f5f7f11d50a3a' or > one of its dependencies. The module > was expected to contain an assembly > manifest. Confirm that the > declaration is correct, and that the > assembly and all its dependencies are > available. > > The referenced component > 'Syncfusion.XlsIO.Base' could not be > found. These errors are for one project with one problematic assembly reference. When I try to build the entire solution there are of course many more errors because of this one. And there are two other projects that has the same problem with other assembly references. I have a list of the referenced assemblies that VS can't seem to resolve: * Microsoft.ReportViewer.Common * Microsoft.ReportViewer.WinForms * Syncfusion.Compression.Base * Syncfusion.Core * Syncfusion.XlsIO.Base The Syncfusion assemblies are from a 3rd-party component package. The other two are related to the Microsoft ReportViewer component. The references has been added via the Add Reference window, in the .NET tab, so I don't think there is anything suspicious about that. In the properties window for the assembly reference, there is no value in Culture, Description, Path, Runtime Version or Strong Name. Version says 0.0.0.0 and Resolved is False. I guess it is pretty obvious that VS cant resolve the reference. My question is why??? I've scratched my head a lot over this one. This only occurs on the server, the solution builds just fine on both my machine, and my coworkers machine. The assembly reference properties are fine on our machines. I have tried **uninstalling** the **3rd-party component** (on the server of course), and then reinstalling it again. Didn't help. I tried to **repair** the **VS2008 installation**. Didn't help. Tried to retrieve an **earlier version** from **source control** (that I know has buildt on the server before), and I got the same error messages. I have checked **file permissions**, and everything appears to be in order. I am running out of ideas... How do I solve this? **Update 16.02.2009:** I have tried to **compare ildasm output** of the dll on my pc and on the server (see the comment I wrote about that), and there is one small difference in a line that to me appears to be a comment. I must admit that I don't understand why there is a difference at all, so maybe someone could explain that to me? I also tried running a **virus scan** on the server. Didn't help. Tried to **remove** the **reference** and then **readd** it by browsing to the dll on disk. Didn't work. **Update 17.03.2009:** I've found the solution! The culprit was the **TruPrevent module of Panda Antivirus**. After disabling the module, everything works! =) I discovered this with the help of [fuslogvw.exe](http://msdn.microsoft.com/en-us/library/e74a18c4%28VS.80%29.aspx) and the log it generated. Googled the result, and stumbled upon [this blog entry.](http://msmvps.com/blogs/carlosq/archive/2007/03/23/the-strange-case-of-error-80131018-loading-a-visual-studio-add-in.aspx). Hope this can help somebody else to.
Almost certainly the problem is environmental - not source related. Some ideas ... (i) Try disabling your anti-virus/anti-malware tools - I've seen cases where these tools (particularly Trend Micro Antivirus, for some reason) can keep a DLL file locked after (during?) scanning, interfering with compilers. (ii) Check your PATH environment variable. Even in these modern days, the PATH variable is used to resolve some things - if this is messed up (too long, maximum length is 2048 characters IIRC) then things can be odd. (iii) You've checked File permissions - have you checked permissions in the registry? For example, SyncFusion installs its license key in both the User and Machine hives - if the build server can't read one or the other, could cause issues. Good luck!
It could also be that the referenced assemblies are in the GAC on the dev machine, but not on the build machine. Get it out of the GAC, into your source repository, and reference it by path.
Assembly references won't resolve properly on our build server
[ "", "c#", "tfsbuild", "assembly-resolution", "" ]
I am looking for a way to identify primitives types in a template class definition. I mean, having this class : ``` template<class T> class A{ void doWork(){ if(T isPrimitiveType()) doSomething(); else doSomethingElse(); } private: T *t; }; ``` Is there is any way to "implement" isPrimitiveType().
**UPDATE**: Since C++11, use the [`is_fundamental`](http://en.cppreference.com/w/cpp/types/is_fundamental) template from the standard library: ``` #include <type_traits> template<class T> void test() { if (std::is_fundamental<T>::value) { // ... } else { // ... } } ``` --- ``` // Generic: Not primitive template<class T> bool isPrimitiveType() { return false; } // Now, you have to create specializations for **all** primitive types template<> bool isPrimitiveType<int>() { return true; } // TODO: bool, double, char, .... // Usage: template<class T> void test() { if (isPrimitiveType<T>()) { std::cout << "Primitive" << std::endl; } else { std::cout << "Not primitive" << std::endl; } } ``` In order to save the function call overhead, use structs: ``` template<class T> struct IsPrimitiveType { enum { VALUE = 0 }; }; template<> struct IsPrimitiveType<int> { enum { VALUE = 1 }; }; // ... template<class T> void test() { if (IsPrimitiveType<T>::VALUE) { // ... } else { // ... } } ``` As others have pointed out, you can save your time implementing that by yourself and use is\_fundamental from the Boost Type Traits Library, which seems to do exactly the same.
[Boost TypeTraits](http://www.boost.org/doc/libs/1_38_0/libs/type_traits/doc/html/index.html) has plenty of stuff.
Identifying primitive types in templates
[ "", "c++", "templates", "" ]
I have written a C++ class that I need to share an instance of between at least two windows processes. What are the various ways to do this? Initially I looked into [#pragma data\_seg](http://msdn.microsoft.com/en-us/library/h90dkhs0(VS.80).aspx) only to be disappointed when I realised that it will not work on classes or with anything that allocates on the heap. The instance of the class must be accessible via a dll because existing, complete applications already use this dll.
You can potentially use [memory-mapped files](http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx) to share data between processes. If you need to call functions on your object, you'd have to use COM or something similar, or you'd have to implement your own RPC protocol.
Look into [Boost::interprocess](http://www.boost.org/doc/libs/1_38_0/doc/html/interprocess.html). It takes a bit of getting used to, but it works very well. I've made relatively complex data structures in shared memory that worked fine between processes. edit: it works with memory-mapped files too. The point is you can use data in a structured way; you don't have to treat the memory blocks (in files or shared memory) as just raw data that you have to carefully read/write to leave in a valid state. Boost::interprocess takes care of that part and you can use STL containers like trees, lists, etc.
Methods of sharing class instances between processes
[ "", "c++", "dll", "process", "share", "" ]
I've been given the task of connecting my code (fortran) with py (2.5), and generate a number of excel reports if possible. The first part went fine - and is done with, but now I'm working on the second. What are my choices for making excel (2007 if possible) sheets from python ? In general, I would need to put some array values in them in a table (formatting doesn't matter), and draw a number of charts from those tables. Is there a way to do this automatically ? Some library ? Anyone done something like this in the past ?
You're simplest approach is to use Python's [csv](http://www.python.org/doc/2.5.2/lib/module-csv.html) library to create a simple CSV file. Excel imports these effortlessly. Then you do Excel stuff to make charts out of the pages created from CSV sheets. There are some recipes for controlling Excel from within Python. See <http://code.activestate.com/recipes/528870/> for an example. The example has references to other projects. Also, you can use [pyExcelerator](http://sourceforge.net/projects/pyexcelerator) or [xlwt](http://pypi.python.org/pypi/xlwt) to create a more complete Excel workbook.
I believe you have two options: 1. Control Excel from Python (using pywin32, see [this question](https://stackoverflow.com/questions/441758/driving-excel-from-python-in-windows/445961)). Requires Windows and Excel. 2. Use the [xlwt](http://pypi.python.org/pypi/xlwt) pure Python library. I have not tried xlwt, I do not know if it handles charts.
python excel making reports
[ "", "python", "excel", "" ]
How do you get the rendered height of an element? Let's say you have a `<div>` element with some content inside. This content inside is going to stretch the height of the `<div>`. How do you get the "rendered" height when you haven't explicitly set the height. Obviously, I tried: ``` var h = document.getElementById('someDiv').style.height; ``` Is there a trick for doing this? I am using jQuery if that helps.
It should just be ``` $('#someDiv').height(); ``` with jQuery. This retrieves the height of the first item in the wrapped set as a number. Trying to use ``` .style.height ``` only works if you have set the property in the first place. Not very useful!
Try one of: ``` var h = document.getElementById('someDiv').clientHeight; var h = document.getElementById('someDiv').offsetHeight; var h = document.getElementById('someDiv').scrollHeight; ``` `clientHeight` includes the height and vertical padding. `offsetHeight` includes the height, vertical padding, and vertical borders. `scrollHeight` includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.
jQuery get the rendered height of an element?
[ "", "javascript", "jquery", "css", "height", "" ]
I'm playing with a PHP weblog application using a shared hosting service, as a part of my PHP learning process. The service provider has a typical LAMP environment with remote ssh access. Vim has been my best friend in exploring the PHP code. However, I found it sometimes hard to trace stuff in the code in case of error. For example, sometimes I visit a page and I got a blank response with no error messages whatsoever. How should I go about debugging this? Any tools that will be helpful? My experience has been mainly in C/C++, Perl and some CGI programming. So PHP is a very refreshing experience with me :-) In case it matters, the application I'm playing with is [Lyceum](http://lyceum.ibiblio.org/), and I don't have much choice on the LAMP environment itself. EDIT: Free software tools preferred :-)
I assume your hosting provider configured their PHP installation with [display\_errors](http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors) turned off, which is a good thing. That's why you're seeing blank pages. So the most practical solution at the moment would be to have an .htaccess file which turns it on: ``` php_flag display_errors on ``` You'd also need [error\_reporting](http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) to an appropriate value: ``` php_flag error_reporting "E_ALL | E_STRICT" ``` Anyway, remember to turn this off before letting users access your web site. For advance debugging I'd recommend [Xdebug](http://xdebug.org/) installed on the server with [Eclipse PDT](http://www.eclipse.org/pdt/) or [NetBeans IDE with PHP support](http://www.netbeans.org/downloads/index.html) as your editor. They both are good clients for debugging, but I really doubt any provider would install Xdebug on their live servers. So you're pretty much left with logging functions if you don't have a development environment.
Getting access to your own local development environment (via XAMPP, for Example) would let you install XDebug. PhpEd would let you debug it, but also Eclipse's PDT Environment. Error Tracing and logging via editing php's ini config file is a good way as well, specially if you can manage it to log information. Also, consider adding trace statements and using FirePHP, for example.
PHP debugging with remote shell access
[ "", "php", "debugging", "methodology", "remote-debugging", "" ]
I am trying to join a number of binary files that were split during download. The requirement stemmed from the project <http://asproxy.sourceforge.net/>. In this project author allows you to download files by providing a url. The problem comes through where my server does not have enough memory to keep a file that is larger than 20 meg in memory.So to solve this problem i modified the code to not download files larger than 10 meg's , if the file is larger it would then allow the user to download the first 10 megs. The user must then continue the download and hopefully get the second 10 megs. Now i have got all this working , except when the user needs to join the files they downloaded i end up with corrupt files , as far as i can tell something is either being added or removed via the download. I am currently join the files together by reading all the files then writing them to one file.This should work since i am reading and writing in bytes. The code i used to join the files is listed here <http://www.geekpedia.com/tutorial201_Splitting-and-joining-files-using-C.html> I do not have the exact code with me atm , as soon as i am home i will post the exact code if anyone is willing to help out. Please let me know if i am missing out anything or if there is a better way to do this , i.e what could i use as an alternative to a memory stream. The source code for the original project which i made changes to can be found here <http://asproxy.sourceforge.net/download.html> , it should be noted i am using version 5.0. The file i modified is called WebDataCore.cs and i modified line 606 to only too till 10 megs of data had been loaded the continue execution. Let me know if there is anything i missed. Thanks
In the end i have found that by using a FTP request i was able to get arround the memory issue and the file is saved correctly. Thanks for all the help
You shouldn't split for memory reasons... the reason to split is usually to avoid having to re-download everything in case of failure. If memory is an issue, you are doing it wrong... you shouldn't be buffering in memory, for example. The easiest way to download a file is simply: ``` using(WebClient client = new WebClient()) { client.DownloadFile(remoteUrl, localPath); } ``` --- Re your split/join code - again, the problem is that you are buffering everything in memory; `File.ReadAllBytes` is a bad thing unless you know you have small files. What you should have is something like: ``` byte[] buffer = new byte[8192]; // why not... int read; while((read = inStream.Read(buffer, 0, buffer.Length)) > 0) { outStream.Write(buffer, 0, read); } ``` This uses a moderate buffer to pump data between the two as a stream. A lot more efficient. The loop says: * try to read some data (at most, the buffer-size) * (this will read at least 1 byte, or we have reached the end of the stream) * if we read something, write this many bytes from the buffer to the output
Joining Binary files that have been split via download
[ "", "c#", "asp.net", "proxy", "" ]
I want to create a 100% object oriented framework in PHP with no procedural programming at all, and where everything is an object. Much like Java except it will be done in PHP. Any pointers at what features this thing should have, should it use any of the existing design patterns such as MVC? How creating objects for every table in the database would be possible, and how displaying of HTML templates etc would be done? Please don't link to an existing framework because I want to do this on my own mainly as a learning excercise. You **will** be downvoted for linking to an existing framework as your answer and saying 'this does what you want'. Some features I'd like to have are: * Very easy CRUD page generation * AJAX based pagination * Ajax based form validation if possible, or very easy form validation * Sortable tables * Ability to edit HTML templates using PHP
I've gone through many of problems on your list, so let me spec out how I handle it. I am also OOP addict and find object techniques extremely flexible and powerful yet elegant (if done correctly). **MVC** - yes, hands down, MVC is a standard for web applications. It is well documented and understandable model. Furthermore, it does on application level what OOP does on class level, that is, it keeps things separated. Nice addition to MVC is [Intercepting Filter](http://java.sun.com/blueprints/corej2eepatterns/Patterns/InterceptingFilter.html) pattern. It helps to attach filters for pre- and post-processing request and response. Common use is logging requests, benchmarking, access checking, caching, etc. **OOP representation** of database tables/rows is also possible. I use [DAO](http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html) or [ActiveRecord](http://martinfowler.com/eaaCatalog/activeRecord.html) on daily basis. Another approach to ORM issues is [Row Data Gateway](http://martinfowler.com/eaaCatalog/rowDataGateway.html) and [Table Data Gateway](http://martinfowler.com/eaaCatalog/tableDataGateway.html). Here's [example implementation](https://tigermouse.svn.sourceforge.net/svnroot/tigermouse/lib/model/table-gateway/TableGateway.class.php) of TDG utilising `ArrayAccess` interface. **HTML templates** also can be represented as objects. I use View objects in conjunction with Smarty template engine. I find this technique EXTREMELY flexible, quick, and easy to use. Object representing view should implement `__set` method so every property gets propagated into Smarty template. Additionally `__toString` method should be implemented to support views nesting. See example: ``` $s = new View(); $s->template = 'view/status-bar.tpl'; $s->username = "John Doe"; $page = new View(); $page->template = 'view/page.tpl'; $page->statusBar = $s; echo $page; ``` Contents of `view/status-bar.tpl`: ``` <div id="status-bar"> Hello {$username} </div> ``` Contents of `view/page.tpl`: ``` <html> <head>....</head> <body> <ul id="main-menu">.....</ul> {$statusBar} ... rest of the page ... </body> </html> ``` This way you only need to `echo $page` and inner view (status bar) will be automatically transformed into HTML. Look at [complete implementation here](https://tigermouse.svn.sourceforge.net/svnroot/tigermouse/view/core-views/View.class.php). By the way, using one of Intercepting Filters you can wrap the returned view with HTML footer and header, so you don't have to worry about returning complete page from your controller. The question of whether to use Ajax or not should not be important at time of design. The framework should be flexible enough to support Ajax natively. **Form validation** is definitely the thing that could be done in OO manner. Build complex validator object using [Composite pattern](http://www.dofactory.com/Patterns/PatternComposite.aspx). Composite validator should iterate through form fields and assigned simple validators and give you Yes/No answer. It also should return error messages so you can update the form (via Ajax or page reload). Another handy element is automatic translation class for changing data in db to be suitable for user interface. For example, if you have INT(1) field in db representing boolean state and use checkbox in HTML that results in empty string or `"on"` in \_POST or \_GET array you cannot just assign one into another. Having translation service that alters the data to be suitable for View or for db is a clean way of sanitizing data. Also, complexity of translation class does not litter your controller code even during very complex transformations (like [the one converting Wiki syntax](https://tigermouse.svn.sourceforge.net/svnroot/tigermouse/lib/translation/) into HTML). Also **i18n** problems can be solved using object oriented techniques. I like using `__` function (double underscore) to get localised messages. The function instead of performing a lookup and returning message gives me a [Proxy](http://en.wikipedia.org/wiki/Proxy_pattern) object and pre-registers message for later lookup. Once Proxy object is pushed into View AND View is being converted into HTML, i18n backend does look up for all pre-registered messages. This way only one query is run that returns all requested messages. **Access controll** issues can be addressed using Business Delegate pattern. I described it in my [other Stackoverflow answer](https://stackoverflow.com/questions/228672/php-access-control-system/325805#325805). Finally, if you would like to play with existing code that is fully object oriented, take look at [Tigermouse framework](http://tigermouse.epsi.pl/). There are some UML diagrams on the page that may help you understand how things work. Please feel free to take over further development of this project, as I have no more time to work on it. Have a nice hacking!
Now at the risk of being downvoted, whilst at the same time being someone who is developing their own framework, I feel compelled to tell you to at least get some experience using existing frameworks. It doesn't have to be a vast amount of experience maybe do some beginner tutorials for each of the popular ones. Considering the amount of time it takes to build a good framework, taking the time to look into what you like and loathe about existing solutions will pale in comparison. You don't even need to just look at php frameworks. Rails, Django etc are all popular for a reason. Building a framework is rewarding, but you need a clear plan and understanding of the task at hand, which is where research comes in. Some answers to your questions: * Yes, it should probably use MVC as the model view controller paradigm translates well into the world of web applications. * For creating models from records in tables in your database, look into ORM's and the Active Record pattern. Existing implementations to research that I know of include Doctrine, more can be found by searching on here. * For anything AJAX related I suggest using jQuery as a starting point as it makes AJAX very easy to get up and running.
Fully Object Oriented framework in PHP
[ "", "php", "frameworks", "oop", "" ]
I develop some C# plug-in libraries in VS2008 that are deployed along with someone else's application. They use ClickOnce for their deployments and I'm trying to do something a bit non-standard, I suppose. On one of the machines where the app and my DLLs are installed, I'd like to manually replace some of my DLLs to test a fix. The app is in c:\Documents and Settings\testsystem\Local Settings\Apps\2.0\blahblahblah...long nasty path\ and my DLLs are located in a subdirectory under that path. My tester took my DLLs and puts them in that subdirectory but it appears from the Trace output that he sends me that an older version of the DLL is actually running. I had the tester verify that the DLLs are in the subdirectory and the Trace log shows the correct path, indicating that the app is running from that location, but the Trace output is not from the DLL that I've sent him. The ClickOnce deployment stuff is all elven magic to me at this point. It doesn't appear that it is overwriting my new DLL but it certainly isn't running the version I expect it to run. Anyone have any ideas? Thanks, Matt
Are you sure you have the correct directory? The click-once directory structure is a bit complicated and the DLLs can be duplicated multiple times. It does not always pull the DLLs from where you expect. Also it could be pulling the DLLs from the GAC if someone once put them there. Try running up [procexp](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx), look for your app and examine the handles it holds. That will tell you the right path to the DLLs in question.
Would publishing an update to your clickonce app with the trace DLL be out of the question for you in this case? That would be the easiest way to do magic in clickonce.
ClickOnce DLL issue
[ "", "c#", "clickonce", "" ]
I have an issue with my application when Windows shuts down - my app isn't exiting nicely, resulting in the End Task window being displayed. How can I use the debugger to see what's going on? Is there a way to send the Windows shutdown message(s) to my application so it thinks Windows is shutting down, so I can see exactly how it behaves?
There is a tool named Restart Manager (rmtool.exe) in the Microsoft's Logo Testing Tools for Windows, which can be used to send shutdown and restart messages to a process. Logo testing tools can be downloaded here: <http://download.microsoft.com/download/d/2/5/d2522ce4-a441-459d-8302-be8f3321823c/LogoToolsv1.0.msi> Then you can simulate shutdown for your process: ``` rmtool.exe -p [PID] -S ``` where [PID] is the process ID. According to the Vista Logo Certification Test Cases document, > Restart Manager shutdown messages are: > > a. WM\_QUERYENDSESSION with LPARAM = ENDSESSION\_CLOSEAPP(0x1): GUI applications must respond (TRUE) immediately to prepare for a restart. > > b. WM\_ENDSESSION with LPARAM = ENDSESSION\_CLOSEAPP(0x1): The application must shutdown within 5 seconds (20 seconds for services). > > c. CTRL\_SHUTDOWN\_EVENT: Console applications must shutdown immediately.
I believe when Windows is shutting down it sends a "WM\_QueryEndSession" to all applications. To simulate a Windows shutdown you could create a little application that just does a PostMessage with this message to your application and see what happens. Windows may send more messages than that to actually close your application (like WM\_CLOSE), but whenever your application receives the "WM\_QueryEndSession" message it means your application is about to have the rug pulled out from under it.
How to simulate Windows shutdown for debugging?
[ "", "c#", ".net", "winforms", "shutdown", "" ]
I am little confused with the applicability of `reinterpret_cast` vs `static_cast`. From what I have read the general rules are to use static cast when the types can be interpreted at compile time hence the word `static`. This is the cast the C++ compiler uses internally for implicit casts also. `reinterpret_cast`s are applicable in two scenarios: * convert integer types to pointer types and vice versa * convert one pointer type to another. The general idea I get is this is unportable and should be avoided. Where I am a little confused is one usage which I need, I am calling C++ from C and the C code needs to hold on to the C++ object so basically it holds a `void*`. What cast should be used to convert between the `void *` and the Class type? I have seen usage of both `static_cast` and `reinterpret_cast`? Though from what I have been reading it appears `static` is better as the cast can happen at compile time? Though it says to use `reinterpret_cast` to convert from one pointer type to another?
The C++ standard guarantees the following: `static_cast`ing a pointer to and from `void*` preserves the address. That is, in the following, `a`, `b` and `c` all point to the same address: ``` int* a = new int(); void* b = static_cast<void*>(a); int* c = static_cast<int*>(b); ``` `reinterpret_cast` only guarantees that if you cast a pointer to a different type, *and then `reinterpret_cast` it back to the original type*, you get the original value. So in the following: ``` int* a = new int(); void* b = reinterpret_cast<void*>(a); int* c = reinterpret_cast<int*>(b); ``` `a` and `c` contain the same value, but the value of `b` is unspecified. (in practice it will typically contain the same address as `a` and `c`, but that's not specified in the standard, and it may not be true on machines with more complex memory systems.) For casting to and from `void*`, `static_cast` should be preferred.
One case when `reinterpret_cast` is necessary is when interfacing with opaque data types. This occurs frequently in vendor APIs over which the programmer has no control. Here's a contrived example where a vendor provides an API for storing and retrieving arbitrary global data: ``` // vendor.hpp typedef struct _Opaque * VendorGlobalUserData; void VendorSetUserData(VendorGlobalUserData p); VendorGlobalUserData VendorGetUserData(); ``` To use this API, the programmer must cast their data to `VendorGlobalUserData` and back again. `static_cast` won't work, one must use `reinterpret_cast`: ``` // main.cpp #include "vendor.hpp" #include <iostream> using namespace std; struct MyUserData { MyUserData() : m(42) {} int m; }; int main() { MyUserData u; // store global data VendorGlobalUserData d1; // d1 = &u; // compile error // d1 = static_cast<VendorGlobalUserData>(&u); // compile error d1 = reinterpret_cast<VendorGlobalUserData>(&u); // ok VendorSetUserData(d1); // do other stuff... // retrieve global data VendorGlobalUserData d2 = VendorGetUserData(); MyUserData * p = 0; // p = d2; // compile error // p = static_cast<MyUserData *>(d2); // compile error p = reinterpret_cast<MyUserData *>(d2); // ok if (p) { cout << p->m << endl; } return 0; } ``` Below is a contrived implementation of the sample API: ``` // vendor.cpp static VendorGlobalUserData g = 0; void VendorSetUserData(VendorGlobalUserData p) { g = p; } VendorGlobalUserData VendorGetUserData() { return g; } ```
When to use reinterpret_cast?
[ "", "c++", "casting", "reinterpret-cast", "" ]
I would like to print the "object reference" of an object in Java for debugging purposes. I.e. to make sure that the object is the same (or different) depending on the situation. The problem is that the class in question inherits from another class, which has overriden both toString() and hashCode() which would usually give me the id. Example situation: Running a multi-threaded application, where I (during development) want to check if all the threads use the same instance of a resource object or not.
What exactly are you planning on doing with it (what you want to do makes a difference with what you will need to call). [`hashCode`](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode--), as defined in the JavaDocs, says: > As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.) So if you are using `hashCode()` to find out if it is a unique object in memory that isn't a good way to do it. [`System.identityHashCode`](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#identityHashCode-java.lang.Object-) does the following: > Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero. Which, for what you are doing, sounds like what you want... but what you want to do might not be safe depending on how the library is implemented.
This is how I solved it: ``` Integer.toHexString(System.identityHashCode(object)); ```
How do you get the "object reference" of an object in java when toString() and hashCode() have been overridden?
[ "", "java", "object", "hashcode", "" ]
I'm currently working on a quite big (and old, sigh) code base, recently upgraded to VS2005 (SP1). Me and my team are changing/updating/replacing modules in this code as we go but we have occasionally been running into problems where the vtables seems broken. I am no expert on vtables but these sure seems to be broken. The errors manifests itself with this error: > Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention. Of course there can be plenty of other reasons for this error but when debugging (Debug build) I can actually verify that the vtables for the object I want to operate on look strange: The stack and heap that reference each vtable looks fine and the pointers to the vtables match perfectly to the map file. This indicates to me that this is not a memory overwriting bug or similar, since then it would affect the stack and heap rather than where the vtables are stored. (They are stored in a read only area right?) Anyway, all seems good so far. But when looking at the memory of the vtable I find that all values, if I interpret them as pointers, although they are in the same range (Eg. 0x00f203db 0x00f0f9be 0x00ecdda7 0x00f171e1) does not match any entry in the map file and many of them are not even aligned to 4 bytes. I don't know all the details of how VS2005 builds the vtables, but this looks wrong to me. If this is correct behavior, perhaps somebody can explain this to me? I guess my question boils down to what can cause this behavior? Is there any know bugs in the linker when having too complex class hierarchies for example? Has anybody seen anything similar before? Currently we are able to get around our crashes by moving functions from the affected class to inline (scary stuff!) but clearly this is not a feasible long term solution. Thanks for any insight! Update: I've been asked for more details about the project and of course I will supply this. First however, the question is not entirely related to the ESP value not being saved error. What I am most interested in is why I see the strange values in the vtable. That said, here is some additional info: The solution relies on several external and internal projects but these have not been changed in a long time, all uses the same calling convention. The code where it seems to break is all within the one pretty standard C++ "main" project of the solution. All code is built with the same compiler. The solution also doesn't use any dlls but links with plenty of static libraries: SHFolder.lib, python25.lib, dxguid.lib, d3d9.lib, d3dx9.lib, dinput8.lib, ddraw.lib, dxerr9.lib, ws2\_32.lib, mss32.lib, Winmm.lib, vtuneapi.lib, vttriggers.lib, DbgHelp.lib, kernel32.lib, user32.lib, gdi32.lib, winspool.lib, comdlg32.lib, advapi32.lib, shell32.lib, ole32.lib, oleaut32.lib, uuid.lib, odbc32.lib, odbccp32.lib
I found the problem. Silly really but the class hierarchy that caused the problem had a virtual function called GetObject which conflicted with the windows #define with the same name. The header files included these windows header files in different order, which confused the linker. So, in fact the problem was corrupted vtables, but I didn't expect this to be reason! Well you learn something every day... However, big thanks to all that replied!
I think the big hint here is in the "*This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention*" part of that error. It seems to me that there is a mismatch between the caller's API and the library which is handling the call. Also, it might be the case that you are mixing code built with different compilers. What more can you tell us about the nature of this project? Is the function you are calling located in an external library? Or can you debug through the entire call stack? **Edit**: You said that the project doesn't use any DLL's. What about static libraries?
VS2005 C++ broken vtables
[ "", "c++", "visual-studio-2005", "vtable", "" ]
If I have a code like this: ``` struct A { virtual void f(int) {} virtual void f(void*) {} }; struct B : public A { void f(int) {} }; struct C : public B { void f(void*) {} }; int main() { C c; c.f(1); return 0; } ``` I get an error that says that I am trying to do an invalid conversion from int to void\*. Why can't compiler figure out that he has to call B::f, since both functions are declared as virtual? --- After reading jalf's answer I went and reduced it even further. This one does not work as well. Not very intuitive. ``` struct A { virtual void f(int) {} }; struct B : public A { void f(void*) {} }; int main() { B b; b.f(1); return 0; } ```
The short answer is "because that's how overload resolution works in C++". The compiler searches for functions F inside the C class, and if it finds any, it stops the search, and tries to pick a candidate among those. It only looks inside base classes if no matching functions were found in the derived class. However, you can explicitly introduce the base class functions into the derived class' namespace: ``` struct C : public B { void f(void*) {} using B::f; // Add B's f function to C's namespace, allowing it to participate in overload resolution }; ```
Or you could do this: ``` void main() { A *a = new C(); a->f(1); //This will call f(int) from B(Polymorphism) } ```
C++ member function virtual override and overload at the same time
[ "", "c++", "inheritance", "polymorphism", "virtual", "" ]
Why do applets have such a low adoption level, compared for example against [Flash](http://en.wikipedia.org/wiki/Adobe_Flash)? Is it because they are technological disadvantages, or is it just an issue of popularity?
One point everyone seems to be forgetting: Originally Flash had a very designer oriented work-flow, so many graphical designers jumped on board and made cool looking stuff, which Internet-users found fun, so they would download Flash, and the community grew. Java Applets on the other hand were targeted at programmers and enterprises, and that was fine, but boring to the average user. And on-top of that the script kiddies of the time (myself included) made Applets that leaked resources and/or froze the browser, and even other more skilled kiddies used the powers of Applets to create traps, and harmful websites, so most Internet users wouldn't enable Applets. So in the end it was probably the target developers (graphical designers vs. programmers) of each platform that caused the issues.
Java vs Flash then and now: Then: 1. Flash had a single-click installer that took 2 minutes to download and run. Java had an installer that took 10 minutes to download and run. 2. Flash applications loaded in less than a second. Java applets took 10 seconds. 3. Flash applications tended to be self-contained and would "just work". Java applets tend to refer to external resources. Broken links were frequent and the applet engine was plagued by stability problems that could sometimes take down the entire browser. 4. Flash adoption was at all-time high because it shipped with Windows. Java did not. Now: 1. Sun rolled out a single-click installer called [Java Kernel](http://java.sun.com/javase/6/6u10faq.jsp#JKernel) that takes 2 minutes to download and run. 2. Java6 update 12 loads applets in under a second. 3. Java applets now run in a separate process than the browser and the engine has been rewritten from the ground up. Stability issues are a thing of the past. Unfortunately, the web is still full of old applets containing broken links. 4. Java ships standard with most new computers. Java adoption rates vary from 70% - 90% depending on who you talk to. Feel free to [measure](http://cowwoc.blogspot.com/2008/12/tracking-java-versions-using-google.html) your own website. The one big difference that remains is that Flash has better artist-oriented tools than Java does. That being said, there is a huge range of software that you can write easier and more efficiently in Java than in Flash. Java is a far more mature and scalable platform. You will see many people using Flash for ad banners, but far more people using Java for full-fledged applications or games. For example, compare 3D rendering support in Java versus Flash.
Why do applets have such a low adoption level?
[ "", "java", "flash", "applet", "" ]
Consider an HTML form: ``` <form action="" method="POST" onsubmit="return checkValidArray()"> <input type="text" name="data" onchange="return validate(this);"> </form> ``` It appears (in both IE 6 and Firefox 3) that when you type some text into the input field and click submit that the onchange event fires for the input field, but the onsubmit event does not fire for the form until you click the submit button a second time (at which time the onchange does not fire, of course). In other words, the onchange seems to prevent the onsubmit from firing. The desire is to check each field in the form when the user exits the field in order to provide them with immediate validation feedback, and also to prevent submission of the form if there is invalid data. [EDIT: Note that both validation functions contain an alert().] How does one get around this problem?
Solution (of a sort): It turns out that it is only presence of an alert() - or a confirm() - during the input's onchange event that causes the form's onsubmit event to not fire. The JS thread appears to get blocked by the alert(). The workaround is to not include any alert() or confirm() in the input's onchange call. Browsers known to be affected: IE6 - Windows IE8 - Win FF3 - Win Browsers known not to be affected: Google Chrome - Win Safari - Mac FF - Mac
I tried with Firefox 3 (Mac) with the following code: ``` <html> <head> <script> function validate(ele) { alert("vali"); return false; } function checkValidArray() { alert("checkValidArray"); } </script> </head> <body> <form action="" method="POST" onsubmit="return checkValidArray()"> <input type="text" name="data" onchange="return validate(this);"> <input type="submit" value="Ok"> </form> </body> </html> ``` It seems to work. When I click on the Ok button, both "Vali" and "Check Valid Array" pop up. Initially I thought `return false` could be the reason why the form was not submitted, but it IS submitted (at least, `checkValidArray()` is called). Now, what are you doing in your `checkValidArray()` and `validate()` methods? Something special? Can you post the code? EDIT: I tested with IE8 and FF3 on windows, and here both events do not get fired. I have no idea why. Perhaps onblur IS a solution, but WHY does onchange not work? Is there a specific reason or is it just another inconsistency? (Works on both FF and Safari on Mac)
Javascript onchange event preventing onsubmit event in HTML form?
[ "", "javascript", "html", "validation", "onchange", "" ]
The following code implements a simple singleton that ensures only 1 instance of my application can be run. However, if another instance is started, I need to be able to grab that instance's command-line arguments, pass them to the initial instance, then terminate the second instance. The issue comes in when I'm attempting to get hold of the first instance of the application. Once I've found the handle of that instance's main form, I pass it to the `Control.FromHandle()` method, expecting to get back a `MainForm`. Instead, the return value is always `null`. (`Control.FromChildHandle()` gives the same result.) Therefore, my question is simply: what am I doing wrong? And is this even possible in .NET? ``` public class MainForm : Form { [DllImport("user32")] extern static int ShowWindowAsync(IntPtr hWnd, int nCmdShow); [DllImport("user32")] extern static bool SetForegroundWindow(IntPtr hWnd); private Mutex singletonMutex; private void MainForm_Load(object sender, EventArgs e) { bool wasCreated; singletonMutex = new Mutex(false, Application.ProductName + "Mutex", out wasCreated); // returns false for every instance except the first if (!wasCreated) { Process thisProcess = Process.GetCurrentProcess(); Process[] peerProcesses = Process.GetProcessesByName(thisProcess.ProcessName.Replace(".vshost", string.Empty)); foreach (Process currentProcess in peerProcesses) { if (currentProcess.Handle != thisProcess.Handle) { ShowWindowAsync(currentProcess.MainWindowHandle, 1); // SW_NORMAL SetForegroundWindow(currentProcess.MainWindowHandle); // always returns null !!! MainForm runningForm = (MainForm) Control.FromHandle(currentProcess.MainWindowHandle); if (runningForm != null) { runningForm.Arguments = this.Arguments; runningForm.ProcessArguments(); } break; } } Application.Exit(); return; } } ```
Single-instance apps are well supported by the .NET framework. Check [this thread](http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/a7082d6a-627f-436e-88d6-20ebff7efc8d/) for an example that does exactly what you need.
Try the following ``` var form = (Form)(Control.FromHandle(myHandle)); ``` **EDIT** Re-read your question and realized you are looking at a handle in another process. There is no way to convert a handle in another process to a Form instance in the current process. My solution will only work for handles in the same process. The only way to get ahold of the Form instance is to use Remoting. But that will require cooperation on the part of both processes which does not appear to be what you are looking for.
How do I get a System.Windows.Form instance from its Win32 handle?
[ "", "c#", "winforms", "winapi", "interop", "ipc", "" ]
* a ticketing site offers a discount on "family" tickets. * a family ticket is 2 adults, 2 children. * the sell tickets page allows a user to enter any number of adult and child tickets. **How do I work out how to apply the family ticket discount, then charge all remaining tickets at their relevant cost (i.e. adult tickets cost more than child tickets) ?** Here's what I have so far (seems to work, but not 100% confident about it (php)) ``` # Work out how many pairs of people there are $numAdultPairs = floor($oForm->adult / 2); $numChildPairs = floor($oForm->child / 2); # work out the number of matching pairs for child / adult if ( $numAdultPairs > $numChildPairs ) { $numberOfFamilyTickets = $numAdultPairs - $numChildPairs; } else if ( $numAdultPairs < $numChildPairs ){ $numberOfFamilyTickets = $numChildPairs - $numAdultPairs; } else if ( $numAdultPairs == $numChildPairs ) { $numberOfFamilyTickets = $numAdultPairs; } # work out the remaining tickets required $remainingAdult = $oForm->adult % 2; $remainingChild = $oForm->child % 2; ```
I don't think your approach actually works. Assume you have 6 adults and 4 children. In this case your first `if` would be true and you would end up with `3 - 2 = 1` family ticket. The correct result would be two family tickets and two adult tickets, though. You want the lowest number of pairs to determine the amount of family tickets. Try something like this: ``` $numberOfFamilyTickets = min($numAdultPairs, $numChildPairs); $remainingAdult = $oForm->adult - 2 * $numberOfFamilyTickets; $remainingChild = $oForm->child - 2 * $numberOfFamilyTickets; ``` Assuming you make sure that `$oForm->adult` and `$oForm->child` are non-negative.
Something along these lines (pseudocode): ``` adultPairs = totalAdults / 2 childPairs = totalChildren / 2 familyPairs = min(adiltPairs, childPairs) adults = totalAdults - familyPairs * 2 children = totalChildren - familyPairs * 2 ```
Calculate num of 2xadult + 2xchild combinations
[ "", "php", "math", "" ]
I am creating a game with an ascii-like map using Java2D on Linux (like a roguelike). By rendering BufferedImages via Graphics2D.drawImage the terrain is rendered. I would like to change the hue of each drawn image on the fly, without hurting performance too much. How can I achieve this? I suspect setComposite is part of the puzzle. Currently I do not need to keep the background intact (so transparency is not an issue). I want to use a wide variety of colors, so pre-generating tinted sprites is not a solution for me.
For high performance you might want to use JOGL. It gives you good access to hardware acceleration, even if you do not need to 3D features.
I asked a similar question a while ago and got a pretty good answer [here](https://stackoverflow.com/questions/23763/colorizing-images-in-java), although I was doing all of the tinting ahead of time. In any case, you'll probably want to look at BufferedImageOp. Also, the [JH Labs site](http://www.jhlabs.com/ip/) has a ton of useful info on doing image processing in java.
tinting sprites in Java2D on the fly?
[ "", "java", "java-2d", "" ]
Following from this [OS-agnostic question](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python), specifically [this response](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291), similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from Windows using Python (including, but not limited to memory usage).
There was a similar question asked: [How to get current CPU and RAM usage in Python?](https://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python) There are quite a few answers telling you how to accomplish this in windows.
In Windows, if you want to get info like from the SYSTEMINFO command, you can use the [WMI module.](https://pypi.python.org/pypi/WMI/) ``` import wmi c = wmi.WMI() systeminfo = c.Win32_ComputerSystem()[0] Manufacturer = systeminfo.Manufacturer Model = systeminfo.Model ``` ... similarly, the os-related info could be got from `osinfo = c.Win32_OperatingSystem()[0]` the full list of [system info is here](http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx) and [os info is here](http://msdn.microsoft.com/en-us/library/windows/desktop/aa394239%28v=vs.85%29.aspx)
How can I read system information in Python on Windows?
[ "", "python", "windows", "operating-system", "" ]
I want to use pimpl idiom with inheritance. Here is the base public class and its implementation class: ``` class A { public: A(){pAImpl = new AImpl;}; void foo(){pAImpl->foo();}; private: AImpl* pAImpl; }; class AImpl { public: void foo(){/*do something*/}; }; ``` And I want to be able to create the derived public class with its implementation class: ``` class B : public A { public: void bar(){pAImpl->bar();}; // Can't do! pAimpl is A's private. }; class BImpl : public AImpl { public: void bar(){/*do something else*/}; }; ``` But I can't use pAimpl in B because it is A's private. So I see some ways to solve it: 1. Create BImpl\* pBImpl member in B, and pass it to A with additional A constructor, A(AImpl\*). 2. Change pAImpl to be protected (or add a Get function), and use it in B. 3. B shouldn't inherit from A. Create BImpl\* pBImpl member in B, and create foo() and bar() in B, that will use pBImpl. 4. Any other way? What should I choose?
``` class A { public: A(bool DoNew = true){ if(DoNew) pAImpl = new AImpl; }; void foo(){pAImpl->foo();}; protected: void SetpAImpl(AImpl* pImpl) {pAImpl = pImpl;}; private: AImpl* pAImpl; }; class AImpl { public: void foo(){/*do something*/}; }; class B : public A { public: B() : A(false){ pBImpl = new BImpl; SetpAImpl(pBImpl); }; void bar(){pBImpl->bar();}; private: BImpl* pBImpl; }; class BImpl : public AImpl { public: void bar(){/*do something else*/}; }; ```
I think the best way from a purely object-oriented-theoretical perspective is to not make BImpl inherit from AImpl (is that what you meant in option 3?). However, having BImpl derive from AImpl (and passing the desired impl to a constructor of A) is OK as well, provided that the pimpl member variable is `const`. It doesn't really matter whether you use a get functions or directly access the variable from derived classes, unless you want to enforce const-correctness on the derived classes. Letting derived classes change pimpl isn't a good idea - they could wreck all of A's initialisation - and nor is letting the base class change it a good idea. Consider this extension to your example: ``` class A { protected: struct AImpl {void foo(); /*...*/}; A(AImpl * impl): pimpl(impl) {} AImpl * GetImpl() { return pimpl; } const AImpl * GetImpl() const { return pimpl; } private: AImpl * pimpl; public: void foo() {pImpl->foo();} friend void swap(A&, A&); }; void swap(A & a1, A & a2) { using std::swap; swap(a1.pimpl, a2.pimpl); } class B: public A { protected: struct BImpl: public AImpl {void bar();}; public: void bar(){static_cast<BImpl *>(GetImpl())->bar();} B(): A(new BImpl()) {} }; class C: public A { protected: struct CImpl: public AImpl {void baz();}; public: void baz(){static_cast<CImpl *>(GetImpl())->baz();} C(): A(new CImpl()) {} }; int main() { B b; C c; swap(b, c); //calls swap(A&, A&) //This is now a bad situation - B.pimpl is a CImpl *, and C.pimpl is a BImpl *! //Consider: b.bar(); //If BImpl and CImpl weren't derived from AImpl, then this wouldn't happen. //You could have b's BImpl being out of sync with its AImpl, though. } ``` Although you might not have a swap() function, you can easily conceive of similar problems occurring, particularly if A is assignable, whether by accident or intention. It's a somewhat subtle violation of the Liskov substitutability principle. The solutions are to either: 1. Don't change the pimpl members after construction. Declare them to be `AImpl * const pimpl`. Then, the derived constructors can pass an appropriate type and the rest of the derived class can downcast confidently. However, then you can't e.g. do non-throwing swaps, assignments, or copy-on-write, because these techniques require that you can change the pimpl member. However however, you're probably not really intending to do these things if you have an inheritance hierarchy. 2. Have unrelated (and dumb) AImpl and BImpl classes for A and B's private variables, respectively. If B wants to do something to A, then use A's public or protected interface. This also preserves the most common reason to using pimpl: being able to hide the definition of AImpl away in a cpp file that derived classes can't use, so half your program doesn't need to recompile when A's implementation changes.
Pimpl idiom with inheritance
[ "", "c++", "inheritance", "oop", "pimpl-idiom", "" ]
I'm trying to do some Socket programming in Java, and I'm using the BufferedStreamReader.read(char[]) method. the java doc states: > Reads characters into an array. This > method will block until some input is > available, an I/O error occurs, or the > end of the stream is reached. Only it's not blocking on input. can somone point out the problem with the following code? Even with the line that writes to the output stream the line that prints "RCVD:" is printing but without any data after the RCVD. ``` public class Main { /** * @param args the command line arguments */ private static Socket tcpSocket; public static void main(String args[]) { try { tcpSocket = new Socket("localhost", 8080); } catch (UnknownHostException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } new Thread(new Runnable() { public void run() { try { System.out.println("Starting listening"); char[] dataBytes = new char[9]; BufferedReader netStream = new BufferedReader(new InputStreamReader(tcpSocket.getInputStream())); while (true) { netStream.read(dataBytes); System.out.println("RCVD: " + String.copyValueOf(dataBytes)); } } catch (UnknownHostException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); new Thread(new Runnable(){ public void run() { System.out.println("Starting Writer"); PrintWriter out = null; try { out = new PrintWriter(tcpSocket.getOutputStream(), true); for (int i = 0 ; i < 10 ; i++) { // out.println("000000000"); } } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); } } ``` **ADDITIONAL INFO** I've tried changing the port number and the application crashes, maybe I'm connecting to something else running on the machine. Also I am reciveing a steady stream of bytes all of which are spaces by the looks of it.
You need to look into [ServerSocket](http://java.sun.com/javase/6/docs/api/java/net/ServerSocket.html). Your Socket at the moment is not actually 'listening', it's trying to connect to localhost:8080 but not actually listen on it!
You are, in fact, connecting to something else on your local machine. Looking at the code above, it looks as if you're expecting to receive, in the socket's input stream, the data that you write into its output buffer. It looks as if you're thinking of the socket as a length of tube, with the input stream at one end of the tube and the output stream at the other end. A socket is in fact *one* end of the tube, with the input stream allowing you to hear what comes down it and the output stream allowing you to "talk" into the tube. Possibly I am confused as to what is confusing you... Does the above help ?
Reading from a socket not waiting for input?
[ "", "java", "sockets", "" ]
What is the difference between Parse() and TryParse()? ``` int number = int.Parse(textBoxNumber.Text); // The Try-Parse Method int.TryParse(textBoxNumber.Text, out number); ``` Is there some form of error-checking like a Try-Catch Block?
`Parse` throws an exception if it cannot parse the value, whereas `TryParse` returns a `bool` indicating whether it succeeded. `TryParse` does not just `try`/`catch` internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the `Parse` method will call `TryParse` and then throw an exception if it returns `false`. In a nutshell, use `Parse` if you are sure the value will be valid; otherwise use `TryParse`.
If the string can not be converted to an integer, then * `int.Parse()` will throw an exception * `int.TryParse()` will return false (but not throw an exception)
Parse v. TryParse
[ "", "c#", "parsing", "integer", "tryparse", "" ]
While refactoring some C# classes, I've run into classes that implement IDisposable. Without thinking, I have created partial class files for each class that implements IDisposable interface. E.g.) For Stamper.cs -> Stamper.cs + Stamper.Dispose.cs where **Stamper.cs** contains actual logic for stamping and **Stamper.Dispose.cs** that contains dispose logic ``` // Stamper.cs public partial class Stamper { // actual logic } // Stamper.Dispose.cs public partial class Stamper: IDisposable { // Implement IDisposable } ``` When I looked at the code, Stamper.cs now looks a lot cleaner and readable (now about 52 lines instead of 100 lines where around 50 lines was simply a clean-up dispose code) Am I going too far with this? **\*EDIT**: Thanks folks for your opinions - I have decided to put two files together into one. The Problem I had faced was that I was actually forgetting to update IDisposable implementation after updating actual logic. Moreover there wasn't much problem navigating between method in the source code. The first reason seems more than a reason enough to stick with one file solution in my specific case.
It seems about as arbitrary as creating a partial class for constructor logic. Now I have to look at two files to grock that class. Partial classes are only really worth it for designer stuff...
Yes, too far. Whats wrong with just sticking a #Region around the code and folding it so you cant see it?
Should I separate Dispose logic into a partial class file?
[ "", "c#", "refactoring", "idisposable", "partial-classes", "" ]
Good morning. As the title indicates, I've got some questions about using python for web development. * What is the best setup for a development environment, more specifically, what webserver to use, how to bind python with it. Preferably, I'd like it to be implementable in both, \*nix and win environment. My major concern when I last tried apache + mod\_python + CherryPy was having to reload webserver to see the changes. Is it considered normal? For some reason cherrypy's autoreload didn't work at all. * What is the best setup to deploy a working Python app to production and why? I'm now using lighttpd for my PHP web apps, but how would it do for python compared to nginx for example? * Is it worth diving straight with a framework or to roll something simple of my own? I see that Django has got quite a lot of fans, but I'm thinking it would be overkill for my needs, so I've started looking into CherryPy. * How exactly are Python apps served if I have to reload httpd to see the changes? Something like a permanent process spawning child processes, with all the major file includes happening on server start and then just lazy loading needed resources? * Python supports multithreading, do I need to look into using that for a benefit when developing web apps? What would be that benefit and in what situations? Big thanks!
So here are my thoughts about it: I am using [Python Paste](http://pythonpaste.org/) for developing my app and eventually also running it (or any other python web server). I am usually not using mod\_python or mod\_wsgi as it makes development setup more complex. I am using [zc.buildout](http://pypi.python.org/pypi/zc.buildout) for managing my development environment and all dependencies together with [virtualenv](http://pypi.python.org/pypi/virtualenv). This gives me an isolated sandbox which does not interfere with any Python modules installed system wide. For deployment I am also using buildout/virtualenv, eventually with a different buildout.cfg. I am also using [Paste Deploy](http://pythonpaste.org/deploy/) and it's configuration mechanism where I have different config files for development and deployment. As I am usually running paste/cherrypy etc. standalone I am using Apache, NGINX or maybe just a Varnish alone in front of it. It depends on what configuration options you need. E.g. if no virtual hosting, rewrite rules etc. are needed, then I don't need a full featured web server in front. When using a web server I usually use ProxyPass or some more complex rewriting using mod\_rewrite. The Python web framework I use at the moment is [repoze.bfg](http://static.repoze.org/bfgdocs/) right now btw. As for your questions about reloading I know about these problems when running it with e.g. mod\_python but when using a standalone "paster serve ... -reload" etc. it so far works really well. repoze.bfg additionally has some setting for automatically reloading templates when they change. If the framework you use has that should be documented. As for multithreading that's usually used then inside the python web server. As CherryPy supports this I guess you don't have to worry about that, it should be used automatically. You should just eventually make some benchmarks to find out under what number of threads your application performs the best. Hope that helps.
**What is the best setup for a development environment?** Doesn't much matter. We use Django, which runs in Windows and Unix nicely. For production, we use Apache in Red Hat. **Is having to reload webserver to see the changes considered normal?** Yes. Not clear why you'd want anything different. Web application software shouldn't be dynamic. Content yes. Software no. In Django, we *develop* without using a web server of any kind on our desktop. The Django "runserver" command reloads the application under most circumstances. For development, this works great. The times when it won't reload are when we've damaged things so badly that the app doesn't properly. **What is the best setup to deploy a working Python app to production and why?** "Best" is undefined in this context. Therefore, please provide some qualification for "nest" (e.g., "fastest", "cheapest", "bluest") **Is it worth diving straight with a framework or to roll something simple of my own?** Don't waste time rolling your own. We use Django because of the built-in admin page that we don't have to write or maintain. Saves mountains of work. **How exactly are Python apps served if I have to reload httpd to see the changes?** Two methods: * Daemon - mod\_wsgi or mod\_fastcgi have a Python daemon process to which they connect. Change your software. Restart the daemon. * Embedded - mod\_wsgi or mod\_python have an embedded mode in which the Python interpreter is inside the mod, inside Apache. You have to restart httpd to restart that embedded interpreter. **Do I need to look into using multi-threaded?** Yes and no. Yes you do need to be aware of this. No, you don't need to do very much. Apache and mod\_wsgi and Django should handle this for you.
Python web programming
[ "", "python", "cherrypy", "" ]
I'm working on repairing the test suite for a project of ours, which is being tested through Hibernate/DBUnit. There are several test cases which all throw a similar exception from Hibernate, which looks something like this: *java.sql.SQLException: Not in aggregate function or group by clause: org.hsqldb.Expression@109062e in statement [... blah ...]* Through my googling, I am suspicious that this is caused by our use of the aggregate function AVG(), as this is in the exception's message, and all of the queries that throw contain it. However, I discovered several links to people who were getting this error, and were able to fix it by either commenting out an "ORDER BY" or "GROUP BY" clause, or by including the other columns from the SELECT clause in the grouping. I understand why this would fix such an error message, but I'm not sure whether it applies to my situation, because I tried doing the same and it made no difference. Also, we have some test cases throwing exceptions which use ORDER/GROUP, but not all. For example: ``` ThingerVO myThinger = (ThingerVO)session.createQuery("SELECT new ThingerVO(" + "r.id, " + "u.id, " + "u.alias, " + "s.id, " + "s.name, " + "r.URL," + "AVG(v.rating), " + "r.totalCount, " + "r.isPrivate, " + "a.id, " + "a.name, " + "r.transactionId, " + "r.size, " + "u.hasPicture " + ") FROM Thinger r LEFT OUTER JOIN r.votes as v, Table1S s " + "JOIN s.Table2A AS a, User u " + "WHERE r.userId = u.id AND " + "s.id = r.Table1SId AND " + "r.id = :thingId") .setInteger("thingId", thingId) .uniqueResult(); ``` This query also causes the same exception to be thrown, even though it doesn't use an ORDER/GROUP clause. Also, I cut/pasted the generated HSQL code from Hibernate directly into the MySQL query browser, and it ran without problems. Also, it's worth pointing out that all of this code works fine on our production database, so I'm really confused as to why it throws here. Some other potentially useful information -- we're using a flat XML database structure with some dummy test data for the test cases, and the MySQL dialect for hibernate. We're using dbunit 2.4.3/hibernate 3.2.6. I tried using the latest hibernate, version 3.3.1, but it behaved the same. Any pointers or hints would be greatly appreciated.
If you use an aggregate function (e.g. `AVG()`) in the SELECT part of the SQL query along with other non-aggregate expressions, then you must have a GROUP BY clause which should list all the non-aggregate expressions. I'm not familiar with java, but looking at the code, it looks like it's going to create and run a query something like this (not quite right, but close enough, I think): ``` SELECT r.id, u.id, u.alias, s.id, s.name, r.URL, AVG(v.rating), r.totalCount, r.isPrivate, a.id, a.name, r.transactionId, r.size, u.hasPicture FROM Thinger r LEFT OUTER JOIN r.votes as v, Table1S s JOIN s.Table2A AS a, User u WHERE r.userId = u.id AND s.id = r.Table1SId AND r.id = :thingId ``` ... This has no `GROUP BY`, but does mix aggregate and non-aggregate expressions in the SELECT clause. The problem is that the SQL is badly formed. The fix would be to add a `GROUP BY` to the end of the query. I can't say why this is working in your production system, but I suspect that there is some subtle difference there. Perhaps something is adding the `GROUP BY` automatically? Can you post a printout of the SQL it executes?
Also, `ORDER BY` does not work in hsqldb when the order-by field is not a String. Unfortunately, this results in the *Not in aggregate function or group by clause* error message, which suggests a grouping problem, hence the confusion... See: <http://markmail.org/message/42vmifme4opz4jgl>
SQL query throws "not in aggregate function or group by clause" exception
[ "", "sql", "hibernate", "hsqldb", "dbunit", "" ]
I am writing a php script and somewhere before my `header()` function i have printed text to the browser hereby causing my `header()` function give me a well known error: > Warning: Cannot modify header information - headers already sent. Now my question is, I have the intentions of using `ob_start()` and `ob_flush()` before and after the `header()` function. But I once heard something like output buffer can affect the performance of one's application negatively. How true is that? Or should I just stick with the idea of printing Javascript function to redirect the page. Thanks for your time.
Using an output buffer requires the server to store the entire output of the PHP in RAM, so if it's a large page, you'll wind up using a fair amount of memory - and the server will also have to wait until the entire page is generated before sending it out, which could cause a small delay. But other than that, I don't think there's much of a disadvantage in using an output buffer. For what you want to do, it's certainly a reasonable solution.
> We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Test `ob_start` and friends to see if the performance difference matters. If it does, look for alternatives. The easiest option is to move the `header()` call before your printing. As you are likely performing a redirect with something like: ``` header('Location: /new/location/'); ``` You should not print anything before this `header()` call because the client wouldn't do anything with the data you printed anyway (unless there's something I'm missing about HTTP). (Javascript is not a good option for redirects, and nor is `meta` refreshing, unless you want to detect Javascript for some reason.)
How can an output buffer worsen performance
[ "", "php", "output-buffering", "" ]
How do you create multiple DB connections using Singleton pattern? Or maybe there's better approach, to share the same class but multiple connections?
How about using a Factory pattern to return the same instance for each connection, e.g. ``` ConnectionFactory::getInstance(ConnectionFactory::DEVELOPMENT); ``` Returns a `Connection` instance for a connection to the development database. Instantiation of the `Connection` should only be performed by the `ConnectionFactory`, which can keep references to those instances in a static array, keyed by the connection type. This avoid the singleton pattern, but ensures you only maintain a single instance of each `Connection`.
I've come up with this solution: ``` class Database { private static $instances = array(); public static function getInstance($connection='default') { if (!array_key_exists($connection,self::$instances)) { self::$instances[$connection] = new Database($connection); } return self::$instances[$connection]; } private function __construct($connection) { $this->credentials = // getting credentials from config by $connection... $this->connect(); // connect using credentials } } $DB1 = Database::getInstance('development'); $DB2 = Database::getInstance('production'); ``` Seems like works for me. Is this a Singleton pattern or something mixed?
Multiple DB connection class
[ "", "php", "class", "singleton", "object", "" ]
I need to get a zip file from an email attachment, unzip it and copy it somewhere. What would be the way I should go about it? I'm currently googling around things like 'Exchange API' and 'processing email attachments' and kind of hoping this kind of thing has been done before. The environment will be Windows and Exchange 2003, and any coding will preferably be in C#.
I did this in the end using [Redemption](https://stackoverflow.com/questions/589254/using-redemption-outlook-with-a-user-other-than-the-logged-in-user-and-gettin) I had a couple of problems, hence the linked question but got there in the end. You do need to have the Outlook client installed, and you need **full** mailbox rights (not just read) on whatever mailbox you are trying to access. This question, [Read MS Exchange email in C#](https://stackoverflow.com/questions/652549/read-ms-exchange-email-in-c/652724#652724) asked a couple of weeks after mine got some good answers as well.
I had to do this some time ago, and the best way is to use WEBDAV. Every mail item can be referenced like a URL. If you check out this [blog post on WEBDAV](http://msdn.microsoft.com/en-us/library/ms877930(EXCHG.65).aspx), it should show you the way.
How should I go about getting and processing an (Exchange) email attachment?
[ "", "c#", "attachment", "exchange-server-2003", "" ]
I'm trying to gain some memory saving in a C++ program and I want to know if I can use blocks as a scope for variables (as in Perl). Let's say I have a **huge** object that performs some computations and gives a result, does it makes sense to do: ``` InputType input; ResultType result; { // Block of code MyHugeObject mho; result = mho.superHeavyProcessing(); } /* My other code ... */ ``` Can I expect the object to be destroyed when exiting the block?
Yes, you can. The destructor will be called as soon as the variable **falls out of scope** and it should release the heap-allocated memory.
Yes absolutely, and in addition to conserving memory, calling the destructor on scope exit is often used where you want the destructor to actually do something when the destructor is called (see RAII). For example, to create a scope based lock and release easily it in an exception safe way, or to let go of access to a shared or precious resource (like a file handle / database connection) deterministically. -Rick
Can I use blocks to manage memory consumption in C++?
[ "", "c++", "object", "scoping", "" ]
I have an existing database I'm trying to put a cake app on top of. The old app used crypt() in Perl to hash the passwords. I need to do the same in the PHP app. Where is the correct place to make that change in a standard cakephp app? And what would such a change look like?
I got it working... here is my AppController: ``` class AppController extends Controller { var $components = array('Auth'); function beforeFilter() { // this is part of cake that serves up static pages, it should be authorized by default $this->Auth->allow('display'); // tell cake to look on the user model itself for the password hashing function $this->Auth->authenticate = ClassRegistry::init('User'); // tell cake where our credentials are on the User entity $this->Auth->fields = array( 'username' => 'user', 'password' => 'pass', ); // this is where we want to go after a login... we'll want to make this dynamic at some point $this->Auth->loginRedirect = array('controller'=>'users', 'action'=>'index'); } } ``` Then here is the user: ``` <?php class User extends AppModel { var $name = 'User'; // this is used by the auth component to turn the password into its hash before comparing with the DB function hashPasswords($data) { $data['User']['pass'] = crypt($data['User']['pass'], substr($data['User']['user'], 0, 2)); return $data; } } ?> ``` Everything else is normal, i think. Here is a good resource: <http://teknoid.wordpress.com/2008/10/08/demystifying-auth-features-in-cakephp-12/>
Actually the above described method by danb didn't work for me in CakePHP 2.x Instead I ended up creating a custom auth component to bypass the standard hashing algorithm: /app/Controller/Component/Auth/CustomFormAuthenticate.php ``` <?php App::uses('FormAuthenticate', 'Controller/Component/Auth'); class CustomFormAuthenticate extends FormAuthenticate { protected function _password($password) { return self::hash($password); } public static function hash($password) { // Manipulate $password, hash, custom hash, whatever return $password; } } ``` ...and then use that in my controller... ``` public $components = array( 'Session', 'Auth' => array( 'authenticate' => array( 'CustomForm' => array( 'userModel' => 'Admin' ) ) ) ); ``` This last block can also be put inside the *beforeFilter* method of the *AppController*. In my case I just choose to put it specifically in one controller where I was going to use custom authentication with a different user model.
How do I replace the cakephp password hashing algorithm?
[ "", "php", "authentication", "cakephp", "crypt", "" ]
I have a project that has a list of gps coordinates. I would like to find a way to make a simple map of those coordinates (possibly just one at a time). The map should have basic street info. This part of our project is pretty simple so I don't think it needs to be an exceptionally feature rich product. This also means it shouldn't be really expensive. What is a good product to achieve this? edit: This is a desktop app where internet connectivity will probably not be available.
Google Maps is great for this. If this is a desktop app with internet access you could still host an IE control and show it there. EDIT: If this is a desktop app without internet access you'll have to buy something like Microsoft Streets & Trips. I don't know if it has reusable controls. You probably have to buy something more expensive to get that. Applications of this nature often fall under the category "GIS". Try searching Google for that.
[Sharpmap](http://www.codeplex.com/SharpMap) is open source project written in C# and released under LGPL. To quote first line from page: > SharpMap is an easy-to-use mapping library for use in web and desktop applications.
What is a good api for mapping gps coordinates in c#?
[ "", "c#", "dictionary", "gps", "gis", "" ]
I'm doing a document viewer for some document format. To make it easier, let's say this is a PDF viewer, a **Desktop application**. One requirement for the software is the speed in rendering. So, right now, I'm caching the image for the next pages while the user is scrolling through the document. This works, the UI is very responsive and it seems like the application is able to render the pages almost instantly....at a cost : the memory usage sometimes goes to 600MB. I cache it all in memory. Now, I can cache to disk, I know, but doing that all the time is noticeably slower. What I would like to do is implement some cache (LRU?), where some of the cached pages (image objects) are on memory and most of them are on disk. Before I embark on this, is there something in the framework or some library out there that will do this for me? It seems a pretty common enough problem. (This is a desktop application, not ASP.NET) Alternatively, do you have other ideas for this problem?
I wrote an LRU Cache and some test cases, feel free to use it. You can read through the source on [my blog](http://samsaffron.com/archive/2009/08/21/Behaviour+driven+design+using+rspec+IronRuby+and+C). For the lazy (here it is minus the test cases): ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LRUCache { public class IndexedLinkedList<T> { LinkedList<T> data = new LinkedList<T>(); Dictionary<T, LinkedListNode<T>> index = new Dictionary<T, LinkedListNode<T>>(); public void Add(T value) { index[value] = data.AddLast(value); } public void RemoveFirst() { index.Remove(data.First.Value); data.RemoveFirst(); } public void Remove(T value) { LinkedListNode<T> node; if (index.TryGetValue(value, out node)) { data.Remove(node); index.Remove(value); } } public int Count { get { return data.Count; } } public void Clear() { data.Clear(); index.Clear(); } public T First { get { return data.First.Value; } } } } ``` LRUCache ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LRUCache { public class LRUCache<TKey, TValue> : IDictionary<TKey, TValue> { object sync = new object(); Dictionary<TKey, TValue> data; IndexedLinkedList<TKey> lruList = new IndexedLinkedList<TKey>(); ICollection<KeyValuePair<TKey, TValue>> dataAsCollection; int capacity; public LRUCache(int capacity) { if (capacity <= 0) { throw new ArgumentException("capacity should always be bigger than 0"); } data = new Dictionary<TKey, TValue>(capacity); dataAsCollection = data; this.capacity = capacity; } public void Add(TKey key, TValue value) { if (!ContainsKey(key)) { this[key] = value; } else { throw new ArgumentException("An attempt was made to insert a duplicate key in the cache."); } } public bool ContainsKey(TKey key) { return data.ContainsKey(key); } public ICollection<TKey> Keys { get { return data.Keys; } } public bool Remove(TKey key) { bool existed = data.Remove(key); lruList.Remove(key); return existed; } public bool TryGetValue(TKey key, out TValue value) { return data.TryGetValue(key, out value); } public ICollection<TValue> Values { get { return data.Values; } } public TValue this[TKey key] { get { var value = data[key]; lruList.Remove(key); lruList.Add(key); return value; } set { data[key] = value; lruList.Remove(key); lruList.Add(key); if (data.Count > capacity) { data.Remove(lruList.First); lruList.RemoveFirst(); } } } public void Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } public void Clear() { data.Clear(); lruList.Clear(); } public bool Contains(KeyValuePair<TKey, TValue> item) { return dataAsCollection.Contains(item); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { dataAsCollection.CopyTo(array, arrayIndex); } public int Count { get { return data.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(KeyValuePair<TKey, TValue> item) { bool removed = dataAsCollection.Remove(item); if (removed) { lruList.Remove(item.Key); } return removed; } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return dataAsCollection.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((System.Collections.IEnumerable)data).GetEnumerator(); } } } ```
For .NET 4.0, you can also use the `MemoryCache` from `System.Runtime.Caching`. <http://msdn.microsoft.com/en-us/library/system.runtime.caching.aspx>
Object cache for C#
[ "", "c#", ".net", "caching", "" ]
I have understanding how heap and garbage collector works: garbage collection happens in generations, memory allocation happens sequentially, during garbage collection free/unused space compacted by shifting data and forming continues block, etc. Is there any headers for allocated memory chunks are present and how big are they (I heard it’s 8-16 bytes for .NET CLR) and if byte, word or quad-word alignment present? I’m interested in any information for JIT (Java) and CLR (.NET Framework or Mono) implementation for x86 and x64 processor architectures.
I believe the header size is two words - one for the type reference and one for the sync block and other flags. The padding is (I believe) just enough to round the total size up to a whole number of words. For instance, a reference type with just an "int" in takes 12 bytes on x86, as demonstrated here: ``` using System; public class Foo { int x; public Foo(int x) { this.x = x; } } public class Test { static void Main(string[] args) { int length = int.Parse(args[0]); Foo x = new Foo(0); Foo[] array = new Foo[length]; // Make sure that JITting the string constructor doesn't // change things long start = GC.GetTotalMemory(true); for (int i=0; i < length; i++) { array[i] = new Foo(i); } long end = GC.GetTotalMemory(true); GC.KeepAlive(array); GC.KeepAlive(x); decimal totalDecimal = end-start; Console.WriteLine(totalDecimal / length); } } ``` One interesting point - for some reason an instance of System.Object takes 12 bytes (on x86) instead of the 8 that I would otherwise have predicted. It's as if the minimum size is 12 bytes, but you get the first four bytes of real data free :) I don't know why the size reported isn't exactly an integer, btw - I suspect it's something to do with a little bit of extra memory required for per page in the managed heap, or something like that. Sometimes the result is a little bit over 12, sometimes a little bit under 12 - that seems to depend on the length given. (The previous version of this answer had a bug in, where it would parse the first command line arg but then ignore it. I've fixed that.) Anyway, I don't believe this slight inaccuracy has anything to do with the size of an individual object in memory.
A complete answer to the question would actually be rather complicated: the overhead associated with object allocation depends not only on the implementation details of the particular virtual machine, but for example also on the generation that the object happens to be in (in other words, the overhead associated with a particular object can change during the lifetime of the object). There are few simple utilities that can be used to estimate the overhead for a particular object, but nothing robust (check out for example <http://java.sun.com/docs/books/performance/1st_edition/html/JPRAMFootprint.fm.html>). In Java, there is also an interface that might give you the object size including overhead, see <http://download-llnw.oracle.com/javase/6/docs/platform/jvmti/jvmti.html#GetObjectSize>.
Java and .NET heap overhead
[ "", "java", ".net", "garbage-collection", "clr", "jit", "" ]