Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've got some controls on a web page that surface configuration elements of my web application. I've wired up to their "OnChange" events, to capture value changes and so on. For each on change, I would like to say Configuration.Save(), but apart from getting "access denied" exceptions on web.config, I suspect this could be some weirdness, in trying to save to the configuration file for each control's onchange. Any suggestions for the best way to handle this?
Would you add some detail as to what type of settings you are trying to update? I really don't think you want to save changes to your web.config from the application. Does the application have a database you could tie your saves to? That seems more appropriate for a changes you would want to make regularly, and in a transaction safe manner. I still think this is better done using a database. But, if you must, then I'd check out this guide to [working with web.config](http://www.west-wind.com/WebLog/posts/8461.aspx).
From an architectural standpoint, it would be better to save the changes to the configuration file when the page is submitted. However, it is likely that the web.config file is locked when the application is started. Consequently, if you have application-specific changes that you would like to save, it is better to find a method other than web.config for saving them.
Saving web configuration elements with events on controls
[ "", "c#", "asp.net", "configuration", "" ]
I have a multi-dimensional array, no problem. How do I interrogator one of the arrays in order to ascertain if it actually holds any data? I am working with VS 2008 and what I can see in the debugger is, lets call the element x, is x{...}. However, if I try and use x.length i get the message 'undefined' - so how do I ascertain if the array has nothing in it? type(x) is returning an object. Here is the constructor code: ``` function initArray() { var length = initArray.arguments.length for (var i = 0; i < length; i++) { this[i+1] = initArray.arguments[i]; } } ``` So it should return a .length value, which it isn't! In the multilevel array, it's the third level down so x = pub[1][8] which should be the target array, but as I said if I then go x.length, or x[].length I get undefined... Thanks.
It looks like your object x is not an array at all. If it were, the length would be zero or positive integer. It sounds like you might have an object and inadvertently added expando properties. try this: ``` for(var prop in x) { var p = prop; // set a breakpoint on this line and check the value of prop } ```
Are you sure it's an array and not an object? Arrays use [] and objects use {}. The array's length should be zero upon its definition. You can check `typeof(x)` to see if it's `undefined`. This is a case where we're shooting in the dark without seeing your code.
How can I work with a multi-dimensional array in JavaScript?
[ "", "javascript", "arrays", "" ]
I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique. For example, say my input is: ``` a = dict() a['one']=1 a['two']=2 ``` I would like my output to be: ``` {1: 'one', 2: 'two'} ``` To clarify I would like my result to be the equivalent of the following: ``` res = dict() res[1] = 'one' res[2] = 'two' ``` Any neat Pythonic way to achieve this?
Python 2: ``` res = dict((v,k) for k,v in a.iteritems()) ``` Python 3 (thanks to @erik): ``` res = dict((v,k) for k,v in a.items()) ```
``` new_dict = dict(zip(my_dict.values(), my_dict.keys())) ```
How do I exchange keys with values in a dictionary?
[ "", "python", "dictionary", "mapping", "reverse", "" ]
Some APIs only support output to files. e.g. a library that converts a BMP to PNG and only has a Save(file) option - no in memory function. Disk IO is slow, though, and sometimes you just want in-memory operations. Is there a generic solution to such a problem? Maybe a fake in-memory file of sorts that would allow one to use the library, yet not pay the performance penalty of disk IO?
Use [named pipes](http://en.wikipedia.org/wiki/Named_pipe). Similar constructs exist for both [Windows](http://msdn.microsoft.com/en-us/library/aa365590%28VS.85%29.aspx)and [Unix](http://www.opengroup.org/onlinepubs/009695399/functions/mkfifo.html) (and [this](http://www.linuxjournal.com/article/2156)). But I don't believe it worth the effort setting up all those constructs. Choose an alternative library or just write to disk if you may.
You can catch file I/O APIs (using [detours](http://research.microsoft.com/en-us/projects/detours/), [N-CodeHook](http://newgre.net/ncodehook) for example), and route them to your implementation (Which will use the memory instead). Here is a [walk thought of someone who done something slimier](http://www.codingthewheel.com/archives/how-i-built-a-working-online-poker-bot-6), now I'm sure the some where there is full implementatio that will do that for you but I could not find one.
Use file-only APIs in memory
[ "", "c++", "performance", "" ]
i am trying to find a certain tag in a html-page with java. all i know is what kind of tag (div, span ...) and the id ... i dunno how it looks, how many whitespaces are where or what else is in the tag ... so i thought about using pattern matching and i have the following code: ``` // <tag[any character may be there or not]id="myid"[any character may be there or not]> String str1 = "<" + Tag + "[.*]" + "id=\"" + search + "\"[.*]>"; // <tag[any character may be there or not]id="myid"[any character may be there or not]/> String str2 = "<" + Tag + "[.*]" + "id=\"" + search + "\"[.*]/>"; Pattern p1 = Pattern.compile( str1 ); Pattern p2 = Pattern.compile( str2 ); Matcher m1 = p1.matcher( content ); Matcher m2 = p2.matcher( content ); int start = -1; int stop = -1; String Anfangsmarkierung = null; int whichMatch = -1; while( m1.find() == true || m2.find() == true ){ if( m1.find() ){ //System.out.println( " ... " + m1.group() ); start = m1.start(); //ende = m1.end(); stop = content.indexOf( "<", start ); whichMatch = 1; } else{ //System.out.println( " ... " + m2.group() ); start = m2.start(); stop = m2.end(); whichMatch = 2; } } ``` but i get an exception with m1(m2).start(), when i enter the actual tag without the [.\*] and i dun get anything when i enter the regular expression :( ... i really havent found an explanation for this ... i havent worked with pattern or match at all yet, so i am a little lost and havent found anything so far. would be awesome if anyone could explain me what i am doing wrong or how i can do it better ... thnx in advance :) ... dg
Here is an example for what you're trying to do adapted from one of my notes: ``` import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String tag = "thetag"; String id = "foo"; String content = "<tag1>\n"+ "<thetag name=\"Tag Name\" id=\"foo\">Some text</thetag>\n" + "<thetag name=\"AnotherTag\" id=\"foo\">Some more text</thetag>\n" + "</tag1>"; String patternString = "<" + tag + ".*?name=\"(.*?)\".*?id=\"" + id + "\".*?>"; System.out.println("Content:\n" + content); System.out.println("Pattern: " + patternString); Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(content); boolean found = false; while (matcher.find()) { System.out.format("I found the text \"%s\" starting at " + "index %d and ending at index %d.%n", matcher.group(), matcher.start(), matcher.end()); System.out.println("Name: " + matcher.group(1)); found = true; } if (!found) { System.out.println("No match found."); } } } ``` You'll notice that the pattern string becomes something like `<thetag.*?name="(.*?)".*?id="foo".*?>` which will search for tags named **thetag** where the **id** attribute is set to "foo". Note the following: * It uses `.*?` to weakly match zero or more of anything (if you don't understand, try removing the `?` to see what I mean). * It uses a submatch expression between parenthesis (the `name="(.*?)"` part) to extract the contents of the **name** attribute (as an example).
I know that I am broadening your question, but I think that using a dedicated library for parsing HTML documents (such as: <http://htmlparser.sourceforge.net/>) will be much more easier and accurate than regexps.
pattern match java: does not work
[ "", "java", "regex", "" ]
Just wondering if it is possible to access the Mac OS X Address Book API's from pure Java 6 code? I want to keep this completely platform independent as my program is built for Windows & Linux also (open source & free: <http://jsmsirl.sourceforge.net/>). Any help is much appreciated!
There is no way, as far as I know. Apple has a guide for accessing the address book through JNI though, which is available [here](http://developer.apple.com/java/jniuniversal.html). The sample code for MyFirstJNIProject is available [here](http://developer.apple.com/samplecode/MyFirstJNIProject/index.html). The guide also shows how to check the underlying operating system and only call the JNI code when running on Mac OS X platforms.
sqlite3 AddressBook-v22.abcddb and You have access to all data from Address Book, now some SQL statements and You're done: select \* from ZABCDCONTACTINDEX; for example HF
Is it possible to access the Mac Address book API from pure Java?
[ "", "java", "macos", "addressbook", "" ]
I'm busy introducing myself to jQuery by implementing a little system where onmouseover on an element causes a text balloon to pop up close to the element. I feel like I'm using too much vanilla JS here, so please suggest where I can improve and what is wrong with this code: ``` <head runat="server"> <script type="text/javascript" src="Scripts/jquery-1.3.2.js"></script> <script type="text/javascript"> $('document').ready(function() { $('span.balloon').each(function() { this.style.display = "none"; }); $('span.ballooned').mouseover(function(event){ if (event.currentTarget.attributes["balloonid"]) { var blnArr = $("#" + event.currentTarget.attributes["balloonid"].value); if (blnArr.length > 0) { blnArr[blnArr.length - 1].style.display = "inline"; }; }; }); }); </script> </head> <body> <div> This is some text where I describe a <span class="ballooned" balloonId="bln-1">text field</span> and want to attach extra info to that phrase. </div> <span class="balloon" id="bln-1">nvarchar(8)</span> </body> ```
``` $(function() { $("span.balloon").hide(); $("span.ballooned[balloonid]").mouseover( function() { var balloonid = "#" + $(this).attr("balloonid"); $(balloonid).css("display", "inline"); }); }); ```
First, let me say there is nothing wrong with using vanilla js, *if you're sure it isn't browser dependent*. The jQuery framework isn't intended to replace any and all javascript syntax. I think most people would say that jQuery is intended to 1) remedy a long standing issue of forcing developers to deal with a browser war we have no control over and 2) to simplify complex tasks that are regularly needed to meet the demands of the day. That said, I would recommend you use [jQuery's CSS](http://docs.jquery.com/CSS) functions to set the properties.
Critique on jQuery Use
[ "", "javascript", "jquery", "" ]
I am creating a registration form which contains two submit buttons. I need to know which button is clicked in the form in my servlet code?
Read the answers to [this question](https://stackoverflow.com/questions/5222/accessing-post-variables-using-java-servlets). So, in ``` String button1 = request.getParameter("button1"); String button2 = request.getParameter("button2"); ``` the value which isn't null is the pressed button. Or, if you want to use the same name for the two buttons you can set a different value ``` <input type="submit" name="act" value="delete"/> <input type="submit" name="act" value="update"/> ``` Then ``` String act = request.getParameter("act"); if (act == null) { //no button has been selected } else if (act.equals("delete")) { //delete button was pressed } else if (act.equals("update")) { //update button was pressed } else { //someone has altered the HTML and sent a different value! } ```
Only the clicked button will be a successful control. ``` <input type="submit" name="action" value="Something"> <input type="submit" name="action" value="Something Else"> ``` Then, server side, check the value of the action data.
How to find out which HTML button was pushed in my servlet?
[ "", "java", "html", "jsp", "button", "" ]
I've been developing with PHP for some years now, and recently came across this code: ``` <?php echo <<<EOB <html> <head> <title>My title</title> </head> ... EOB; ?> ``` I've never seen this approach to print HTML, which seems to be pretty useful and less prone to some weird variable or double quote syntax error. I've searched for some official information about this and only found a post of Rasmus talking about this. What is a detailed explanation about this functionality and what does EOB mean? Maybe *end of block*?
This is known as [heredoc](http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc) syntax. The documentation will tell you everything you need to know. Essentially, however: > A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. > > The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore. So `EOB` is just what the author chose as his delimiter, not really sure what it stands for in his case but the identifier can be whatever you want.
Just for the sake of completeness, Heredoc in PHP is inherited from [Perl](http://en.wikipedia.org/wiki/Perl), which itself inherited it from the [Bourne shell](https://en.wikipedia.org/wiki/Bourne_shell).
PHP expression <<<EOB
[ "", "php", "html", "heredoc", "" ]
I was testing something I read earlier about how random `Math.random()` really is, and wanted to display 10000 numbers that was supposed to be a random number between 0 and 10000000. To see the test, I chose to just join the array of random numbers to a string with `<br>` between each integer. And then I just did `$("#"+elm).html(randomNumberString);` which was really slow. I just figured it was the generation and sorting of random numbers into an array. But as I started placing timers in my code, it got appearant that it was the output that was slowing everything down. Just as a test I did `document.getElementById(elm).innerHTML = randomNumberString;` jQuery.html(): 2500ms getElementById.innerHTML: 170ms I tried this across all 5 browsers, and the numbers were very close in all browsers... Am I using jQuery wrong in this instance? I also tried append and fetching the element before the timer started, so I could simply do `$(elm).html()`, but that didn't help. It seems to be the actual `html()` function that's slowing everything down..? **EDIT** I ended up doing this: ``` randomStringNumber = "<div>" + randomStringNumber + "</div>"; ``` and now the whole thing runs a lot faster: jQuery.html(): 120ms getElementById.innerHTML: 80ms Still faster using oldschool html, though. And if anyone has an answer to why wrapping it in one element is faster, I'd appreciate that...
25 tip to improve your jquery use <http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx> <http://acsenthil.wordpress.com/2011/07/04/improve-your-jquery-25-excellent-tips/> 1. Load the framework from Google Code 2. Use a cheat sheet 3. Combine all your scripts and minify them 4. Use Firebug’s excellent console logging facilities 5. Keep selection operations to a minimum by caching 6. Keep DOM manipulation to a minimum 7. Wrap everything in a single element when doing any kind of DOM insertion 8. Use IDs instead of classes wherever possible 9. Give your selectors a context 10. Use chaining properly 11. Learn to use animate properly 12. Learn about event delegation 13. Use classes to store state 14. Even better, use jQuery’s internal data() method to store state 15. Write your own selectors 16. Streamline your HTML and modify it once the page has loaded 17. Lazy load content for speed and SEO benefits 18. Use jQuery’s utility functions 19. Use noconflict to rename the jquery object when using other frameworks 20. How to tell when images have loaded 21. Always use the latest version 22. How to check if an element exists 23. Add a JS class to your HTML attribute 24. Return ‘false’ to prevent default behaviour 25. Shorthand for the ready event
The fastest way is this: ``` $.getJSON("/Admin/GetFolderList/", function(result) { var optionsValues = '<select>'; $.each(result, function(item) { optionsValues += '<option value="' + item.ImageFolderID + '">' + item.Name + '</option>'; }); optionsValues += '</select>'; var options = $('#options'); options.replaceWith(optionsValues); }); ``` According to [this link](http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip7) is the fastest way because you wrap everything in a single element when doing any kind of DOM insertion.
jQuery html() acting really slow
[ "", "javascript", "jquery", "performance", "" ]
I have a windows forms app where I have split different functionality into several user controls. I want each of these user controls to have an accept button. Any best practices here? My idèa is to detect which user control that has focus, and than set it in the parent Form. Any other idèas?
Jan Miksovsky has an excellent blog on UI design, and wrote [an article about this very thing](http://miksovsky.blogs.com/flowstate/2006/01/speed_tasks_wit.html). > Most UI platforms allow a designer to > indicate which button in a dialog > should be the default button: the > button that will be pressed if the > user types the Enter key. The default > button is generally the button the > user is most likely to press next, > often a button like OK that closes the > dialog. In very high-traffic dialogs, > you may want to consider dynamically > changing the default button to save > keystrokes and help speed the user's > task. The example he uses is the "Select Names" dialog in Microsoft Outlook, which changes the default button depending on what you are doing.
The best practice is usually to only have one accept button for your form so that its behavior is consistent. It generally would be confusing for users if hitting return caused different actions depending on which section of the form had focus. However, if you have a specialized application or users have requested this feature then I think the solution you propose would work.
.NET UserControl accept button best practice?
[ "", "c#", ".net", "winforms", "user-controls", "acceptbutton", "" ]
Suppose that I define some class: ``` class Pixel { public: Pixel(){ x=0; y=0;}; int x; int y; } ``` Then write some code using it. Why would I do the following? ``` Pixel p; p.x = 2; p.y = 5; ``` Coming from a Java world I always write: ``` Pixel* p = new Pixel(); p->x = 2; p->y = 5; ``` They basically do the same thing, right? One is on the stack while the other is on the heap, so I'll have to delete it later on. Is there any fundamental difference between the two? Why should I prefer one over the other?
Yes, one is on the stack, the other on the heap. There are two important differences: * First, the obvious, and less important one: Heap allocations are slow. Stack allocations are fast. * Second, and much more important is [RAII](http://en.wikipedia.org/wiki/RAII). Because the stack-allocated version is automatically cleaned up, it is *useful*. Its destructor is automatically called, which allows you to guarantee that any resources allocated by the class get cleaned up. This is essentialy how you avoid memory leaks in C++. You avoid them by never calling `delete` yourself, instead wrapping it in stack-allocated objects which call `delete` internally, typicaly in their destructor. If you attempt to manually keep track of all allocations, and call `delete` at the right times, I guarantee you that you'll have at least a memory leak per 100 lines of code. As a small example, consider this code: ``` class Pixel { public: Pixel(){ x=0; y=0;}; int x; int y; }; void foo() { Pixel* p = new Pixel(); p->x = 2; p->y = 5; bar(); delete p; } ``` Pretty innocent code, right? We create a pixel, then we call some unrelated function, and then we delete the pixel. Is there a memory leak? And the answer is "possibly". What happens if `bar` throws an exception? `delete` never gets called, the pixel is never deleted, and we leak memory. Now consider this: ``` void foo() { Pixel p; p.x = 2; p.y = 5; bar(); } ``` This won't leak memory. Of course in this simple case, everything is on the stack, so it gets cleaned up automatically, but even if the `Pixel` class had made a dynamic allocation internally, that wouldn't leak either. The `Pixel` class would simply be given a destructor that deletes it, and this destructor would be called no matter how we leave the `foo` function. Even if we leave it because `bar` threw an exception. The following, slightly contrived example shows this: ``` class Pixel { public: Pixel(){ x=new int(0); y=new int(0);}; int* x; int* y; ~Pixel() { delete x; delete y; } }; void foo() { Pixel p; *p.x = 2; *p.y = 5; bar(); } ``` The Pixel class now internally allocates some heap memory, but its destructor takes care of cleaning it up, so when *using* the class, we don't have to worry about it. (I should probably mention that the last example here is simplified a lot, in order to show the general principle. If we were to actually use this class, it contains several possible errors too. If the allocation of y fails, x never gets freed, and if the Pixel gets copied, we end up with both instances trying to delete the same data. So take the final example here with a grain of salt. Real-world code is a bit trickier, but it shows the general idea) Of course the same technique can be extended to other resources than memory allocations. For example it can be used to guarantee that files or database connections are closed after use, or that synchronization locks for your threading code are released.
They are not the same until you add the delete. Your example is overly trivial, but the destructor may actually contain code that does some real work. This is referred to as RAII. So add the delete. Make sure it happens even when exceptions are propagating. ``` Pixel* p = NULL; // Must do this. Otherwise new may throw and then // you would be attempting to delete an invalid pointer. try { p = new Pixel(); p->x = 2; p->y = 5; // Do Work delete p; } catch(...) { delete p; throw; } ``` If you had picked something more interesting like a file (which is a resource that needs to be closed). Then do it correctly in Java with pointers you need to do this. ``` File file; try { file = new File("Plop"); // Do work with file. } finally { try { file.close(); // Make sure the file handle is closed. // Oherwise the resource will be leaked until // eventual Garbage collection. } catch(Exception e) {};// Need the extra try catch to catch and discard // Irrelevant exceptions. // Note it is bad practice to allow exceptions to escape a finally block. // If they do and there is already an exception propagating you loose the // the original exception, which probably has more relevant information // about the problem. } ``` The same code in C++ ``` std::fstream file("Plop"); // Do work with file. // Destructor automatically closes file and discards irrelevant exceptions. ``` Though people mention the speed (because of finding/allocating memory on the heap). Personally this is not a deciding factor for me (the allocators are very quick and have been optimized for C++ usage of small objects that are constantly created/destroyed). The main reason for me is object life time. A locally defined object has a very specific and well defined lifetime and the the destructor is guaranteed to be called at the end (and thus can have specific side effects). A pointer on the other hand controls a resource with a dynamic life span. ### The main difference between C++ and Java is: The concept of who owns the pointer. It is the responsibility of the owner to delete the object at the appropriate time. This is why you very rarely see *raw* pointers like that in real programs (as there is no ownership information associated with a *raw* pointer). Instead pointers are usually wrapped in smart pointers. The smart pointer defines the semantics of who owns the memory and thus who is responsible for cleaning it up. Examples are: ``` std::auto_ptr<Pixel> p(new Pixel); // An auto_ptr has move semantics. // When you pass an auto_ptr to a method you are saying here take this. You own it. // Delete it when you are finished. If the receiver takes ownership it usually saves // it in another auto_ptr and the destructor does the actual dirty work of the delete. // If the receiver does not take ownership it is usually deleted. std::tr1::shared_ptr<Pixel> p(new Pixel); // aka boost::shared_ptr // A shared ptr has shared ownership. // This means it can have multiple owners each using the object simultaneously. // As each owner finished with it the shared_ptr decrements the ref count and // when it reaches zero the objects is destroyed. boost::scoped_ptr<Pixel> p(new Pixel); // Makes it act like a normal stack variable. // Ownership is not transferable. ``` There are others.
Why not use pointers for everything in C++?
[ "", "c++", "pointers", "heap-memory", "stack-memory", "" ]
Is there any reasons why PHP's json\_encode function does not escape all [JSON](http://www.json.org/) control characters in a string? For example let's take a string which spans two rows and has control characters (\r \n " / \) in it: ``` <?php $s = <<<END First row. Second row w/ "double quotes" and backslash: \. END; $s = json_encode($s); echo $s; // Will output: "First row.\r\nSecond row w\/ \"double quotes\" and backslash: \\." ?> ``` Note that carriage return and newline chars are unescaped. Why? I'm using jQuery as my JS library and it's $.getJSON() function will do fine when you fully, 100% trust incoming data. Otherwise I use JSON.org's library json2.js like everybody else. But if you try to parse that encoded string it throws an error: ``` <script type="text/javascript"> JSON.parse(<?php echo $s ?>); // Will throw SyntaxError </script> ``` And you can't get the data! If you remove or escape \r \n " and \ in that string then JSON.parse() will not throw error. Is there any existing, good PHP function for escaping control characters. Simple str\_replace with search and replace arrays will not work.
D'oh - you need to double-encode: JSON.parse is expecting a string of course: ``` <script type="text/javascript"> JSON.parse(<?php echo json_encode($s) ?>); </script> ```
``` function escapeJsonString($value) { # list from www.json.org: (\b backspace, \f formfeed) $escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c"); $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b"); $result = str_replace($escapers, $replacements, $value); return $result; } ``` I'm using the above function which escapes a backslash (must be first in the arrays) and should deal with formfeeds and backspaces (I don't think `\f` and `\b` are supported in PHP).
PHP's json_encode does not escape all JSON control characters
[ "", "php", "json", "" ]
I am using the subprocess package in Python to run a subprocess, which I later need to kill. However, the documentation of the subprocess package states that the terminate() function is only available from 2.6 We are running Linux with 2.5 and for backwards compatibility reasons I cannot upgrade to 2.6, what is the alternative? I am guessing that these functions are convenience methods for something.
You call os.kill on the process pid. ``` os.kill(process.pid, signal.SIGKILL) ``` You're OK because you're on on Linux. Windows users are out of luck.
To complete @Gareth's answer, on Windows you do: ``` import ctypes PROCESS_TERMINATE = 1 handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, theprocess.pid) ctypes.windll.kernel32.TerminateProcess(handle, -1) ctypes.windll.kernel32.CloseHandle(handle) ``` not quite as elegant as `os.kill(theprocess.pid, 9)`, but it does work;-)
In Python 2.5, how do I kill a subprocess?
[ "", "python", "subprocess", "" ]
I have an expensive query using the row\_number over() functionality in SQL Server 2005. I return only a sub list of those records as the query is paginated. However, I would like to also return the total number of records, not just the paginated subset. Running the query effectively twice to get the count is out of the question. Selecting count(\*) is also out of the question as the performance is absolutely terrible when I've tried this. What I'd really love is @@ROW\_NUMBERROWCOUNT :-)
Check out the COUNT(\*) aggregate when used with OVER(PARTITON BY..), like so: ``` SELECT ROW_NUMBER() OVER(ORDER BY object_id, column_id) as RowNum , COUNT(*) OVER(PARTITION BY 1) as TotalRows , * FROM master.sys.columns ``` This is IMHO the best way to do it without having to do two queries.
Over the years a pile of developer sweat has gone into efficiently paging result sets. Yet, there is no one answer--it depends on your use case. Part of the use case is getting your page efficiently, part is figuring out how many rows are in a complete result set. So sorry if i stray a little into paging, but the two are pretty tightly coupled in my mind. There are a lot of strategies, most of which are bad if you have any sort of data volume & don't fit the use case. While this isn't a complete list, following are some of the options..... ## Run Separate `Count(*)` * run a separate query that does a simple "select count(\*) from MyTable" * simple and easy for a small table * good on an unfiltered large table that is either narrow or has a compact non-clustered index you can use * breaks down when you have a complicated `WHERE/JOIN` criteria because running the `WHERE/JOIN` twice is expensive. * breaks down on a wide index because the number of reads goes up. ## Combine `ROW_Number() OVER()` and `COUNT(1) OVER(PARTITION By 1)` * This was suggested by @RBarryYoung. It has the benefit of being simple to implement and very flexible. * The down side is that there are a lot of reasons this can become extremely expensive quickly. * For example, in a DB i'm currently working there is a Media table with about 6000 rows. It's not particularly wide, has a integer clustered PK and, as well as a compact unique index. Yet, a simple `COUNT(*) OVER(PARTITION BY 1) as TotalRows` results in ~12,000 reads. Compare that to a simple `SELECT COUNT(*) FROM Media` -- 12 reads. Wowzers. > UPDATE -- the reads issue I mentioned is a bit of red-herring. It turns out, that with windowed functions the unit used to measure reads is kind of mixed. The net result is what appears to be massive numbers of reads. You can see more on the issue here : [Why are logical reads for windowed aggregate functions so high?](https://stackoverflow.com/questions/4230838/why-are-logical-reads-for-windowed-aggregate-functions-so-high) ## Temp Tables / Table Variables * There are lots of strategies that take a result set and insert relevant keys or segments of results into temp tables / table variables. * For small/medium sized result sets this can provide great results. * This type of strategy works across almost any platform/version of SQL. * Operating on a result set multiple times (quite often a requirement) is also easy. * The down side is when working with large results sets ... inserting a few million rows into a temp table has a cost. * Compounding the issue, in a high volume system pressure on TempDB can be quite a factor, and temp tables are effectively working in TempDB. ## Gaussian Sum / Double Row Number * This idea relies on *subset* of something the mathematician Gauss figured out (how to sum a series of numbers). The subset is how to get row count from any point in the table. * From a series of numbers (`Row_Number()`) the row count for 1 to N is `(N + 1) - 1`. More explanation in the links. * The formula seems like it would net out to just N, but the if you stick with the formula an interesting things happens, you can figure out row count from a page in the middle of the table. * The net result is you do `ROW_Number() OVER(Order by ID)` and `ROW_Number() OVER(Order by ID DESC)` then sum the two numbers and subtract 1. * Using my Media table as an example my reads dropped from 12,000 to about 75. * In a larger page you've ended up repeating data many many times, but the offset in reads may be worth it. * I haven't tested this on too many scenarios, so it may fall apart in other scenarios. ## Top (@n) / SET ROWCOUNT * These aren't specific strategies per-se, but are optimizations based on what we know about the query optimizer. * Creatively using Top(@n) [top can be a variable in SQL 2008] or SET ROWCOUNT can reduce your working set ...even if you're pulling a middle page of a result set you can still narrow the result * These ideas work because of query optimizer behavior ...a service pack/hotfix can change the behavior (although probably not). * In certian instances SET ROWCOUNT can be a bit in accurate * This strategy doesn't account for getting the full row count, just makes paging more efficient ## So what's a developer to do? Read my good man, read. Here are some articles that I've leaned on... * [A More Efficient Method for Paging Through Large Result Sets](https://web.archive.org/web/20211020131201/https://www.4guysfromrolla.com/webtech/042606-1.shtml) * [Optimising Server-Side Paging - Part I](http://www.sqlservercentral.com/articles/paging/69892/) * [Optimising Server-Side Paging - Part II](http://www.sqlservercentral.com/articles/paging/70120/) * [Explaination of the Gaussian Sum](http://mathcentral.uregina.ca/QQ/database/QQ.02.06/jo1.html) * [Returning Ranked Results with Microsoft SQL Server 2005](https://web.archive.org/web/20210512232142/http://www.4guysfromrolla.com/webtech/010406-1.shtml) * [ROW\_NUMBER() OVER Not Fast Enough With Large Result Set](http://weblogs.asp.net/eporter/archive/2006/10/17/ROW_5F00_NUMBER_28002900_-OVER-Not-Fast-Enough-With-Large-Result-Set.aspx) * [Retrieving the First N Records from a SQL Query](https://web.archive.org/web/20210417081325/http://www.4guysfromrolla.com/webtech/070605-1.shtml) * [Server Side Paging using SQL Server 2005](http://www.sqlteam.com/article/server-side-paging-using-sql-server-2005) * [Why are logical reads for windowed aggregate functions so high?](https://stackoverflow.com/questions/4230838/why-are-logical-reads-for-windowed-aggregate-functions-so-high) Hope that helps.
Efficient way of getting @@rowcount from a query using row_number
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "" ]
In the code below, why it is that when I take the address of a map index (which contains a list) and I take the address of the list itself, they both have different values. See the code below for clarification. ``` #include <iostream> #include <list> #include <map> using namespace std; int main() { list<char> listA; //list of chars map<int,list<char> > mapper; //int to char map mapper[1] = listA; cout << &(mapper[1]) << endl; cout << &listA << endl; } ```
You get different addresses because you create a copy of the original list and assing it to the map structure. Consider using pointers (`map< int, list<char>* >`).
This line will add a *copy* of the value of the local `listA` and add it to the map at index 1. You now have two different lists. ``` mapper[1] = listA; ```
Different address with map indexes vs content of map index
[ "", "c++", "stl", "dictionary", "" ]
I have a list/collection of objects that may or may not have the same property values. What's the easiest way to get a distinct list of the objects with equal properties? Is one collection type best suited for this purpose? For example, in C# I could do something like the following with LINQ. ``` var recipients = (from recipient in recipientList select recipient).Distinct(); ``` My initial thought was to use lambdaj ([link text](http://code.google.com/p/lambdaj/ "lamdbaj")), but it doesn't appear to support this.
Use an implementation of the interface `Set<T>` (class T may need a custom `.equals()` method, and you may have to implement that `.equals()` yourself). Typically a `HashSet` does it out of the box : it uses `Object.hashCode()` and `Object.equals()` method to compare objects. That should be unique enough for simple objects. If not, you'll have to implement `T.equals()` and `T.hashCode()` accordingly. See Gaurav Saini's comment below for libraries helping to implement equals and hashcode.
``` return new ArrayList(new HashSet(recipients)); ```
Java - Distinct List of Objects
[ "", "java", "list", "collections", "" ]
How do you Make A Repeat-Until Loop in C++? As opposed to a standard While or For loop. I need to check the condition at the end of each iteration, rather than at the beginning.
``` do { // whatever } while ( !condition ); ```
When you want to check the condition at the beginning of the loop, simply negate the condition on a standard `while` loop: ``` while(!cond) { ... } ``` If you need it at the end, use a `do` ... `while` loop and negate the condition: ``` do { ... } while(!cond); ```
How do you Make A Repeat-Until Loop in C++?
[ "", "c++", "loops", "for-loop", "while-loop", "" ]
I'd like to store some data in Python in a similar form to a dictionary: `{1:'a', 2:'b'}`. Every value will be unique, not just among other values, but among keys too. Is there a simple data structure that I can use to get the corresponding object no matter if I ask using the 'key' or the 'value'? For example: ``` >>> a = {1:'a', 2:'b'} >>> a[1] 'a' >>> a['b'] 2 >>> a[3] KeyError ``` The 'keys' are standard python ints, an the values are short (<256char) strings. My current solution is creating a reversed dictionary and searching it if I can't find a result in the original dictionary: ``` pointsreversed = dict((v, k) for k, v in points.iteritems()) def lookup(key): return points.get(key) or pointsreversed.key() ``` This uses twice as much space, which isn't great (my dictionaries can be up to a few hundred megs) and is 50% slower on average. EDIT: as mentioned in a few answers, two dicts doesn't double memory usage, as it's only the dictionary, not the items within, that is duplication. Is there a solution that improves on this?
Related posts: [Python mapping inverse](https://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/483833) [Python 1:1 mappings](https://stackoverflow.com/questions/863935/a-data-structure-for-11-mappings-in-python) Of course, if all values and keys are unique, couldn't you just use a single dictionary, and insert both key:value and value:key initially?
If your keys and values are non-overlapping, one obvious approach is to simply store them in the same dict. ie: ``` class BidirectionalDict(dict): def __setitem__(self, key, val): dict.__setitem__(self, key, val) dict.__setitem__(self, val, key) def __delitem__(self, key): dict.__delitem__(self, self[key]) dict.__delitem__(self, key) d = BidirectionalDict() d['foo'] = 4 print d[4] # Prints 'foo' ``` (You'll also probably want to implement things like the `__init__`, `update` and `iter*` methods to act like a real dict, depending on how much functionality you need). This should only involve one lookup, though may not save you much in memory (you still have twice the number of dict entries after all). Note however that neither this nor your original will use up twice as much space: the dict only takes up space for the references (effectively pointers), plus an overallocation overhead. The space taken up by your data itself will not be repeated twice since the same objects are pointed to.
Reversible dictionary for python
[ "", "python", "dictionary", "hashtable", "" ]
I don't know if I'm thinking of this the right way, and perhaps somebody will set me straight. Let's say I have a models.py that contains this: ``` class Order(models.Model): customer = models.foreignKey(Customer) total = models.charField(max_length=10) has_shipped = models.booleanField() class Product(models.Model): sku = models.charField(max_length=30) price = models.charField(max_length=10) ``` Now, obviously an order would contain products and not just a product. What would be the best way to add products to an order? The only way I can think is to add another field to 'Order' called 'products', and fill it with a CSV with a sku for each product in it. This, for obvious reasons is not ideal, but I'm not very good at this stuff yet and have no idea of what the better way is. (keep in mind this is pseudo code, so don't mind misspellings, etc.)
What you're after is a many to many relationship between product and order. Something like: ``` class Order(models.Model): customer = models.foreignKey(Customer) total = models.charField(max_length=10) has_shipped = models.booleanField() products = models.ManyToManyField(Product) ``` see the docs [here](http://www.djangoproject.com/documentation/models/many_to_many/) and [here](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField).
You can create one more model which will serve as many-to-many relationship between Order and Products something like this ``` class OrderProducts(models.Model) product = models.ForeignKey(Product) order = models.ForeignKey(Order) ```
How do I store multiple values in a single attribute
[ "", "python", "django", "e-commerce", "" ]
Have you ever created or encountered a [self modifying code](http://en.wikipedia.org/wiki/Self-modifying_code) in Java? If yes, then please post the link or simply post the code.
Ignoring the world of grief you could be causing yourself via self-modifying code(!), it seems to me there are 3 options: 1. use the inbuilt compiler support of Java 6 and write/recompile/reload classes 2. use the Apache [BCEL](http://jakarta.apache.org/bcel/index.html) bytecode manipulation library to write your class directly 3. make use of Java 6's inbuilt scripting support (or use Apache [BSF](http://jakarta.apache.org/bsf/)) to write methods in your JVM scripting language of choice, and execute these Of the three above, my initial choice (in the absence of requirements) would be to take a look at option 3. I suspect it's the least painful way to start. I've used all of the above - unfortunately I can't post links to client code.
You can write (Java) code that generates new classes (byte code) at runtime using a library like [bcel](http://jakarta.apache.org/bcel/). That's not quite the same as self-modifying code. I suspect self-modifying code is not something the [JVM](http://de.wikipedia.org/wiki/Java_Virtual_Machine) supports. For an example of generating new code at runtime, have a look at the source code of [clojure](http://clojure.org).
Self modifying code in Java
[ "", "java", "self-modifying", "" ]
I am about to move servers and i was talking to somebody and they suggested using sql server express 2008 installed on the servers. I have full access to the server. Does this express engine work at the same speed (performance) as a true sql server 2008? I know about the limitations i..e max 4 GB per DB ... and max 1 GB of ram... Considering the server has 2GB installed and is shared with windows... i don't see this being a problem but would love to hear some feedback.. I have around 4 dbs .. and they have maybe 4 users logged into them at the same time, its not a great deal of use really... What i really trying to mesure up is if i should installed SQL SERVER 2008 FULL version on the server or express.. Any help with a choice would be really helpful. It appears express uses the same DB engine as the FULL version ... I don't need any clever replication, clustering or things like that... But i want to go down the right path ... Any help really appreciated
Express is the same code as the other SQL editions (Workgroup, Standard, Enterprise/Developer and Data Center). The only different code base is the 'CE' edition, that is based on the mobile SQL CE code. Express has the restrictions you already enumerated (DB size, RAM) and also is using only one scheduler, so in effect will use only one CPU core. Also certain features are restricted in Express, like certain replication scenarios. The biggest advantage is that customers can start with Express and if they out-grow its capabilities they can swap in a higher edition without any application change, the database files are interchangeable between all editions, including Express.
Its the same engine, but I found you have to fight it all the way in making it anything but a desktop-environment database, from management to tcpip configuration, etc. And of course, it has built in limits on database size and resource usage. Once it is configured the way you want though, it runs fine. In real production settings I find the lack of SSIS quite the killer, though. So the bottom line is that it is usable, but not great. You might also consider the Workgroup edition, which is reasonably priced and less limited, but of course it is more expensive than free.
SQL Server 2008 express performance in production environment?
[ "", "sql", "sql-server", "performance", "sql-server-2008", "sql-server-2008-express", "" ]
Suppose I have a string like this: ``` one two three "four five six" seven eight ``` and I want to convert it to this: ``` one,two,three,"four five six",seven,eight ``` What's the easiest way to do this in C#?
Here's a more reusable function that I came up with: ``` private string ReplaceWithExceptions(string source, char charToReplace, char replacementChar, char exceptionChar) { bool ignoreReplacementChar = false; char[] sourceArray = source.ToCharArray(); for (int i = 0; i < sourceArray.Length; i++) { if (sourceArray[i] == exceptionChar) { ignoreReplacementChar = !ignoreReplacementChar; } else { if (!ignoreReplacementChar) { if (sourceArray[i] == charToReplace) { sourceArray[i] = replacementChar; } } } } return new string(sourceArray); } ``` Usage: ``` string test = "one two three \"four five six\" seven eight"; System.Diagnostics.Debug.WriteLine(ReplaceWithExceptions(test, char.Parse(" "), char.Parse(","), char.Parse("\""))); ```
Assuming that quotes are inescapable you can do the following. ``` public string SpaceToComma(string input) { var builder = new System.Text.StringBuilder(); var inQuotes = false; foreach ( var cur in input ) { switch ( cur ) { case ' ': builder.Append(inQuotes ? cur : ','); break; case '"': inQuotes = !inQuotes; builder.Append(cur); break; default: builder.Append(cur); break; } } return builder.ToString(); } ```
How do I convert spaces, except for those within quotes, to commas in C#?
[ "", "c#", "string", "" ]
I have two queries in Access. Both of them are moderately nasty to create, but at the end of the process they do have the same number of fields with the same data types. They both work independently, producing the expected results. Unfortunately, ``` SELECT * FROM [qry vaBaseQuery-S2] UNION ALL SELECT * FROM [qry BaseQuery]; ``` throws two 'Invalid use of null' errors, one after the other. I've used union on Access 2000 queries with null values before without issue, so I'm a bit stumped. Can anyone suggest what might be happening here? Further information that might be relevant: * Neither query has any blank rows in it * UNION SELECT \* (without the ALL) throws the same error but only once?! Edit: * Using the field names instead of \* doesn't help Edit2: * Given the query was going to be a make table query run from a form anyway, I just left it as two separate queries (one make table and one append) and trigger the two in sequence. Given the answers below, that sounds much less effort than trying to actually work out what Access is objecting too.
As mentioned in edited question: Given the query was going to be a make table query run from a form anyway, I just left it as two separate queries (one make table and one append) and trigger the two in sequence.
Arvo wrote: "sometimes [ACE/Jet] evaluates conditional parts in very weird order" -- I can vouch for that and not just when using UNION. Here's something I posted recently on SO where merely adding a WHERE clause to a query resulted in the engine evaluating in the wrong order causing an 'Invalid procedure call' error and I could not find a way round it. [SQL for parsing multi-line data?](https://stackoverflow.com/questions/915814/sql-for-parsing-multi-line-data/939611#939611) I suggest you post the SQL code from the two Query objects. Perhaps someone can spot something the engine may have problems with.
Union query throwing 'Invalid use of null' exception
[ "", "sql", "ms-access", "union", "" ]
This is an extension of a question I previously asked [here](https://stackoverflow.com/questions/1087794/c-load-a-dll-file-and-access-methods-from-class-within). Long story short, I dynamically load a DLL and make a `type` out of it with the following code: ``` Assembly assembly = Assembly.LoadFile("C:\\test.dll"); Type type = assembly.GetType("test.dllTest"); Activator.CreateInstance(type); ``` From there I can use `type` to reference virtually anything in the `dllTest` class. The class by default when ran should bring up a form (in this case, fairly blank, so it's not complex). I feel like I'm missing a key line of code here that's keeping the form from loading on the screen. `dllTest.cs` (within the DLL) consists of: ``` namespace test { public partial class dllTest : Form { public dllTest() { InitializeComponent(); } } } ``` `InitializeComponent()` sets up the layout of the form, which is far too long to paste here and shouldn't make a difference. Any ideas?
You have to do something with the form you've just created: ``` Assembly assembly = Assembly.LoadFile("C:\\test.dll"); Type type = assembly.GetType("test.dllTest"); Form form = (Form)Activator.CreateInstance(type); form.ShowDialog(); // Or Application.Run(form) ```
Yes, you aren't actually specifying any code to run outside the class initializer. For instance, with forms you have to actually show them. You could modify your code to the following... ``` Assembly assembly = Assembly.LoadFile("C:\\test.dll"); Type type = assembly.GetType("test.dllTest"); Form form = Activator.CreateInstance(type) as Form; form.ShowDialog(); ```
Displaying a form from a dynamically loaded DLL
[ "", "c#", "dll", "forms", "" ]
do you have any good suggestions how to backup remote php site and mysql, and upload it to another remote ftp? I do have shell access and it is linux system. Kind of lame question when I post it like that, but I assume some script would have to be run on remote server with site, that would do this. If you don't mind sharing your ideas, I would appreciate it. Best, Zeljko
Depends on the capabilities of your shell and the size of your site, but the first step could be very trivial: Use mysqldump and zip it together with your webpage. For uploading your archive you can maybe use [wput](http://freshmeat.net/projects/wput/) or simply fall back to [ftp](http://www.inlumineconsulting.com:8080/website/scripting.ftp.html) which should be available on most shells.
Use [mysqldump](http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html "mysqldump") do dump the DB into a "data" directory within the site. An alternative would be SELECT INTO OUTFILE if you already have the SQL scheme stored somewhere. Use tar to pack up the website contents. ``` tar -xvf site.tar ``` Use FTP, SCP, SFTP, etc to transfer that to the new location, unpack, then depending on how the DB was dumped restore the DB and give it a whirl.
Suggestions for backing up php site and mysql db
[ "", "php", "mysql", "backup", "" ]
I have a simple application in which I need to let the user select a shader (.fx HLSL or assembly file, possibly with multiple passes, but all and only pixel shader) and preview it. The application runs, the list of shaders comes up, and a button launches the "preview window." From this preview window (which has a DirectX viewport in it), the user selects an image and the shader is run on that image and displayed. Only one frame needs rendered (not real-time). I have a vertex/pixel shader combination set up that takes a quad and renders it to the screen, textured with the chosen image. This works perfectly. I need to then run another effect, purely pixel shader, on the output from the first effect, and display the final image (post-processed) to the screen. This doesn't work at all. I've tried for the past few days to get it working, but for no apparent reason, the identical code blocks used to render each effect only render the first. I can add the second shader file as a second pass in the first shader file and it runs perfectly (although completely defeats my goal of previewing user-created shaders). When I try to use a second effect (which loads and compiles just fine), it does nothing. I've taken the results of the first shader (with GetRenderTargetData) and placed them in a texture & surface (destTex and destSur), then set that texture as the input for the second pass (using dev->SetTexture and later effect->SetTexture("thisframe", destTex)). All calls succeed, effects compile, textures load, quads are drawn, but the effect is not visible. I suspected at first the device (created with software vertex processing) was causing the issue, but that doesn't seem to be the case (I tried with hardware and mixed). Additionally, using both a HAL and REF device (not a problem, since the app isn't realtime anyways), that second shader isn't visible. Everything is written in C++ for Direct3D 9.
Try clearing the depth-stencil buffer after each time you render the quad.
First Create a texture, then render the first shader directly into that texture. Finally render the second shader with the texture as input to the Backbuffer.
DirectX post-processing shader
[ "", "c++", "directx", "shader", "" ]
I don't want to use styles from style.css, so I decided to remove style.css from DOM. This work just fine in Firefox and IE8, but not in IE6: ``` $("LINK[href='http://www.example.com/style.css']").remove(); ``` Any other solution, with jQuery? --- Here is example: HTML: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Testing</title> <script type="text/javascript" src="path/to/jquery.js"></script> <script type="text/javascript"> $(document).ready(function() { $("link[href*='style.css']").remove(); }); </script> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <div id="content">...</div> </body> </html> ``` And here is CSS (style.css): ``` #content { background-color:#333; } ``` Only in IE #content is still dark. :( Maybe is jQuery bug?
**This is not a bug in jQuery, it is a bug (or possibly, a feature) of the IE rendering engine.** It seems this problem is being caused by the fact that Internet Explorer does not correctly re-render the page after removing the LINK element from the DOM. In this particular case, the LINK tag is no longer present at the DOM, but IE still displays the CSS that has been loaded into memory. **A workaround / solution for this is to disable the stylesheet using the `.disabled` property like this:** ``` // following code will disable the first stylesheet // the actual DOM-reference to the element will not be removed; // this is particularly useful since this allows you to enable it // again at a later stage if you'd want to. document.styleSheets[0].disabled = true; ``` **EDIT in reply to your comment:** Or, if you want to remove it by the href use the following code: ``` var styleSheets = document.styleSheets; var href = 'http://yoursite.com/foo/bar/baz.css'; for (var i = 0; i < styleSheets.length; i++) { if (styleSheets[i].href == href) { styleSheets[i].disabled = true; break; } } ```
Perhaps it's something strange IE6 does to URL in the `href` attribute? Try something like: ``` $("LINK[href*='style.css']").remove(); ``` (i.e. check whether the `href` value *contains* "style.css") It's just a guess, however. If that doesn't work, I recommend checking the JQuery documentation closely on the subject of attribute selectors and the `remove` method. Also keep in mind that it's also not impossible that it's in fact a bug. (IE6 in general causes lots of issues involving JavaScript and DOM manipulation, among other things.)
Removing <link> element with jQuery?
[ "", "javascript", "jquery", "css", "dom", "" ]
I'm not sure if ``` return *this ``` is the only way we could return an instance of a class who called a member function? The reason why I asked is because our instructor told us to avoid using pointers if necessary and I'm wondering if this is a case where the only necessary way to do it is by returning the this pointer. I'm working with a fraction class that holds private data members numerator and denominator. The member function I'm talking about is used to add two fractions for example: ``` Fraction C = A.plus(B); ``` plus member function is defined as this: ``` Fraction& plus( const Fraction frac ) ``` The instructor wants us to do C = A += B , so I guess that's why.
Get a new instructor. It looks as if the declaration of plus() is completely wrong. * it probably should return a value rather than a reference * if it must return a reference, it should return a const reference * it should definitely take a const reference as a parameter That is for likely sensible implementations of a member plus() function. Of course, it should probably be a friend.
I think in this case it is safe to use ``` return *this ``` because `this` refers to the current object so it is guaranteed to exist, so it won't be null. The reason `plus` returns reference to itself is so that it can be chained: ``` Fraction C = A.plus(B).plus(D) // perhaps? ``` Note that in the above case C will be created by copying the result of addition. This also assumes that operation `plus` is meant to modify object (in this case A) and return the reference to this modified object. Wouldn't plus accept reference instead of making copy of the parameter? ``` Fraction& plus( const Fraction& frac ) ``` This is similar to how you would implement `operator=` (an example): ``` A& operator=(const A& right) { if(this == &right) return *this; // Handle self-assignment b = right.b; return *this; } ``` Maybe you would want to not modify object and return new object: ``` // assuming there's a constructor Fraction(int numerator, int denominator): Fraction* plus(Fraction const& rhs) { return new Fraction(numerator * rhs.denominator + rhs.numerator * denominator, denominator * rhs.denominator); } ``` But this of course has to return pointer to new instance which is not a reference as maybe required in your task (?). Or even better: ``` Fraction plus(Fraction const& rhs) { return Fraction(numerator * rhs.denominator + rhs.numerator * denominator, denominator * rhs.denominator); } ``` This will create Fraction in the space of calling function so there's no overhead of copying structure on return.
Is using *this a good idea?
[ "", "c++", "this-pointer", "" ]
I need to take a C++ vector with potentially a lot of elements, erase duplicates, and sort it. I currently have the below code, but it doesn't work. ``` vec.erase( std::unique(vec.begin(), vec.end()), vec.end()); std::sort(vec.begin(), vec.end()); ``` How can I correctly do this? Additionally, is it faster to erase the duplicates first (similar to coded above) or perform the sort first? If I do perform the sort first, is it guaranteed to remain sorted after `std::unique` is executed? Or is there another (perhaps more efficient) way to do all this?
I agree with [R. Pate](https://stackoverflow.com/questions/1041620/most-efficient-way-to-erase-duplicates-and-sort-a-c-vector/1041874#1041874) and [Todd Gardner](https://stackoverflow.com/questions/1041620/most-efficient-way-to-erase-duplicates-and-sort-a-c-vector/1041700#1041700); a [`std::set`](http://en.cppreference.com/w/cpp/container/set) might be a good idea here. Even if you're stuck using vectors, if you have enough duplicates, you might be better off creating a set to do the dirty work. Let's compare three approaches: **Just using vector, sort + unique** ``` sort( vec.begin(), vec.end() ); vec.erase( unique( vec.begin(), vec.end() ), vec.end() ); ``` **Convert to set (manually)** ``` set<int> s; unsigned size = vec.size(); for( unsigned i = 0; i < size; ++i ) s.insert( vec[i] ); vec.assign( s.begin(), s.end() ); ``` **Convert to set (using a constructor)** ``` set<int> s( vec.begin(), vec.end() ); vec.assign( s.begin(), s.end() ); ``` Here's how these perform as the number of duplicates changes: ![comparison of vector and set approaches](https://i.stack.imgur.com/gGgtR.png) **Summary**: when the number of duplicates is large enough, *it's actually faster to convert to a set and then dump the data back into a vector*. And for some reason, doing the set conversion manually seems to be faster than using the set constructor -- at least on the toy random data that I used.
I redid Nate Kohl's profiling and got different results. For my test case, directly sorting the vector is always more efficient than using a set. I added a new more efficient method, using an `unordered_set`. Keep in mind that the `unordered_set` method only works if you have a good hash function for the type you need uniqued and sorted. For ints, this is easy! (The standard library provides a default hash which is simply the identity function.) Also, don't forget to sort at the end since unordered\_set is, well, unordered :) I did some digging inside the `set` and `unordered_set` implementation and discovered that the constructor actually construct a new node for every element, before checking its value to determine if it should actually be inserted (in Visual Studio implementation, at least). Here are the 5 methods: **f1: Just using `vector`, `sort` + `unique`** ``` sort( vec.begin(), vec.end() ); vec.erase( unique( vec.begin(), vec.end() ), vec.end() ); ``` **f2: Convert to `set` (using a constructor)** ``` set<int> s( vec.begin(), vec.end() ); vec.assign( s.begin(), s.end() ); ``` **f3: Convert to `set` (manually)** ``` set<int> s; for (int i : vec) s.insert(i); vec.assign( s.begin(), s.end() ); ``` **f4: Convert to `unordered_set` (using a constructor)** ``` unordered_set<int> s( vec.begin(), vec.end() ); vec.assign( s.begin(), s.end() ); sort( vec.begin(), vec.end() ); ``` **f5: Convert to `unordered_set` (manually)** ``` unordered_set<int> s; for (int i : vec) s.insert(i); vec.assign( s.begin(), s.end() ); sort( vec.begin(), vec.end() ); ``` I did the test with a vector of 100,000,000 ints chosen randomly in ranges [1,10], [1,1000], and [1,100000] The results (in seconds, smaller is better): ``` range f1 f2 f3 f4 f5 [1,10] 1.6821 7.6804 2.8232 6.2634 0.7980 [1,1000] 5.0773 13.3658 8.2235 7.6884 1.9861 [1,100000] 8.7955 32.1148 26.5485 13.3278 3.9822 ```
What's the most efficient way to erase duplicates and sort a vector?
[ "", "c++", "sorting", "vector", "stl", "duplicates", "" ]
I have a process intensive task that I would like to run in the background. The user clicks on a page, the PHP script runs, and finally, based on some conditions, if required, then it has to run a shell script, E.G.: ``` shell_exec('php measurePerformance.php 47 844 email@yahoo.com'); ``` Currently I use [shell\_exec](http://uk.php.net/shell_exec), **but** this requires the script to wait for an output. Is there any way to execute the command I want **without** waiting for it to complete?
How about adding. ``` "> /dev/null 2>/dev/null &" shell_exec('php measurePerformance.php 47 844 email@yahoo.com > /dev/null 2>/dev/null &'); ``` Note this also gets rid of the stdio and stderr.
This will execute a command and disconnect from the running process. Of course, it can be any command you want. But for a test, you can create a php file with a sleep(20) command it. ``` exec("nohup /usr/bin/php -f sleep.php > /dev/null 2>&1 &"); ```
Is there a way to use shell_exec without waiting for the command to complete?
[ "", "php", "shell", "" ]
By default nunit tests run alphabetically. Does anyone know of any way to set the execution order? Does an attribute exist for this?
Your unit tests should each be able to run independently and stand alone. If they satisfy this criterion then the order does not matter. There are occasions however where you will want to run certain tests first. A typical example is in a Continuous Integration situation where some tests are longer running than others. We use the category attribute so that we can run the tests which use mocking ahead of the tests which use the database. i.e. put this at the start of your quick tests ``` [Category("QuickTests")] ``` Where you have tests which are dependant on certain environmental conditions, consider the *TestFixtureSetUp* and *TestFixtureTearDown* attributes, which allow you to mark methods to be executed before and after your tests.
I just want to point out that while most of the responders assumed these were unit tests, the question did not specify that they were. nUnit is a great tool that can be used for a variety of testing situations. I can see appropriate reasons for wanting to control test order. In those situations I have had to resort to incorporating a run order into the test name. It would be great to be able to specify run order using an attribute.
NUnit Test Run Order
[ "", "c#", ".net", "attributes", "nunit", "tdd", "" ]
Pardon my ignorance, but I've never really developed Windows applications. How do you store user settings? Is an embedded database the preferred method?
I think you are looking for [user settings](http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx): > The .NET Framework 2.0 allows you to > create and access values that are > persisted between application > execution sessions. These values are > called settings. Settings can > represent user preferences, or > valuable information the application > needs to use. For example, you might > create a series of settings that store > user preferences for the color scheme > of an application. Or you might store > the connection string that specifies a > database that your application uses. > Settings allow you to both persist > information that is critical to the > application outside of the code, and > to create profiles that store the > preferences of individual users.
It depends on what kind of settings. There are a variety of methods from embedded databases (like SQLite) to XML files, to the Registry. * If the settings are very few, the registry often makes sense. * If the settings are more complicated, and need to be hand edited, you can use XML files or JSON. * If the settings are complex and do not need hand editing, an embedded database like SQLite, .NetBtree, or BerkelyDB .NET are good choices.
What's the preferred method for storing user settings in a .NET windows application?
[ "", "c#", ".net", "winforms", "" ]
I face the following problem ``` function book($memberid, $classid){ if (!book){ // update the db and change the book variable to true } } ``` My problem is 2 requests submitted at the same time. The first request passes the line if (!book){ but not yet update the db. And at the same time, the second request runs the same function and also passes the line if (!book){. Therefore, the result is wrong. I want to know how to solve this concurrency problem. Lock the db? But I am afraid that it will affect the performance.
Why do you need that variable? The standard way of resolving concurrency problems when updating databases is to let the database handle it by means of transactions (which will impact performance in some cases, but so will a code only solution). I'd like to see what goes inside the if (!book) clause. EDIT: Why don't you change the db to make the (person,class) combination a unique key? That way you just physically cannot insert twice the same value in the table. I'm still taking wild guesses because it depends on the structure of the database. Also MySQL has a special syntax to do a conditional insert which would suit here. Check this [url](http://forums.mysql.com/read.php?97,164551,164575#msg-164575).
If you [create an unique index(person,class)](http://dev.mysql.com/doc/refman/5.0/en/create-index.html) you can simply try to insert the new record without any previous tets. If there's already another record with the same values in (person,class) the new record will be rejected and MySQL raises a ["duplicate key" error](http://dev.mysql.com/doc/refman/5.0/en/error-messages-server.html#error_er_dup_entry) which can be appropriately handled by your script: ``` if ( 1062===mysql_errno() ) { echo "you've already made a reservation for this lecture."; } ```
Concurrent requests problem in mysql
[ "", "php", "mysql", "" ]
Why does the following code throw `ArrayStoreException`? ``` double[] a = {2.0,3.4,3.6,2.7,5.6}; int[] b = {2,3,4,5}; System.arraycopy(b,0,a,1,4); ```
From the docs for [`System.arraycopy`](http://java.sun.com/javase/6/docs/api/java/lang/System.html): > Otherwise, if any of the following is > true, an ArrayStoreException is thrown > and the destination is not modified: > > [...] > > The src argument and dest argument > refer to arrays whose component types > are different primitive types. That's exactly the case here - `int` and `double` are different primitive types, so the exception is thrown as documented. The point of `arraycopy` is that it can work blindingly fast by copying the raw data blindly, without having to apply any conversions. In your case it *would* have to apply conversions, so it fails.
Yeah, that's the documented behavior for an `arraycopy` between arrays with different primitive types as components. Whether the type could normally be promoted isn't relevant; this is what `arraycopy` is designed to do.
Unexpected ArrayStoreException
[ "", "java", "" ]
Is there a simple way to have isometric projection? I mean [the true isometric projection](http://en.wikipedia.org/wiki/Isometric_projection), not the general orthogonal projection. (Isometric projection happens only when projections of unit X, Y and Z vectors are equally long and angles between them are exactly 120 degrees.)
Try using [gluLookAt](https://registry.khronos.org/OpenGL-Refpages/gl4/) ``` glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); /* use this length so that camera is 1 unit away from origin */ double dist = sqrt(1 / 3.0); gluLookAt(dist, dist, dist, /* position of camera */ 0.0, 0.0, 0.0, /* where camera is pointing at */ 0.0, 1.0, 0.0); /* which direction is up */ glMatrixMode(GL_MODELVIEW); glBegin(GL_LINES); glColor3d(1.0, 0.0, 0.0); glVertex3d(0.0, 0.0, 0.0); glVertex3d(1.0, 0.0, 0.0); glColor3d(0.0, 1.0, 0.0); glVertex3d(0.0, 0.0, 0.0); glVertex3d(0.0, 1.0, 0.0); glColor3d(0.0, 0.0, 1.0); glVertex3d(0.0, 0.0, 0.0); glVertex3d(0.0, 0.0, 1.0); glEnd(); glFlush(); ``` Results in [![alt text](https://i.stack.imgur.com/Z9nyf.png)](https://i.stack.imgur.com/Z9nyf.png) We can draw a cube to check that parallel lines are indeed parallel ``` glPushMatrix(); glTranslated(0.5, 0.5, 0.5); glColor3d(0.5, 0.5, 0.5); glutWireCube(1); glPopMatrix(); ``` [![alt text](https://i.stack.imgur.com/vtyRs.png)](https://i.stack.imgur.com/vtyRs.png)
An isometric projection is just a matter of using an orthographic projection with a specific rotation angle. You should be able to choose any of the 8 potential orientations, with a orthographic projection, and get a perfect isometric view of your model. Just follow the math in your referenced Wiki article for setting up the view matrix, and do an orthographic projection for your projection matrix, and you're all set.
true isometric projection with opengl
[ "", "c++", "opengl", "projection", "isometric", "" ]
A specific example: becoming familiar with django's project source code (core, contrib, utils, etc.). Example of a useful tool: ctags - it allows you to "jump" to the file+location where a function/method is defined. Wondering about other tools that developers use (example: is there a tool that given a function x(), lists the functions that call x() and that are called by x()?). Thanks. **Edit**: added an answer with an aggregate of tools mentioned so far in other answers
The following is an aggregate of tools mentioned in other answers... ## cscope [http://cscope.sourceforge.net/](https://cscope.sourceforge.net/) wikipedia entry: [http://en.wikipedia.org/wiki/Cscope](https://en.wikipedia.org/wiki/Cscope) cscope is a console mode or text-based graphical interface ... It is often used on very large projects to find source code, functions, declarations, definitions and regular expressions given a text string. ## pycscope [http://pypi.python.org/pypi/pycscope/](https://pypi.org/project/pycscope/) generates a cscope index of Python source trees ## ctags and exuberant ctags [http://ctags.sourceforge.net/](https://ctags.sourceforge.net/) [http://ctags.sourceforge.net/ctags.html](https://ctags.sourceforge.net/ctags.html) wikipedia entry: [http://en.wikipedia.org/wiki/Ctags](https://en.wikipedia.org/wiki/Ctags) Ctags is a program that generates an index (or tag) file of names found in source and header files of various programming languages. Depending on the language, functions, variables, class members, macros and so on may be indexed. These tags allow definitions to be quickly and easily located by a text editor or other utility. ## Eclipse: [http://www.eclipse.org/](https://www.eclipse.org/) wikipedia entry: [http://en.wikipedia.org/wiki/Eclipse\_%28software%29](https://en.wikipedia.org/wiki/Eclipse_(software)) Eclipse is a multi-language software development platform comprising an IDE and a plug-in system to extend it. It is written primarily in Java and can be used to develop applications in Java and, by means of the various plug-ins, in other languages as well, including C, C++, COBOL, Python, Perl, PHP, and others. ## PyDev [http://pydev.sourceforge.net/](https://pydev.sourceforge.net/) "Pydev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE" ## Komodo Edit [http://www.activestate.com/komodo\_edit/](https://www.activestate.com/products/komodo-edit/) wikipedia entry: [http://en.wikipedia.org/wiki/ActiveState\_Komodo](https://en.wikipedia.org/wiki/ActiveState_Komodo) Komodo Edit is a free text editor for dynamic programming languages introduced in January 2007. With the release of version 4.3, Komodo Edit is built on top of the Open Komodo project. It was developed for programmers who need a multi-language editor with broad functionality, but not the features of an IDE, like debugging, DOM viewer, interactive shells, and source code control integration. ## Prashanth's call graph (visualization) tool [http://blog.prashanthellina.com/2007/11/14/generating-call-graphs-for-understanding-and-refactoring-python-code/](https://web.archive.org/web/20150803104638/http://blog.prashanthellina.com:80/2007/11/14/generating-call-graphs-for-understanding-and-refactoring-python-code/) Just thought I'd share a link to an interesting small fun script I've found long time ago, that draws a graph of function calls. It works only for simple cases, so "as is" it's more fun than useful. ## rope/ropemacs [http://rope.sourceforge.net/ropemacs.html](https://web.archive.org/web/20150428084244/http://rope.sourceforge.net:80/ropemacs.html) Ropemacs is a plugin for performing python refactorings in emacs. It uses [rope](https://rope.sourceforge.net/) library and pymacs. [http://www.enigmacurry.com/2008/05/09/emacs-as-a-powerful-python-ide/](https://enigmacurry.com/2008/05/09/emacs-as-a-powerful-python-ide/) ## Wing IDE [http://www.wingware.com/](https://www.wingware.com/) Wing IDE has goto-definition, find uses, a source browser, refactoring, and other code intelligence features that should help. Another good way to understand unfamiliar Python code is to set a breakpoint, run to it in the debugger, and then go up and down the stack. In Wing Professional you can also use the Debug Probe to interact with and try out things in the debug runtime state (it's a Python shell that runs in the context of the current debug stack frame).
You can maybe try cscope! Wikipedia says that > cscope is often used to search content within C or C++ files, but it can be used to search for content in other languages such as Java, Python, PHP and Perl.[citation needed] And you can also dig in [this project](http://pypi.python.org/pypi/pycscope/0.2).
tools to aid in browsing/following (large) python projects' source code
[ "", "python", "django", "ide", "" ]
I am running on an issue using C# SendKeys.Send method. I am trying to replace keyboard keys with other keys, for example when I press "a" in keyboard I want that key to be "s" for example, when I am doing this in my code: ``` if ((Keys)keyCode== Keys.A) { SendKeys.Send("s"); } ``` Right now I get only "sa" character printed in my notepad, but instead of printing "sa" I need to get only "s" character in this case because when I press "a" on my keyboard, "a" must be replaced with "s". I tried removing the last character by adding this line: ``` SendKeys.Send("{BS}"); ``` But all I got is "s" character removed and "a" character was there. How can I prevent this from happening?
I solved this problem by registering global hot keys. Thank you. [This](http://www.dotnet2themax.com/ShowContent.aspx?ID=103cca7a-0323-47eb-b210-c2bb7075ba78) was the resourse that I used to solve my problem.
I would reverse my calls: `SendKeys.Send("{BS}");` `SendKeys.Send("S");` EDIT (After Question Updated): If you're working with the string (for your special characters), can you not just capture the string generated by the key press ("a") and modify it by setting the string to the unicode value of the character you're attempting to represent? If the other solutions people have been mentioning aren't working, that's where I'd try next...
C# SendKeys.Send
[ "", "c#", "sendkeys", "" ]
I want to reuse some code I wrote to add some functionality to a datagridview. I want the default datagridview properties and events to be exposed, so I didn't want to create a new custom component. so I tried writing a subclass, which works fine. but it also occurred to me that I could write a standalone utility class that takes a datagridview in the constructor and sets it up the same way. e.g. ``` public class MyGrid { private DataGridView m_dg; public MyGrid(DataGridView dg) { m_dg = dg; m_dg.RowHeadersVisible = false; m_dg.SortCompare += new DataGridViewSortCompareEventHandler(m_dg_SortCompare); } void m_dg_SortCompare(object sender, DataGridViewSortCompareEventArgs e) { // do custom sorting here } } ``` so somewhere in my app's startup I would call ``` MyGrid g1 = new MyGrid(dataGridView1); MyGrid g2 = new MyGrid(dataGridView2); ``` and so forth. any disadvantages to this approach? it seems like much of the code is going to be the same, the difference is between how you instantiate the extended grid (drag and drop a subclassed control to the form vs drag a plain datagridview and call the above code)
The only disadvantage of a utility class, is that you lose the designer support. Meaning, if you subclass the control, when you add it to the designer, any changes you make in the constructor of your inherited control will show up in the designer. Furthermore, if you want to add some properties to it, they will show up in the properties window, giving it even more flexibility. If designer support doesn't matter to you though, then I don't see any other drawbacks to a utility class.
In the long run, a utility class will be more maintainable than a subclassed control unless you are doing something more substantial to extend DataGridView than modifying sorting. Your approach for the utility class (taking a DataGridView in the constructor) is a solid approach.
utility class vs subclassing .net controls
[ "", "c#", "datagridview", "controls", "subclassing", "" ]
I am trying to learn WCF. I have a simple client and server application setup and upon pressing a button on the client, it gets an updated value from the server. My next step is I am trying to do a callback from the server to the client to update its value. I have poured through many examples, and they just seem too big and confusing. Is there anyone that can give my just the simplest example of its implementation in C#? I keep looking through examples online and I just do not understand what it takes? Of course I could copy the example line by line but that does me no good because I still don't what to implement if I wanted to do this in my own code. Could someone please help me with a very simple example on what steps I would need to take and what I would need to do in the server code and then in the client code to make this happen? Thank you
Here is about the simplest complete example that I can come up with: ``` public interface IMyContractCallback { [OperationContract] void OnCallback(); } [ServiceContract(CallbackContract = typeof(IMyContractCallback))] public interface IMyContract { [OperationContract] void DoSomething(); } [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)] public class MyService : IMyContract { public void DoSomething() { Console.WriteLine("Hi from server!"); var callback = OperationContext.Current.GetCallbackChannel<IMyContractCallback>(); callback.OnCallback(); } } public class MyContractClient : DuplexClientBase<IMyContract> { public MyContractClient(object callbackInstance, Binding binding, EndpointAddress remoteAddress) : base(callbackInstance, binding, remoteAddress) { } } public class MyCallbackClient : IMyContractCallback { public void OnCallback() { Console.WriteLine("Hi from client!"); } } class Program { static void Main(string[] args) { var uri = new Uri("net.tcp://localhost"); var binding = new NetTcpBinding(); var host = new ServiceHost(typeof(MyService), uri); host.AddServiceEndpoint(typeof(IMyContract), binding, ""); host.Open(); var callback = new MyCallbackClient(); var client = new MyContractClient(callback, binding, new EndpointAddress(uri)); var proxy = client.ChannelFactory.CreateChannel(); proxy.DoSomething(); // Printed in console: // Hi from server! // Hi from client! client.Close(); host.Close(); } } ``` A few namespaces will need to be included in order to run the example: ``` using System; using System.ServiceModel; using System.ServiceModel.Channels; ```
I know, old question... I came across this question from a google search earlier today and the answer provided by Ray Vernagus is the easiest to understand example of WCF that I have read to date. So much so that I was able to rewrite it in VB.NET without using any online converters. I thought I'd add the VB.NET variant of the example that Ray Vernagus provided. Just create a new VB.NET Windows Console application, add a reference to `System.ServiceModel`, and copy/paste the entire code below into the default `Module1` class file. ``` Imports System.ServiceModel Imports System.ServiceModel.Channels Public Interface IMyContractCallback <OperationContract()> _ Sub OnCallBack() End Interface <ServiceContract(CallBackContract:=GetType(IMyContractCallback))> _ Public Interface IMyContract <OperationContract()> _ Sub DoSomething() End Interface <ServiceBehavior(ConcurrencyMode:=ConcurrencyMode.Reentrant)> _ Public Class Myservice Implements IMyContract Public Sub DoSomething() Implements IMyContract.DoSomething Console.WriteLine("Hi from server!") Dim callback As IMyContractCallback = OperationContext.Current.GetCallbackChannel(Of IMyContractCallback)() callback.OnCallBack() End Sub End Class Public Class MyContractClient Inherits DuplexClientBase(Of IMyContract) Public Sub New(ByVal callbackinstance As Object, ByVal binding As Binding, ByVal remoteAddress As EndpointAddress) MyBase.New(callbackinstance, binding, remoteAddress) End Sub End Class Public Class MyCallbackClient Implements IMyContractCallback Public Sub OnCallBack() Implements IMyContractCallback.OnCallBack Console.WriteLine("Hi from client!") End Sub End Class Module Module1 Sub Main() Dim uri As New Uri("net.tcp://localhost") Dim binding As New NetTcpBinding() Dim host As New ServiceHost(GetType(Myservice), uri) host.AddServiceEndpoint(GetType(IMyContract), binding, "") host.Open() Dim callback As New MyCallbackClient() Dim client As New MyContractClient(callback, binding, New EndpointAddress(uri)) Dim proxy As IMyContract = client.ChannelFactory.CreateChannel() proxy.DoSomething() ' Printed in console: ' Hi from server! ' Hi from client! Console.ReadLine() client.Close() host.Close() End Sub End Module ```
What steps do I need to take to use WCF Callbacks?
[ "", "c#", ".net", "vb.net", "wcf", "callback", "" ]
i want to make a draggable image in jquery. first of all my experience with jquery is 0. having said that let me describe what i want to achieve. i have fixed width/height div. and the image contained inside the div is large in size. so i want the image to be draggable inside that div so that the user can see the entire image. can someone help. pls be a little elaborate about the procedure considering my jquery fluency.
You can use the following; ``` $(function() { $("#draggable").draggable(); }); ``` ``` .container { margin-top: 50px; cursor: move; } #screen { overflow: hidden; width: 200px; height: 200px; clear: both; border: 1px solid black; } ``` ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <div class="container"> <div id="screen"> <img src="https://picsum.photos/200/200" class="drag-image" id="draggable" /> </div> </div> ```
You want the jQuery [Draggable](http://docs.jquery.com/UI/Draggable) UI tool. The code for this, as with all jQuery, is very simple: ``` $(document).ready(function(){ $("#draggable").draggable(); }); ``` Will create a draggable object from a standard html tag (the `IMG` in your case). And for limiting it's mobility to a specific region, you would look into its [containment option](http://docs.jquery.com/UI/Draggable#option-containment). ### Update: *"What is '#draggable' and 'ready'"?* 1. '#draggable' represents the element that you want to be able to drag. The hash (#) symbol represents an ID. When you add your image tags, may give give it an id like the following: `<img src="myimage.jpg" id="draggable" />` That will make the javascript above make your image draggable, because it has the '#draggable' id that the jQuery is looking for. 2. `'.ready()'` is the method that is automagically raised by your browser once the page is finished loading. Developers are encouraged by the jQuery group to place all jQuery code within this method to ensure all of the elements on the page are completely loaded prior to any jQuery code attempts to manipulate them.
jquery drag image
[ "", "javascript", "jquery", "dom", "jquery-ui", "" ]
Assigning a `Date` variable to another one will copy the reference to the same instance. This means that changing one will change the other. How can I actually clone or copy a `Date` instance?
Use the [Date](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date) object's [`getTime()`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/getTime) method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC ([epoch time](http://en.wikipedia.org/wiki/Unix_time)): ``` var date = new Date(); var copiedDate = new Date(date.getTime()); ``` In Safari 4, you can also write: ``` var date = new Date(); var copiedDate = new Date(date); ``` ...but I'm not sure whether this works in other browsers. (It seems to work in IE8).
This is the cleanest approach ``` let date = new Date() let copyOfDate = new Date(date.valueOf()) console.log(date); console.log(copyOfDate); ```
How to clone a Date object?
[ "", "javascript", "datetime", "" ]
I have a simple WinForms app just one window with one WebBrowser control inside. On vista this fails to show the date but works OK XP ? The website runs activeX to show the date. ``` namespace WindowsFormsBrowserTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.webBrowser1.Navigate("http://www.pcpitstop.com/testax.asp"); } } } ``` <http://www.pcpitstop.com/testax.asp> Any clues would be really appreciated, should be simple but I have no idea. Any security experts out there?
I have eventually sorted this issue out. One web page caused exceptions. The application was hosting a web page running an activeX control. Turned off Data Execution Prevention "DEP" for the application with a post build step. All working fine now.
Can you view the website properly in Internet Explorer on Vista when it fails? I know when I visit that website I get asked to install an ActiveX control. The WebBrowser control won't handle the installation of the ActiveX control for you.
WebBrowser control fails on Vista
[ "", "c#", "winforms", "security", "windows-vista", "webbrowser-control", "" ]
I have an array of objects, and want the objects to be able to reference their 'neighbors' (the next and previous objects in the array). Is there an existing pattern to do that? Perhaps the array should be wrapped in an object (since the object can be iterated just as well as the array). That's fine too, I'm just looking for an existing good-practice pattern.
Described problem looks very similar to usual [linked list](http://en.wikipedia.org/wiki/Linked_list). You can just add next and prev fields into your object, or in case you don't want to change it, you can create a wrapper object which will contain the original and will have those fields. Or in case the array is global enough to store only your current index inside the array and then it's very simple to get your neighbors.
I'd consider using the [Iterator interface](http://php.net/manual/en/class.iterator.php) with your wrapper object. This approach would be the "existing good practice" that you're looking for.
PHP Array of Objects Internal Navigation Pattern
[ "", "php", "design-patterns", "oop", "" ]
I have a utc timestamp in the IS8601 format and am trying to convert it to unix time. This is my console session: ``` In [9]: mydate Out[9]: '2009-07-17T01:21:00.000Z' In [10]: parseddate = iso8601.parse_date(mydate) In [14]: ti = time.mktime(parseddate.timetuple()) In [25]: datetime.datetime.utcfromtimestamp(ti) Out[25]: datetime.datetime(2009, 7, 17, 7, 21) In [26]: datetime.datetime.fromtimestamp(ti) Out[26]: datetime.datetime(2009, 7, 17, 2, 21) In [27]: ti Out[27]: 1247815260.0 In [28]: parseddate Out[28]: datetime.datetime(2009, 7, 17, 1, 21, tzinfo=<iso8601.iso8601.Utc object at 0x01D74C70>) ``` As you can see, I can't get the correct time back. The hour is ahead by one if i use fromtimestamp(), and it's ahead by six hours if i use utcfromtimestamp() Any advice? Thanks!
You can create an `struct_time` in UTC with [`datetime.utctimetuple()`](http://docs.python.org/library/datetime.html#datetime.datetime.utctimetuple) and then convert this to a unix timestamp with [`calendar.timegm()`](http://docs.python.org/library/calendar.html#calendar.timegm): ``` calendar.timegm(parseddate.utctimetuple()) ``` This also takes care of any daylight savings time offset, because `utctimetuple()` normalizes this.
I am just guessing, but one hour difference can be not because of time zones, but because of daylight savings on/off.
How to specify time zone (UTC) when converting to Unix time? (Python)
[ "", "python", "datetime", "iso8601", "unix-timestamp", "" ]
noob here still experimenting with templates. Trying to write a message processing class template ``` template <typename T> class MessageProcessor { //constructor, destructor defined //Code using t_ and other functions foo( void ) { //More code in a perfectly fine method } private: T *t_ }; ``` All defined in a header file. I've built and tested my class and all is well. Now, I'm trying to do this: ``` template <typename T> class MessageProcesor { //Same stuff as before foo(void) { //Same code as before in foo, but one new line: t_->getMessageSender<MessageType>(); } private: T *t_; }; ``` However, this line gives me an error of bad expression-type before '>' token. I've added the necessary header files to define what a MessageType is. I've used this function many time before, just not in this context. I suspect that the compiler doesn't like the fact that the template function is fully defined (specialized?) within an undefined class template (unspecialized?). I'm not fully grokking what makes a template 'specialized'. Most explanations center on the concepts of 'full' or 'partial', but not what makes it specialized in the first place. Apologies if you'd like to see more code. I have no internet access at work and that's where I'm doing this, so I have to put everything into my mental 'scratchpad' and bring it home.
Your member function 'foo' needs a return type and you need to use the keyword 'template' when you use member templates in dependent expressions (expressions whose meanings rely directly or indirectly on a generic template parameter) ``` t_->template getMessageSender<MessageType>(); // ok t_->getMessageSender<MessageType>(); // not ok ``` Perhaps this example will help you appreciate when a member template *needs* to be prefixed by the 'template' keyword [Note: in the interest of symmetry you may always use the 'template' prefix on member templates, but it is optional when used on a non-dependent expression. ``` struct MyType { template<class T> void foo() { } }; template<class U> struct S { template<class T> void bar() { MyType mt; // non-dependent on any template parameter mt.template foo<int>(); // ok mt.foo<int>(); // also ok // 't' is dependent on template parameter T T t; t.template foo<int>(); // ok t.foo<int>(); // not ok S<T> st; // 'st' is dependent on template parameter T st.template foo<int>(); // ok st.foo<int>(); // not ok S<MyType> s; // non-dependent on any template parameter s.bar<int>(); // ok s.template bar<int>(); // also ok } }; ``` Hope that helps.
Add the keyword `template` between `->` and the name of the template method: ``` t_->template getMessageSender<MessageType>(); ```
Template class inside class template in c++
[ "", "c++", "templates", "specialization", "class-template", "" ]
I want to take a snapshot with my webcam using java and save it to a jpg file. What are the steps needed to do so? A tutorial would be greatly appreciated. Greetings, Burkhard
the JMF (Java Media Framework) is a good starting point. However, I did not succeed with it. I finally found the solution [here](http://www.comp.rgu.ac.uk/staff/fh/CM4062/mis/jmf/FrameGrab.html). The important part being: ``` Buffer buf = frameGrabber.grabFrame(); // Convert frame to an buffered image so it can be processed and saved Image img = (new BufferToImage((VideoFormat) buf.getFormat()).createImage(buf)); buffImg = new BufferedImage(img.getWidth(this), img.getHeight(this), BufferedImage.TYPE_INT_RGB); //TODO saving the buffImg ```
what you are looking for might be the Java Media Framework (JMF). See the [Sun Tutorial](http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/solutions/index.html). I hope that helps.
How to take single snapshots from a webcam?
[ "", "java", "windows", "webcam", "capture", "" ]
I get an integer and I need to convert to a month names in various locales: Example for locale en-us: 1 -> January 2 -> February Example for locale es-mx: 1 -> Enero 2 -> Febrero
``` import java.text.DateFormatSymbols; public String getMonth(int month) { return new DateFormatSymbols().getMonths()[month-1]; } ```
# tl;dr ``` Month // Enum class, predefining and naming a dozen objects, one for each month of the year. .of( 12 ) // Retrieving one of the enum objects by number, 1-12. .getDisplayName( TextStyle.FULL_STANDALONE , Locale.CANADA_FRENCH // Locale determines the human language and cultural norms used in localizing. ) ``` # java.time Since Java 1.8 (or 1.7 & 1.6 with the [*ThreeTen-Backport*](http://www.threeten.org/threetenbp/)) you can use this: ``` Month.of(integerMonth).getDisplayName(TextStyle.FULL_STANDALONE, locale); ``` Note that `integerMonth` is 1-based, i.e. 1 is for January. Range is always from 1 to 12 for January-December (i.e. Gregorian calendar only).
How can I convert an Integer to localized month name in Java?
[ "", "java", "date", "locale", "" ]
I have asked this problem on many popular forums but no concrete response. My applciation uses serial communication to interface with external systems each having its own interface protocol. The data that is received from the systems is displayed on a GUI made in Qt 4.2.1. Structure of application is such that 1. When app begins we have a login page with a choice of four modules. This is implemented as a maindisplay class. Each of the four modules is a separate class in itself. The concerned module here is of action class which is responsible of gathering and displaying data from various systems. 2. User authentication gets him/her into the action screen. The constructor of the action screen class executes and apart from mundane initialisation it starts the individual systems threads which are implemented as singleton. Each system protocol is implemented as a singleton thread of the form: ``` class SensorProtocol:public QThread { static SensorProtocol* s_instance; SensorProtocol(){} SensorProtocol(const SensorProtocol&); operator=(const SensorProtocol&); public: static SensorProtocol* getInstance(); //miscellaneous system related data to be used for // data acquisition and processing }; ``` In implementation file \*.cpp: ``` SensorProtocol* SensorProtocol::s_instance=0; SensorProtocol* SensorProtocol::getInstance() { //DOUBLE CHECKED LOCKING PATTERN I have used singletons // without this overrated pattern also but just fyi if(!s_instance) { mutex.lock(); if(!s_instance) s_instance=new SensorProtocol(); mutex.unlock(); } } ``` Structure of run function ``` while(!mStop) { mutex.lock() while(!WaitCondition.wait(&mutex,5) { if(mStop) return; } //code to read from port when data becomes available // and process it and store in variables mutex.unlock(); } ``` In the action screen class I have define an InputSignalHandler using sigaction and saio. This is a function pointer which is activated as soon as data arrives on any of the serial ports. It is a global function (we cannot change it as it is specific to Linux) which is just used to compare the file descriptors of the serial port where data has arrived and the fd's of the sensor systems, if a match is found WaitCondition.wakeOne is invoked on that thread and it comes out the wait and reads and processes the data. In the action screen class the individual threads are started as `SensorProtocol::getInstance()->start()`. Each system's protocol has a frame rate at which it sends data. Based on this fact, in actions screen we set up update timers to time out at refresh rate of protocols. When these timers time out the UpdateSensorProtocol() function of operation screen is called ``` connect(&timer, SIGNAL(timeout), this,SLOT(UpdateSensorProtocol())); ``` This grabs an instance of sensor singleton as ``` SensorProtocol* pSingleton=SensorProtocol::getInstance(); if(pSingleton->mUpdate) { //update data on action screen GUI pSingleton->mUpdate=false; //NOTE : this variable is set to // true in the singleton thread // while one frame is processed completely } ``` For all uses of singleton instance `SensorProtocol::getInstance()` is used. Given the above scenario, One of my protocols is hanging no matter what changes I do. The hang occurs in the while displaying data using UpdateSensorProtocol() If I comment `ShowSensorData()` function in the `UpdateSensorProtocol()` it works fine. But otherwise it hangs and the GUI freezes. Any suggestions! Also, Since the main thread grabs the running instance of singleton, is it really multithreading because we are essentially changing mUpdate in singleton itself albeit from action screen. I am confused in this. Also, Can somebody suggest an alternate design as to what I am doing now. Thanks In Advance
First off all don't make the Systems singletons. Use some kind of [Context Encapsulation](http://www.two-sdg.demon.co.uk/curbralan/papers/europlop/ContextEncapsulation.pdf) for the different system. If you ignoe this advice and still want to create "singletons" threads at least use `QApplication::instance();` as the parent of the thread and put `QThread::wait()` in the singleton destructors otherwise your program will crash at the program exit. ``` if(!s_instance){ QMutexLocker lock(&mutex); if(!s_instance) s_instance=new SensorProtocol( QApplication::instance()); } ``` But this isn't going to solve your problem ... Qt is event driven so try to exployed this very nice event-driven architecture and create a eventloop for each system thread. Then you can create "SystemProtocols" that live in another threads and you can create timers, send events between threads, ... without using low level synchronization objects. Have a look at the blog entry from Bradley T. Hughes [Treading without the headache](http://labs.trolltech.com/blogs/2006/12/04/threading-without-the-headache/) Code is not compiled but should give you a good idea where to start ... ``` class GuiComponent : public QWidget { //... signals: void start(int); // button triggerd signal void stop(); // button triggerd singal public slots: // don't forget to register DataPackage at the metacompiler // qRegisterMetaType<DataPackage>(); void dataFromProtocol( DataPackage ){ // update the gui the the new data } }; class ProtocolSystem : public QObject { //... int timerId; signals: void dataReady(DataPackage); public slots: void stop() { killTimer(timerId); } void start( int interval ) { timerId = startTimer(); } protected: void timerEvent(QTimerEvent * event) { //code to read from port when data becomes available // and process it and store in dataPackage emit dataReady(dataPackage); } }; int main( int argc, char ** argv ) { QApplication app( argc, argv ); // construct the system and glue them together ProtocolSystem protocolSystem; GuiComponent gui; gui.connect(&protocolSystem, SIGNAL(dataReady(DataPackage)), SLOT(dataFromProtocol(DataPackage))); protocolSystem.connect(&gui, SIGNAL(start(int)), SLOT(start(int))); protocolSystem.connect(&gui, SIGNAL(stop()), SLOT(stop())); // move communication to its thread QThread protocolThread; protocolSystem.moveToThread(&protocolThread); protocolThread.start(); // repeat this for other systems ... // start the application gui.show(); app.exec(); // stop eventloop to before closing the application protocolThread.quit(); protocolThread.wait(); return 0; } ``` Now you have total independent systems, gui and protocols don't now each other and don't even know that the program is multithreaded. You can unit test all systems independently in a single threaded environement and just glue them together in the real application and if you need to, divided them between different threads. That is the program architecture that I would use for this problem. Mutlithreading without a single low level synchronization element. No race conditions, no locks, ...
### Problems: Use RAII to lock/unlock your mutexes. They are currently not exception safe. ``` while(!mStop) { mutex.lock() while(!WaitCondition.wait(&mutex,5)) { if(mStop) { // PROBLEM 1: You mutex is still locked here. // So returning here will leave the mutex locked forever. return; } // PROBLEM 2: If you leave here via an exception. // This will not fire, and again you will the mutex locked forever. mutex.unlock(); // Problem 3: You are using the WaitCondition() incorrectly. // You unlock the mutex here. The next thing that happens is a call // WaitCondition.wait() where the mutex MUST be locked } // PROBLEM 4 // You are using the WaitCondition() incorrectly. // On exit the mutex is always locked. So nwo the mutex is locked. ``` What your code should look like: ``` while(!mStop) { MutextLocker lock(mutex); // RAII lock and unlock mutex. while(!WaitCondition.wait(&mutex,5)) { if(mStop) { return; } //code to read from port when data becomes available // and process it and store in variables } ``` By using RAII it solves all the problems I spotted above. ### On a side note. Your double checked locking will not work correctly. By using the static function variable suggested by 'Anders Karlsson' you solve the problem because g++ guarantees that static function variables will only be initialized once. In addition this method guaranteed that the singelton will be correctly destroyed (via destructor). Currently unless you are doing some fancy stuff via onexit() you will be leaking memory. See here for lots of details about better implementation of singleton. [C++ Singleton design pattern](https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289) See here why your double checked locking does not work. [What are all the common undefined behaviours that a C++ programmer should know about?](https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-c-programmer-should-know-about/367690#367690)
Threading issues in C++
[ "", "c++", "multithreading", "qt", "qt4", "" ]
I wonder how is the best way to integrate Java modules developed as separate J(2)EE applications. Each of those modules exposes Java interfaces. The POJO entities (Hibernate) are being used along with those Java interfaces, there is no DTO objects. What would be the best way to integrate those modules i.e. one module calling the other module interface remotely? I was thinking about: EJB3, Hessian, SOAP, JMS. there are pros and cons of each of the approaches. Folks, what is your opinion or your experiences?
Having dabbled with a few of the remoting technologies and found them universally unfun I would now use Spring remoting as an abstraction from the implementation. It allows you to concentrate on writing your functionality and let Spring handle the remote part with some config. you have the choice of several implementations (RMI, Spring's HTTP invoker, Hessian, Burlap and JMS). The abstraction means you can pick one implementation and simply swap it if your needs change. See the [SpringSource docs](http://static.springsource.org/spring/docs/2.0.x/reference/remoting.html) for more information.
The standard approach would be to use plain RMI between the various service components but this brings issues of sharing your Java interfaces and versioning changes to your domain model especially if you have lots of components using the same classes. Are you really running each service in a separate VM? If these EJBs are always talking to each other then you're best off putting them into the same VM and avoiding any remote procedure calls as these services can use their LocalInterfaces. The other thing that may bite you is using Hibernate POJOs. You may think that these are simple POJOs but behind the scenes Hibernate has been busy with CGLib trying to do things like allow lazy initialization. If these beans are serialzed and passed over remote boundaries then you may end up with odd Hibernate Exception getting thown. Personally I'd prefer to create simple DTOs or write the POJOs out as XML to pass between components. My colleagues would go one step further and write custom wire protocols for transferring the data for performance reasons. Recently I have been using the MULE ESB to integrate various service components. It's quite nice as you can have a mix of RMI, sockets, web services etc without having to write most of the boiler plate code. <http://www.mulesource.org/display/COMMUNITY/Home>
What remoting approach for Java application would you recommend?
[ "", "java", "remoting", "" ]
I'm wondering if there's a reason that there's no `first(iterable)` in the Python built-in functions, somewhat similar to `any(iterable)` and `all(iterable)` (it may be tucked in a stdlib module somewhere, but I don't see it in `itertools`). `first` would perform a short-circuit generator evaluation so that unnecessary (and a potentially infinite number of) operations can be avoided; i.e. ``` def identity(item): return item def first(iterable, predicate=identity): for item in iterable: if predicate(item): return item raise ValueError('No satisfactory value found') ``` This way you can express things like: ``` denominators = (2, 3, 4, 5) lcd = first(i for i in itertools.count(1) if all(i % denominators == 0 for denominator in denominators)) ``` Clearly you can't do `list(generator)[0]` in that case, since the generator doesn't terminate. Or if you have a bunch of regexes to match against (useful when they all have the same `groupdict` interface): ``` match = first(regex.match(big_text) for regex in regexes) ``` You save a lot of unnecessary processing by avoiding `list(generator)[0]` and short-circuiting on a positive match.
In **Python 2**, if you have an iterator, you can just call its `next` method. Something like: ``` >>> (5*x for x in xrange(2,4)).next() 10 ``` In **Python 3**, you can use the [`next` built-in](https://docs.python.org/3/library/functions.html#next) with an iterator: ``` >>> next(5*x for x in range(2,4)) 10 ```
There's a [Pypi package called “first”](https://pypi.python.org/pypi/first) that does this: ``` >>> from first import first >>> first([0, None, False, [], (), 42]) 42 ``` Here's how you would use to return the first odd number, for example: ``` >> first([2, 14, 7, 41, 53], key=lambda x: x % 2 == 1) 7 ``` If you just want to return the first element from the iterator regardless of whether is true or not, do this: ``` >>> first([0, None, False, [], (), 42], key=lambda x: True) 0 ``` It's a very small package: it only contains this function, it has no dependencies, and it works on Python 2 and 3. It's a single file, so you don't even have to install it to use it. In fact, here's almost the entire source code (from version 2.0.1, by Hynek Schlawack, released under the MIT licence): ``` def first(iterable, default=None, key=None): if key is None: for el in iterable: if el: return el else: for el in iterable: if key(el): return el return default ```
Why is there no first(iterable) built-in function in Python?
[ "", "python", "iterator", "generator", "" ]
I'd like to create a Word document using Python, however, I want to re-use as much of my existing document-creation code as possible. I am currently using an XSLT to generate an HTML file that I [programatically convert](http://www.xhtml2pdf.com/) to a PDF file. However, my client is now requesting that the same document be made available in Word (.doc) format. So far, I haven't had much luck finding any solutions to this problem. Is anyone aware of an open source library (or \*gulp\* a proprietary solution) that may help resolve this issue? NOTE: All possible solutions must run on Linux. I believe this eliminates pywin32.
A couple ways you can create Word documents using Python: * Use COM automation to create a document using the MS Word object model (using `pywin32`). <http://python.net/crew/pirx/spam7/> * Automate OpenOffice using Python: <http://wiki.services.openoffice.org/wiki/Python> * If rtf format is OK, use the PyRTF library: <http://pyrtf.sourceforge.net/> EDIT: Since COM is out of the question, I suggest the following (inspired by @kcrumley's answer): Using the UNO library to automate Open Office from python, open the HTML file in OOWriter, then save as .doc. EDIT2: There is now a pure Python [python-docx project](https://python-docx.readthedocs.org/en/latest/) that looks nice (I have not used it).
I tried [python-docx](https://github.com/mikemaccana/python-docx) with succes, it enables you to make and edit docx within Python
How can I create a Word document using Python?
[ "", "python", "xml", "xslt", "ms-word", "" ]
I need to generate invoices in large batch which will be transformed to EDI and transported to our HQ. There is an order table with all the orders coming in. At some point in the day I have to grab a set (about 1k) and generate the invoices. 1. Where would be the best place to generate the invoice numbers? On SQL Server backend? Or grab the batch into a .NET application and then generate the invoice numbers there? The invoice numbers can be random but must not repeat (for 3-4 years). I have a max of 12 digits to play with and can be alpha numeric. Where can I find information on generating invoice numbers. Note: While I am generating the invoices I need to compute the order totals and tax. I would appreciate your input.
Invoice numbers may be regulated by legal demands (where I live they need to be in sequence, and I don't think that there may be gaps in the sequence). You often see that the numbers include an element that will scope them in time (such as the year: **2009**03472). That way you minimize the risk of using the same number twice. You say you have ~1K invoices a day. That means that 6-figure invoice number will cover your needs. So 4-digit year followed by zero-padded 6-figure invoice number should probably get you going. I would probably have the database generate them to ensure that they are unique.
Add a table to your database which stores the value of the last Invoice Number used, and a stored procedure to increment this value and return the new value to you to use in the creation of your Invoice. When you save your new Invoice, make the call to the SP to get the next Invoice Number one of the last things you do - after validation passed but immdiately before writing to disk - in order to try to minimise the risk of "holes" in your numbering sequence.
Generating Invoices
[ "", ".net", "sql", "sql-server", "invoice", "" ]
Given a table where the first column is seconds past a certain reference point and the second one is an arbitrary measurement: ``` 6 0.738158581 21 0.801697222 39 1.797224596 49 2.77920469 54 2.839757536 79 3.832232283 91 4.676794376 97 5.18244704 100 5.521878863 118 6.316630137 131 6.778507504 147 7.020395216 157 7.331607129 176 7.637492223 202 7.848079136 223 7.989456499 251 8.76853608 278 9.092367123 ... ``` As you see, the measurements are sampled at irregular time points. I need to smooth the data by averaging the reading up to 100 seconds prior each measurement (in Python). Since the data table is huge, an iterator-based method is really preferred. Unfortunately, after two hours of coding I can't figure out efficient and elegant solution. Can anyone help me? **EDIT**s 1. I want one smoothed reading for each raw reading, and the smoothed reading is to be the arithmetic mean of the raw reading and any others in the previous 100 (delta) seconds. (John, you are right) 2. Huge ~ 1e6 - 10e6 lines + need to work with tight RAM 3. The data is approximately random walk 4. The data is sorted # RESOLUTION I have tested solutions proposed by J Machin and yairchu. They both gave the same results, however, on my data set, J Machin's version performs exponentially, while that of yairchu is linear. Following are execution times as measured by IPython's *%timeit* (in microseconds): ``` data size J Machin yairchu 10 90.2 55.6 50 930 258 100 3080 514 500 64700 2660 1000 253000 5390 2000 952000 11500 ``` Thank you all for the help.
I'm using a sum result to which I'm adding the new members and subtracting the old ones. However in this way one may suffer accumulating floating point inaccuracies. Therefore I implement a "Deque" with a list. And whenever my Deque reallocates to a smaller size. I recalculate the sum at the same occasion. I'm also calculating the average up to point x including point x so there's at least one sample point to average. ``` def getAvgValues(data, avgSampleTime): lastTime = 0 prevValsBuf = [] prevValsStart = 0 tot = 0 for t, v in data: avgStart = t - avgSampleTime # remove too old values while prevValsStart < len(prevValsBuf): pt, pv = prevValsBuf[prevValsStart] if pt > avgStart: break tot -= pv prevValsStart += 1 # add new item tot += v prevValsBuf.append((t, v)) # yield result numItems = len(prevValsBuf) - prevValsStart yield (t, tot / numItems) # clean prevVals if it's time if prevValsStart * 2 > len(prevValsBuf): prevValsBuf = prevValsBuf[prevValsStart:] prevValsStart = 0 # recalculate tot for not accumulating float precision error tot = sum(v for (t, v) in prevValsBuf) ```
You haven't said exactly when you want output. I'm assuming that you want one smoothed reading for each raw reading, and the smoothed reading is to be the arithmetic mean of the raw reading and any others in the previous 100 (delta) seconds. Short answer: use a collections.deque ... it will never hold more than "delta" seconds of readings. The way I've set it up you can treat the deque just like a list, and easily calculate the mean or some fancy gizmoid that gives more weight to recent readings. Long answer: ``` >>> the_data = [tuple(map(float, x.split())) for x in """\ ... 6 0.738158581 ... 21 0.801697222 [snip] ... 251 8.76853608 ... 278 9.092367123""".splitlines()] >>> import collections >>> delta = 100.0 >>> q = collections.deque() >>> for t, v in the_data: ... while q and q[0][0] <= t - delta: ... # jettison outdated readings ... _unused = q.popleft() ... q.append((t, v)) ... count = len(q) ... print t, sum(item[1] for item in q) / count, count ... ... 6.0 0.738158581 1 21.0 0.7699279015 2 39.0 1.112360133 3 49.0 1.52907127225 4 54.0 1.791208525 5 79.0 2.13137915133 6 91.0 2.49500989771 7 97.0 2.8309395405 8 100.0 3.12993279856 9 118.0 3.74976297144 9 131.0 4.41385300278 9 147.0 4.99420529389 9 157.0 5.8325615685 8 176.0 6.033109419 9 202.0 7.15545189083 6 223.0 7.4342562845 6 251.0 7.9150342134 5 278.0 8.4246097095 4 >>> ``` **Edit** One-stop shop: get your fancy gizmoid here. Here's the code: ``` numerator = sum(item[1] * upsilon ** (t - item[0]) for item in q) denominator = sum(upsilon ** (t - item[0]) for item in q) gizmoid = numerator / denominator ``` where upsilon should be a little less than 1.0 (<= zero is illegal, just above zero does little smoothing, one gets you the arithmetic mean plus wasted CPU time, and greater than one gives the inverse of your purpose).
smoothing irregularly sampled time data
[ "", "python", "datetime", "data-mining", "smoothing", "" ]
So I have a static class that is supposed to be used as a log file manager, capable of adding "messages" (strings) to a Queue object, and that will push messages out to a file. Trouble is, many different threads should be enqueueing, and that the writer needs to be async as well. Currently when I insert into the queue, I'm also checking to see if the writer is writing (bool check), if it's not, i set the bool and then start the writing, but I'm getting intermittent IO exceptions about file access, and then wierd writing behavior sometimes. Someone want to give me a hand on this?
It sounds like the queue is driving the file writing operation. I recommend that you invert the control relationship so that the writer drives the process and checks the queue for work instead. The simplest way to implement this is to add a polling mechanism to the writer in which it checks the queue for work at regular intervals. Alternately, you could create an observerable queue class that notifies subscribers (the writer) whenever the queue transitions from empty: the subscribing writer could then begin its work. (At this time, the writer should also unsubscribe from the queue's broadcast, or otherwise change the way it reacts to the queue's alerts.) After completing its job, the writer then checks the queue for more work. If there's no more work to do, it goes to sleep and resume polling or goes to sleep and resubscribes to the queue's alerts. As [Irwin noted in his answer](https://stackoverflow.com/questions/1064374/multi-threaded-file-write-enqueueing/1064466#1064466), you also need to use the thread-safe wrapper provided by the `Queue` class' `Synchronized` method or manually synchronize access to your `Queue` if multiple threads are reading from it and writing to it ([as in SpaceghostAli's example](https://stackoverflow.com/questions/1064374/multi-threaded-file-write-enqueueing/1064525#1064525)).
If you don't want to restructure your code dramatically like I suggested in my other answer, you could try this, which assumes your `LogManager` class has: * a static thread-safe queue, `_SynchronizedQueue` * a static object to lock on when writing, `_WriteLock` and these methods: ``` public static void Log(string message) { LogManager._SynchronizedQueue.Enqueue(message); ThreadPool.QueueUserWorkItem(LogManager.Write(null)); } // QueueUserWorkItem accepts a WaitCallback that requires an object parameter private static void Write(object data) { // This ensures only one thread can write at a time, but it's dangerous lock(LogManager._WriteLock) { string message = (string)LogManager._SynchronizedQueue.Dequeue(); if (message != null) { // Your file writing logic here } } } ``` There's only one problem: the lock statement in the `Write` method above will guarantee only one thread can write at a time, but this is dangerous. A lot can go wrong when trying to write to a file, and you don't want to hold onto (block) thread pool threads indefinitely. Therefore, you need to use a synchronization object that lets you specify a timeout, such as a `Monitor`, and rewrite your `Write` method like this: ``` private static void Write() { if (!Monitor.TryEnter(LogManager._WriteLock, 2000)) { // Do whatever you want when you can't get a lock in time } else { try { string message = (string)LogManager._SynchronizedQueue.Dequeue(); if (message != null) { // Your file writing logic here } } finally { Monitor.Exit(LogManager._WriteLock); } } } ```
Multi-threaded file write enqueueing
[ "", "c#", "multithreading", "file-io", "" ]
Now I'm sure this is super easy, I have a function called "remove\_deposit" which I want it to make the checkbox false if it's true. But I can't seem to get it to work.. ``` function remove_deposit() { if(document.getElementById('deposit').checked == true) { document.getElementById('deposit').checked == false; }; }; ``` Am I at least on the right track?? lol
``` function remove_deposit() { if(document.getElementById('deposit').checked == true) { document.getElementById('deposit').checked = false; }; }; ``` You were doing a comparison instead of simply setting the checked attribute to false.
``` function remove_deposit() { document.getElementById('deposit').checked = false } ``` That's all you need. The reason why your code wasn't working was because you used two equals signs, which is a comparison operator, instead of one equals sign, which is the assignment operator. **Addendum:** I removed the if statement since it doesn't really do anything useful afaict. If you did this to optimize the code, then I'd just like to point out that checking the if statement will probably be slower than just setting the checkbox to false. Also, you don't need to end every line with a semi-colon in JavaScript. You can do that if you want to put multiple commands on a single line, but otherwise it's not necessary. Results are in. If most of the time people running the javascript to set the checkbox to false do have the checkbox set to true, skipping the if statement is faster. Otherwise, if most of the time the checkbox is set to false, then the if statement would be faster. With a 1:1 ratio, no if statement is preferred. The checkbox would have to be set to false at least 54% of the time for the if code to be more efficient. [http://img33.imageshack.us/img33/4260/results.png http://img33.imageshack.us/img33/4260/results.png](http://img33.imageshack.us/img33/4260/results.png) **Side-note:** If it's a checkbox, it's probably in a form, so you could also access it with the old-fashioned method document.formName.elementName instead of document.getElementById(). Because the form method doesn't need to traverse the DOM like getElementById does, I think that would be faster. The results are in. With 0 IDs preceding it, document.test\_form.checkbox (DTFC) is slower than document.getElementById('checkbox') (GEBI). With 100 IDs preceding it, document.test\_form.checkbox is still slower than document.getElementById('checkbox'). [http://img8.imageshack.us/img8/6683/resultsw.png http://img8.imageshack.us/img8/6683/resultsw.png](http://img8.imageshack.us/img8/6683/resultsw.png) I guess that settles it. **PS:** These were all tested on Firefox using Firebug. I cannot make any claims about the efficiency of Safari's WebKit, Konqueror's KJS, IE's proprietary engine, or Google Chrome's V8. I'm guessing they should wind up somewhat similar to these, but they could be different.
javascript onclick remove single checkbox
[ "", "javascript", "function", "" ]
Dupe of [calculate playing time of a .mp3 file](https://stackoverflow.com/questions/1090507/calculate-playing-time-of-a-mp3-file) im reading a audio file(for ex:wav,mp3 etc) and get a long value as duration.now i want to convert that long value into correct time duration(like,00:05:32)
Depending on exactly what the `long` represents, you could probably use one of the [`TimeSpan` constructor overloads](http://msdn.microsoft.com/en-us/library/system.timespan.timespan.aspx) to get a `TimeSpan` object representing the duration of the sound file. Assuming the `long` represents milliseconds: ``` long soundLength = GetSoundLength(); TimeSpan duration = new TimeSpan(0, 0, 0, 0, soundLength); Console.WriteLine("{0} minutes and {1} seconds", duration.Minutes, duration.Seconds); ``` Edit: fixed the contstructor call; it was one parameter short.
First you should determine what it is that you are receiving as input. Then you can convert this into a TimeSpan object which is easy to work with and display onscreen. See <http://msdn.microsoft.com/en-us/library/system.timespan.aspx> for more information.
calculating time duration of a file
[ "", "c#", "file", "audio", "" ]
I have two geo-spatial simple convex polygon areas, in latitudes and longitudes (decimal degrees) that I want to compute using Javas Polygon class. I basically want to see if these two lat,long polygons intersect, and to calculate the areas (in sq meters) of both. Now java.awt.Polygon class only uses x,y co-ordinate system, but I need to use lats,longs. How can I do this, and/or is there any other classes/libraries available?
All you need to do is convert [from spherical to rectangular coordinates](http://www.math.ucsd.edu/~byeap/math20c/math20cw2007/lecturenotes_files/06_02_06_F_20C.pdf) if you think that really matters. I'm not sure that it does, because the java.awt.Polygon is merely a data structure holding for *pairs of values*. If you read the javadocs, they say > The Polygon class encapsulates a description of a closed, two-dimensional region within a coordinate space. This region is bounded by an arbitrary number of line segments, each of which is one side of the polygon. Internally, a polygon comprises of a list of (x,y) coordinate pairs, where each pair defines a vertex of the polygon, and two successive pairs are the endpoints of a line that is a side of the polygon. The first and final pairs of (x,y) points are joined by a line segment that closes the polygon. They happen to label those points as x and y, which makes all of us think rectangular coordinates, but they need not be from your point of view. A bug on the service of your sphere would view it as a 2D space. Your radius is large and constant. You just can't count on using any of Polygon's methods (e.g., contains(), getBounds2D(), etc.) In this case, the important thing is your area calculation. You can use a Polygon for your area calculation, storing lats and longs, as long as you view Polygon as a data structure. You might also thing of abandoning this idea and writing your own. It's not too hard to create your own Point and Polygon for spherical coordinates and doing it all with that coordinate system in mind from the start. Better abstraction, less guessing for clients. Your attempt to reuse java.awt.Polygon is admirable, but not necessary. You can perform the area calculation easily by converting it to a contour integral and using Gaussian quadrature to integrate along each straight line boundary segment. You can even include the curvature of each segment at each integration point, since you know the formula.
Why not use `Polygon` class multiplying coordinates for 10^n making them integers? `Polygon` accepts arrays of int as points. Just an Idea
How to use Javas Polygon class with lat,longs
[ "", "java", "" ]
I have a method I'm writing that uses reflection to list a class's static properties, but I'm only interested in those that are of a particular type (in my case, the property must be of a type derived from DataTable). What I would like is something like the if() statement in the following (which presently always returns true): ``` PropertyInfo[] properties = ( typeof(MyType) ).GetProperties( BindingFlags.Public | BindingFlags.Static ); foreach( PropertyInfo propertyInfo in properties ) { if( !( propertyInfo.PropertyType is DataTable ) ) continue; //business code here } ``` Thanks, I'm stumped.
You need to use [Type.IsAssignableFrom](http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx) instead of the "is" operator. This would be: ``` if( !( DataTable.IsAssignableFrom(propertyInfo.PropertyType) ) ``` `DataTable.IsAssignableFrom(propertyInfo.PropertyType)` will be true if PropertyType is a DataTable or a subclass of DataTable.
``` if( !( propertyInfo.PropertyType.isSubClassOf( typeof(DataTable) ) ) continue; ``` I think that should do it.
How do you use the IS operator with a Type on the left side?
[ "", "c#", "reflection", "static", "properties", "types", "" ]
I want to create my own IM and I'm searching an open-source IM APIs. What do you think is the best open-source IM APIs. And what good front end to use? Thanks.
If you are looking into making a client, check out libpurple. This is what pidgin and many other IM clients use to access multiple IM networks. <http://developer.pidgin.im/wiki/WhatIsLibpurple> If you are just worried about one IM network, the easiest one to work with would be Jabber because it is an open sourced protocol <http://www.jabber.org/>
XMPP... lots of documentation, libraries and so on. <http://xmpp.org>
OpenSource Instant Messaging APIs
[ "", "c++", "api", "open-source", "instant-messaging", "" ]
I have two tables, for example: ``` Table A Table B ======= ======= Name | Color Name | Color ---------------------- ---------------------- Mickey Mouse | red Mickey Mouse | red Donald Duck | green Donald Duck | blue Donald Duck | blue Minnie | red Goofy | black Minnie | red ``` Table A is my source table and B is the destination table. Now I need a query which finds all the different (additional) rows in table A so table B can be updated with those rows. So I need a query which finds me the following rows from table A: ``` Name | Color ---------------------- Donald Duck | green Goofy | black ``` What is a good approach for such a query? It should be as efficient as possible (avoid too many joins). Thanks for any help!
I would use a NOT EXISTS structure. ``` SELECT Name, Color FROM TableA WHERE NOT EXISTS ( SELECT 1 FROM TableB WHERE TableA.Name = TableB.Name AND TableA.Color = TableB.Color) ```
``` SELECT a.Name, a.Color FROM a LEFT OUTER JOIN b ON (a.Name = b.Name AND a.Color = b.Color) WHERE b.Name IS NULL AND b.Color IS NULL ```
SQL - Check table for new rows?
[ "", "sql", "" ]
I'm using $().post and php to change the contents of a <textarea>. The script is succeeding - firebug clearly shows that the text in between the textarea tags has changed, and my little alert fires. The user, however, doesn't see the changes. In Firefox the change doesn't occur at all, and in IE, the textarea updates up to 10 seconds late. Here's the jquery I'm using: ``` $(document).ready(function() { $('#pv_list li:first').addClass('hilite'); $("input[name='db_entries']:first").attr('checked', 'checked'); $("input[name='db_entries']").click(function () { $.post("changeEntry.php", {post: $(this).val()}, function(data) { $("textarea").text(data);alert('done'); }); $('#pv_list li').removeClass('hilite'); $(this).parent().addClass('hilite'); }); }); ``` At first I thought it was because the page didn't validate, but it validates xhtml transitional. The thing that's really bugging me is I had it working earlier and can't figure out what I changed.
Have you tried using [val()](http://docs.jquery.com/Attributes/val) to set the value of the textarea instead of text()? ``` $.post("changeEntry.php",{post: $(this).val()}, function(data) { $("textarea").val(data); alert('done'); }); ```
Set `.val()` instead of `.text()` Stackoverflow Archive: * [Set Value of Textarea in jQuery](https://stackoverflow.com/questions/415602/set-value-of-textarea-in-jquery) * [Insert text into textarea with jQuery](https://stackoverflow.com/questions/946534/insert-text-into-textarea-with-jquery) * [How to retrieve the value of a textarea with Javascript](https://stackoverflow.com/questions/873536/how-to-retrieve-the-value-of-a-text-area-in-javascript) * [Appending input-value to textarea-value](https://stackoverflow.com/questions/913042/append-input-to-textarea-as-being-types-in-jquery)
jquery.post() and php
[ "", "php", "jquery", "" ]
Lets say for example: ``` $(".button").click(function() { $.post("commandrunner.php", { param1: 'value', param2: 'value2', param3: 'value3' }, function(data, textStatus) { $(this).parent().after('<p>button clicked</p>'); }, "json" ); }); ``` I ran this and it didn't work. I tried a couple of things before I theorized the callback wasn't being invoked in the context of this particular ".button" and so $(this) was useless. This worked instead: ``` $(".button").click(function() { var thisButton = $(this); $.post("commandrunner.php", { param1: 'value', param2: 'value2', param3: 'value3' }, function(data, textStatus) { thisButton.parent().after('<p>button clicked</p>') }, "json" ); }); ``` This feels like a bit of a hack. Is this the right way to get a reference to the clicked on button? And what context is that (or any other callback) invoked in? Thanks! Ali
What you've noticed here is the way JavaScript closures work. As in other OO languages, when a method is invoked, it has a "this", which is similar to Java's `this` or Ruby's `self`. However, the JavaScript `this` is remarkably malleable, and jQuery takes advantage of that property to set it to a useful value when it calls your callback. In the case of events, jQuery sets the `this` pointer to point at the element that you bound the event handler to. Check this out: ``` var hello = function() { console.log("Hello " + this); }); ``` If you come from an OO background, you might look at the above snippet in bewilderment: what does `this` point to. By default, it will point at the global object (window in browsers). But you can easily override that: ``` hello.call("world") // will print "Hello world" ``` Call takes multiple arguments after the `this` which are passed in as arguments. A similar method, called `apply`, will also take a `this` as the first argument, but takes an Array of arguments as the second parameter. Now, if we look at your example again: ``` $(".button").click(function() { $.post("commandrunner.php", { param1: 'value', param2: 'value2', param3: 'value3' }, function(data, textStatus) { $(this).parent().after('<p>button clicked</p>') }, "json" ); }); ``` The issue here is that when jQuery called the function again, it did not call it with the same `this`. When you create an anonymous function, it will hold onto all **local** variables in the same scope, but not `this`, which is set by JavaScript itself (to the global object) or overridden when called. As a result, the solution is to store off a pointer to `this` in a local variable, which will then be available to the closure. The solution, as mentioned above, is: ``` $(".button").click(function() { var parent = $(this).parent(); $.post("commandrunner.php", { param1: 'value', param2: 'value2', param3: 'value3' }, function() { parent.after('<p>button clicked</p>') }, "json" ); }); ``` In general, when I store off a local, I store off the most specific set of elements I can, to make the callback code simpler. The common jQuery idiom is to do `var self = this`, which is perfectly fine as well. Also note that JavaScript functions do not check the number of parameters, so it's perfectly legal to leave the parameters empty if you do not **use** them. They will still be passed in, but the empty parameter list will simply be ignored.
According to [jquery api](http://api.jquery.com/jQuery.ajax/) (under "Callback Function Queues") the `this` object in any JQuery AJAX callback function will automatically point to the settings of the ajax object or - if specified - the `context` object. Sadly you cannot specify a `context` in $.post().
What context is the jQuery.post callback function invoked in?
[ "", "javascript", "jquery", "" ]
I screwed up my last post. Lets see if I can get this one right.. Would anyone be able to tell me how to pull the server name out of a UNC? (I'm looking for a regex) this is the string I want to pull the servername from: ``` **\\\servername\d$\directory** ``` My Code is in C# ``` Regex r = new Regex(?????, RegexOptions.IgnoreCase); Match m = r.Match(@"\\servername\d$\directory"); CaptureCollection cc = m.Captures; foreach (Capture c in cc) { System.Console.WriteLine(c); } ``` I am looking to capture just: servername no slashes or anything.
**Note: This answer is for education purposes - better to use the Uri object and not re-invent existing functions.** Same solution as on [the other question](https://stackoverflow.com/questions/1053216/regular-expressions-how-to-pull-the-server-name-from-a-unc), but with backslashes reversed, and therefore escaped, (and possessive quantifier removed, since C# regex doesn't support that): ``` (?<=^\\\\)[^\\]+ ``` The server name will be in `\0` or `$0` or simply the result of the function, depending on how you call it and what C# offers. Explanation in regex comment mode: ``` (?x) # flag to enable regex comments (?<= # begin positive lookbehind ^ # start of line \\\\ # escaped backslashes to give literal \\ chars. ) # end positive lookbehind [^\\]+ # greedily match any non-\ until a \ or end of string found. ```
Why use regex when `Uri` will do it too? ``` Uri uri = new Uri(@"\\servername\d$\directory"); Console.WriteLine(uri.Host); // servername Console.WriteLine(uri.IsUnc); // true ```
need a c# regex to get servername out of UNC
[ "", "c#", "regex", "url", "uri", "unc", "" ]
If I run my JBoss application from the Windows command prompt I can get the list of printers (including networked printers just fine). If I run my JBoss application as a Windows service, I only get the list of printers that are directly connected to the machine. The networked printers don't show up. Here is the Java code I use to get the list of printers: ``` PrintService[] printerServices = PrintServiceLookup.lookupPrintServices(null, null); ``` It doesn't appear to be a permissions problem, since according to our administrator, the permissions are setup just fine. Does some have a better explanation, or is there a set of permissions that might be required to get the networked printers to show up?
You have to run the windows service as a user on the domain that has the appropriate permissions, not as LocalUser. You can also add networked printers using a tcp/ip connection, and the problem goes away.
My colleague had this very same problem just minutes ago, but on a REDHAT LINUX system. His server had been rebooted and printer functionality worked only half way; lp worked, cups worked, but no access to printers from Java. He found out localhost had disappeared from the hosts file. His solution: add localhost to hosts file (but since you are on windows, this might not be your solution)
Java Print Service: PrintServiceLookup.lookupPrintServices does not return networked printers
[ "", "java", "windows", "printing", "service", "" ]
I tried running a python script: ``` print "Hello, World!" ``` And I get this error: ``` File "hello.py", line 1 print "Hello, World!" ^ SyntaxError: invalid syntax ``` What is going on?
``` print("Hello, World!") ``` You are probably using Python 3.0, where `print` is [now a function](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function) (hence the parenthesis) instead of a statement.
Unfortunately the [xkcd comic](http://xkcd.com/353/) isn't completely up to date anymore. [![https://imgs.xkcd.com/comics/python.png](https://imgs.xkcd.com/comics/python.png "I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I'm leaving you.")](http://xkcd.com/353/) Since Python 3.0 you have to write: ``` print("Hello world!") ``` And someone still has to write that `antigravity` library :(
Hello World in Python
[ "", "python", "python-3.x", "" ]
I have to create a special TextFieldUI that draws an image as the background. That image contains some alpha components. However, whenever a character is written in that text field, first it redraws the background and then draws the character. This is fine when the background contains no alpha components, but after a few characters have been typed, the alpha areas sum up to become black. The only way I can see around this is in the paintBackground method of TextfieldUI (which I'm overriding), I have to first sample the color of the background at that location, paint the entire graphics component that color, and then paint my background. 1. Does anyone know how to sample the color of a pixel when all I have access to is the Graphics object? 2. Is there a better way to draw a custom image as the textfield background other than overriding paintBackground in TextfieldUI? Thanks
I haven't tried it before, but Swing is built on top of AWT, and the [Robot](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Robot.html#getPixelColor%28int,%20int%29) class had a way of sampling specific pixels in the AWT
Well, I don't know what your custom code looks like in the paintBackground method, but I would make sure you fill in the text field background before you draw the image. I'll let you decide if its "better" or not, but you can use the [Background Panel](http://tips4java.wordpress.com/2008/10/12/background-panel/) which allows you to add an image to a panel. Then you add the text field to the panel (the text field is automatically made non-opaque so the image shows through). Then you add the panel to the GUI. If that doesn't work then it would be nice to have a demo of your code so we can see whats actually happening.
Java sampling pixel color in swing
[ "", "java", "swing", "" ]
I am trying to get a web app made on Zend Framework up but am encountering this error Warning: require\_once(Zend/Loader.php) [function.require-once]: failed to open stream: No such file or directory in /var/www/worm/index.php on line 17 Fatal error: require\_once() [function.require]: Failed opening required 'Zend/Loader.php' (include\_path='/var/worminc/application/../library') in /var/www/worm/index.php on line 17 Please suggest the possible solutions?
I don't think you've configured your LIB\_PATH correctly. At the top of your bootstrap put: ``` define('LIB_PATH', '/full/path/to/Library'); //Zend Framework is in Library set_include_path(LIB_PATH . PATH_SEPARATOR . get_include_path()); require_once('Zend/Loader.php'); ```
If the system cannot find something - first you have to find out where it is looking for it. ``` echo get_include_path(), "\n"; die; ``` Look in the directories it shows, and if the directory 'Zend/' is not there, you know what is wrong.
Zend framework web app not coming up?
[ "", "php", "zend-framework", "loader", "" ]
I host my site with GoDaddy , and I use the PHP `mail()` function at the moment to send form mails from my site. GoDaddy has a 1000 SMTP relay limit per day for form mail stuff, but they swear that with my PHP script that I should not be touching it. 1. Since `mail()` doesn't take SMTP info, does it just automatically use GoDaddy's (or whatever hosting you may be on)? 2. If my site is going to be expecting more than 1000 emails sent out a day (separate instances, not in a loop), should I be using a different method, or is `mail()` the right choice?
Php uses by default, the local mail-server. However you can specify this in your php.ini configuration file. If you expect to send more email than that, you might want to look into finding a different server to mail from, or alternative hosting
Dont use mail() function of php it will send your mail to junk only. Instead use SMTP php mailer function. **Why we should use SMTP instead PHP mail():** **SMTP** log in to an actual account on a mailserver and send the mail through SMTP to another mail server. If the mail server is configured correctly, your mails are sent from an actual account on a mailserver and will not wind up flagged as spam. **Mail** sent with the mail() function is sent with sendmail in most cases. There is no authentication going on and it will almost always be flagged as spam if you use the "From:" in the extra headers. This is because if you take a look at an original email file in say, gmail, you will see the headers that are sent. You are actually sending from user@serverhostname.tld and not someone@example.com like you had told the mail function to do. If you use SMTP and view the original the email is actually sent from someone@example.com You can download SMTP class from: 1. <https://code.google.com/a/apache-extras.org/p/phpmailer/source/browse/trunk/class.smtp.php?r=170> 2. <http://www.phpclasses.org/package/14-PHP-Sends-e-mail-messages-via-SMTP-protocol.html>
What SMTP server does PHP mail() use by default, and are there better options?
[ "", "php", "email", "" ]
I don't know the name for this, if did i would search for it. I wanted something like this, i think its uses javascript but I'm not sure how to do it know. In a web page you have 2 listboxs, its content comes from mysql. There is 2 tables in the database, for each listbox, they are both related. Then when you select a item from the listbox 1 we dynamically loads the options for listbox 2 based on the selection you made in listbox1, and if you change the selection it listbox 1 he also changes the options for listbox 2. I think i've expressed correctly, if its confused just say it. Thanks for the help once again.
<http://remysharp.com/2007/09/18/auto-populate-multiple-select-boxes/> is a jquery plugin using PHP and mySQL Josh
Sounds like you are looking for some combination of Ajax + Server side language + MySQL. Ajax can be handled with: - jQuery - Mootools - Home brew XmlHttpResponse Server side can be: - C# - Java - PHP - Ruby Using JavaScript to attach to the onChange event of the first list box, you would then use ajax to get the second listbox contents (based on the selected item in the first list)
Load options for listbbox from Mysql to listbox, controled by other list - Javascript
[ "", "javascript", "mysql", "html", "" ]
I have checked my PHP ini file (`php.ini`) and `display_errors` is set and also error reporting is `E_ALL`. I have restarted my Apache webserver. I have even put these lines at the top of my script, and it doesn't even catch simple parse errors. For example, I declare variables with a `"$"` and I don't close statements`";"`. But all my scripts show a blank page on these errors, but I want to actually see the **errors** in my browser output. ``` error_reporting(E_ALL); ini_set('display_errors', 1); ``` What is left to do?
### DEV environment This always works for me: ``` ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); error_reporting(E_ALL); ``` However, this doesn't make PHP to show parse errors occurred in the same file. Also, these settings can be overridden by PHP. In these cases the only way to show those errors is to modify your php.ini (or php-fpm.conf) with this line: ``` display_errors = on ``` (if you don't have access to `php.ini`, then putting this line in `.htaccess` might work too): ``` php_flag display_errors 1 ``` ### PROD environment Note that above recommendation is only suitable for the DEV environment. On a live site it must be ``` display_errors = off log_errors = on ``` And then you'll be able to see all errors in the error log. See [Where to find PHP error log](https://stackoverflow.com/q/5127838/285587) ### AJAX calls In case of AJAX call, on a DEV server, open DevTools (F12), then Network tab. Then initiate the request which result you want to see, and it will appear in the Network tab. Click on it and then the Response tab. There you will see the exact output. While on a live server just check the error log all the same.
You can't catch parse errors in the same file where error output is enabled at runtime, because it parses the file before actually executing anything (and since it encounters an error during this, it won't execute anything). You'll need to change the actual server configuration so that display\_errors is on and the approriate error\_reporting level is used. If you don't have access to php.ini, you may be able to use .htaccess or similar, depending on the server. [This question](https://stackoverflow.com/questions/78296/reasons-why-php-would-echo-errors-even-with-errorreporting0) may provide additional info.
How do I get PHP errors to display?
[ "", "php", "error-handling", "syntax-error", "error-reporting", "" ]
I have a template file in a folder " c:\template\_folder". At runtime, I will create a new folder " c:\new\_folder" and wish to copy the template file to the new\_folder only if the file doesnt exist. description: for the first time, I will copy the template file to the new\_folder and rename it with username... so that after first time the loop finishes, i will have 8 excel files with username as the name of the each file. for the second loop, if I have to copy the template file to new\_folder and rename it to the username, if the file with the user name already exists, then it shouldnt copy the file to the folder. I am addin the snippet of the code for reference. ``` foreach (FileInfo fi in templateFile) { string oldfilename = null; string newfilename = null; if (dir.Exists) { fi.CopyTo(Path.Combine(dir.ToString(), fi.Name)); FileInfo fileName = new FileInfo(fi.Name); oldfilename = Path.Combine(dir.ToString(), fileName.ToString()); newfilename = Path.Combine(dir.ToString(), tempUserName + " " + "E" + tempUserID + " VIPv7.0.xls"); //if( !dir.ToString().Contains(newfilename)) foreach( FileInfo fileList in fileNames) { if (fileList.Exists == false) File.Move(oldfilename, newfilename); } } } ``` please help me in working this. thanks ramm
To conditionally move a file only if it doesn't already exist you would do it like this: ``` if (!File.Exists(newfilename)) { File.Move(oldfilename, newfilename); } ``` Your code snippet confuses me, so I hope I've answered your question correctly. If I'm missing something please let me know.
Your code doesn't seem correct to me (it doesn't compile), but you can check if a file exists by calling File.Exists(filename), so: ``` foreach( FileInfo fileList in fileNames) { if (!File.Exists(newfilname)) File.Move(oldfilename, newfilename); } ```
How to Add file to the folder only if the file doesnt exist using C#
[ "", "c#", ".net", "filesystems", "" ]
I have an application that has two threads. The first one (the main thread) that captures the data using socket and update DataTables The second Inserts the DataTables into the database. The application works fine but when it closes, the main thread finishes reading the data and call Abort method in the second thread, which may be inserting into database and this leads to inconsistent data. Currently I am using the following solution to overcome "aborting during insertion" EDIT: After the powerful answers I changed the code ``` void MainThread() { while(Read()) { //Read Data through socket try { //Wait on Mutex1 //Update Tables } finally { //Release Mutex1 } } _isrunning = false; _secondThread.Join(); } void SecondThread() { while(_isrunning) { try { //Wait on Mutex1 //Insert Tables into Database using transactions } finally { //Release Mutex1 } } } ```
Assuming "call abort method" means aborting the thread using Thread.Abort. [Don't do that](http://haacked.com/archive/2004/11/12/how-to-stop-a-thread.aspx). You are effectively crashing your app. There are plenty cleaner ways of doing this with Monitors. Nonetheless, you should not be getting inconsistent data in your DB when your app crashes that's why you have DB transactions which have the [ACID](http://en.wikipedia.org/wiki/ACID) properties. **VERY IMPORTANT EDIT** You said: you do not use transactions for performance reasons, and instead use mutexes. This is **WRONG** on quite a few levels. Firstly, transactions can make certain operations faster, for example try inserting 10 rows into a table, try it again within a transaction, the transaction version will be faster. Secondly, what happens when/if your app crashes, do you corrupt your DB? What happens when multiple instances of your app are running? Or while you run reports against your DB in query analyzer?
As long as both threads are not marked as background threads, the app will keep running until both threads exit. So really, all you need to do is to get each thread separately to exit cleanly. In the case of the thread that writes to the database, this may mean exhausting a producer/consumer queue and checking a flag to exit. I showed a suitable producer/consumer queue [here](https://stackoverflow.com/questions/530211#530228) - the worker would just be: ``` void WriterLoop() { SomeWorkItem item; // could be a `DataTable` or similar while(queue.TryDequeue(out item)) { // process item } // queue is empty and has been closed; all done, so exit... } ``` --- Here's a full example based on `SizeQueue<>` - note that the process doesn't exit until the reader **and** writer have exited cleanly. If you don't want to have to drain the queue (i.e. you want to exit sooner, and forget any pending work), then fine - add an extra (volatile) flag somewhere. ``` static class Program { static void Write(object message) { Console.WriteLine(Thread.CurrentThread.Name + ": " + message); } static void Main() { Thread.CurrentThread.Name = "Reader"; Thread writer = new Thread(WriterLoop); writer.Name = "Writer"; var queue = new SizeQueue<int>(100); writer.Start(queue); // reader loop - note this can run parallel // to the writer for (int i = 0; i < 100; i++) { if (i % 10 == 9) Write(i); queue.Enqueue(i); Thread.Sleep(5); // pretend it takes time } queue.Close(); Write("exiting"); } static void WriterLoop(object state) { var queue = (SizeQueue<int>)state; int i; while (queue.TryDequeue(out i)) { if(i%10==9) Write(i); Thread.Sleep(10); // pretend it takes time } Write("exiting"); } } ```
Gracefully closing multithreading application?
[ "", "c#", "database", "multithreading", "application-close", "" ]
Consider the following: ``` typedef struct { int a; int b; int c; int d; } ABCD; typedef std::vector<ABCD> VecABCD; ``` Say I wanted to add up every 'a' member in a vector of type VecABCD. Easy! I just loop through the vector, and sum as I go. ``` int CalcSumOfA(const VecABCD &vec) { int sumOfA = 0; VecABCD::const_iterator it; for(it=vec.begin();it!=vec.end();it++) sumOfA += it->a; return sumOfA; } ``` Say I wanted to do the same thing with 'b'? Easy! I'd write....essentially the same function, but with only trivial changes. Same with 'c' and 'd'. So, is there a more concise, less repetitive way of doing this? I'd like to do something like: ``` int sumOfA = SumOfMembers(myVec, a); ``` but I can't conceive of how I'd put such a function together. Ideally, it'd be a template, and I could use it with a vector of any kind of structure, not specifically bound to VecABCD. Anyone have any ideas?
STL summations can be done with [`std::accumulate`](http://en.cppreference.com/w/cpp/algorithm/accumulate) ``` #include <functional> accumulate(v.begin(), v.end(), 0, bind(plus<int>(), _1, bind(&ABCD::a, _2))) ``` If you wanted this to be more generic, you could take a tr1::function to the member you want to bind: ``` int sum_over_vec(const vector<ABCD>& v, const tr1::function<int (const ABCD&)>& member) { return accumulate(v.begin(), v.end(), 0, bind(plus<int>(), _1, bind(member, _2))); }; // ... int sum_a = sum_over_vec(vec, bind(&ABCD::a, _1)); ``` --- Another way to do it, rather than putting your logic in the functor, would be to put the logic in the iterator, using a boost::transform iterator: ``` tr1::function<int (const ABCD&)> member(bind(&ABCD::a, _1)); accumulate(make_transform_iterator(v.begin(), member), make_transform_iterator(v.end(), member), 0); ``` **EDITED TO ADD: C++11 lambda syntax** This becomes somewhat clearer with the C++11 lambdas (though unfortunately not shorter): ``` accumulate(v.begin(), v.end(), 0, [](int sum, const ABCD& curr) { return sum + curr.a }); ``` and ``` int sum_over_vec(const vector<ABCD>& v, const std::function<int (const ABCD&)>& member) { return accumulate(v.begin(), v.end(), 0, [&](int sum, const ABCD& curr) { return sum + member(curr}); }); }; ``` Usage: ``` // Use a conversion from member function ptr to std::function. int sum_a = sum_over_vec(vec, &ABCD::a); // Or using a custom lambda sum the squares. int sum_a_squared = sum_over_vec(vec, [](const ABCD& curr) { return curr.a * curr.a; }); ```
Another option would be to use pointer-to-members: ``` int CalcSumOf(const VecABCD & vec, int ABCD::*member) { int sum = 0; for(VecABCD::const_iterator it = vec.begin(), end = vec.end(); it != end; ++it) sum += (*it).*member; return sum; } ... int sumA = CalcSumOf(myVec, &ABCD::a); // find sum of .a members int sumB = CalcSumOf(myVec, &ABCD::b); // find sum of .b members // etc. ```
Summing struct members inside a vector
[ "", "c++", "stl", "" ]
I am trying to write a program that displays the integers between 1 and 100 that are divisible by either 6 or 7 **but not both**. Here is my code: ``` import acm.program.*; public class Problem4 extends ConsoleProgram { public void run() { for (int i = 1; i <= 100; i++) { boolean num = ((i % 6 == 0) || (i % 7 == 0)); if (num == true) println(i + " is divisible"); } } } ``` The above code shows the following answers: 6,7,12,14,18,21,24,28,30,35,36,**42**,48,49,54,56,60,63,66,70,72,77,78,**84**,90,91,96,98 Now the bold numbers 42 and 84 are both divisbile by 6 and 7. Now If I change the `||` to `&&` in the above code, the result shows only 42 and 84. What change should I do to remove these 2 numbers from the final result?
you have to make your condition look like: ``` boolean num = (i % 6 == 0 || i % 7 == 0) && !(i % 6 == 0 && i % 7 == 0); ``` that's basically converting "*but not both*" to Java code :)
XOR is the way to go. ``` import acm.program.*; public class Problem4 extends ConsoleProgram { public void run() { for (int i = 1; i <= 100; i++) { if ( (i % 6 == 0) ^ (i % 7 == 0) ) { println(i + " is divisible"); } } } } ```
Finding integers that are divisible by 6 or 7 but not both
[ "", "java", "integer-division", "" ]
I have run into a situation where I want to ensure that a compound element of a table is unique. For example: ``` Table ( id char(36) primary key, fieldA varChar(12) not null, fieldB varChar(36) not null ) ``` I don't want fieldA and fieldB to be a compound primary key, since they change frequently, and 'id' is used as a reference throughout the system. fieldA and fieldB are not unique in and of themselves, but their combinations need to be unique. So for example, {{1, Matt, Jones}, {2, David, Jones}, {3, Matt, Smith}} would be valid data, but {{1, Matt, Jones}, {2, Matt, Jones}} would not be.
Add a UNIQUE key to your table definition: ``` Table ( id char(36) primary key, fieldA varChar(12) not null, fieldB varChar(36) not null, UNIQUE fieldA_fieldB (fieldA, fieldB) ) ```
You can add an UNIQUE key constraint on the two fields: ``` ALTER TABLE `table_name` ADD UNIQUE ( `fieldA`, `fieldB` ); ```
How can I enforce compound uniqueness in MySQL?
[ "", "sql", "mysql", "database-design", "" ]
I've a bash script that sequentially calls a java program. That's a bit tricky but mainly what i do is to have a loop and executes about 1500 times the same java program with different arguments. My question is, when using java 1.5 (the sun VM), each time I'm calling the java program a new instance of the jvm is created ? (I'm not sure that's the right vocabulary...) Should I avoid this situation by introducing a level of indirection, i.e building a list of all the parameters and then executing one java program which takes these parameters and executes what was previously my entry point ? Or can I deal with the problem by configuring the JVM as resident or something like that and dynamically invokes my program.... hope this is clear.... thx...
You could save the parameters into a file and use the Java program to process it without constant restart. You could also pipe in the parameters into the running Java app through the console, similarly as for example `ls | grep java` **Edit:** And for the first question. I doubt the java runtime would stay deliberately in memory. Probably most JRE files would remain in the disk cache anyway. On Windows there is a Java Quick Start service which keeps the JRE files around to reduce the startup time for a java program. Don't know whether there is a similar thing for \*nix.
JVM startup is notoriously slow, and it certainly not intended to be done in a loop like that. Unfortunately the only way to avoid this if you are passing command line parameters to the java program is to modify the java program itself in some way to have alternative forms of interaction (either from the console, or a port, or a read a file). Java Quick Start is the only (closest thing to a) solution if the java program cannot be changed. The real solution is to change the Java program. The most obvious change would be to have your loop write to a file, and then start the java program that would read the file one line at a time. That works if the loop doesn't care about the results from the java program for the next set of parameters. If it does, then it would really be necessary to understand that relationship to advise on an appropriate solution. The socket solution suggested by Savvas is certain a general purpose solution, but there may be better options, depending on what you need to accomplish.
Sequential execution of java programs == sequential activation of the jvm?
[ "", "java", "jvm", "" ]
There is simple JSON serialization module with name "simplejson" which easily serializes Python objects to JSON. I'm looking for similar module which can serialize to XML.
<http://code.activestate.com/recipes/415983/> <http://sourceforge.net/projects/pyxser/> <http://soapy.sourceforge.net/> <http://www.ibm.com/developerworks/webservices/library/ws-pyth5/> <http://gnosis.cx/publish/programming/xml_matters_1.txt>
There is [`huTools.structured.dict2xml`](https://github.com/hudora/huTools/blob/master/huTools/structured.py#L171) which tries to be compatible to `simplejson` in spirit. You can give it hints how to wrap nested sub-structures. Check the documentation for [`huTools.structured.dict2et`](https://github.com/hudora/huTools/blob/master/huTools/structured.py#L99) which returns `ElementTree` Objects instead if the strings returned by `dict2xml`. ``` >>> data = {"kommiauftragsnr":2103839, "anliefertermin":"2009-11-25", "prioritaet": 7, ... "ort": u"Hücksenwagen", ... "positionen": [{"menge": 12, "artnr": "14640/XL", "posnr": 1},], ... "versandeinweisungen": [{"guid": "2103839-XalE", "bezeichner": "avisierung48h", ... "anweisung": "48h vor Anlieferung unter 0900-LOGISTIK avisieren"}, ... ]} >>> print ET.tostring(dict2et(data, 'kommiauftrag', ... listnames={'positionen': 'position', 'versandeinweisungen': 'versandeinweisung'})) '''<kommiauftrag> <anliefertermin>2009-11-25</anliefertermin> <positionen> <position> <posnr>1</posnr> <menge>12</menge> <artnr>14640/XL</artnr> </position> </positionen> <ort>H&#xC3;&#xBC;cksenwagen</ort> <versandeinweisungen> <versandeinweisung> <bezeichner>avisierung48h</bezeichner> <anweisung>48h vor Anlieferung unter 0900-LOGISTIK avisieren</anweisung> <guid>2103839-XalE</guid> </versandeinweisung> </versandeinweisungen> <prioritaet>7</prioritaet> <kommiauftragsnr>2103839</kommiauftragsnr> </kommiauftrag>''' ```
Serialize Python dictionary to XML
[ "", "python", "xml", "serialization", "xml-serialization", "" ]
We have a web application that until now installed under the "Default Web Site" in IIS. A customer now wants us to install it under a different web site, and we want to do that from the installer. My question is in 2 parts: A) How do I programatically add another web site alongside the 'default web site'? B) We are using Windows Installer - is there a way to trigger whatever code I write for section A from within the installer in time for the installation to take place at the new location? It looks like overriding Install() is too late in the game...
we use a js windows script to update our virtual directories between branches, I would imagine that you could use the same objects to create a website ``` var iisPath = "IIS://localhost/W3SVC/" + siteID; var site = GetObject(iisPath); ``` Microsoft has a [fairly extensive article](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/2db9f530-2a10-40bd-b68d-667ba62ac5fe.mspx?mfr=true) on configuring IIS 6 programatically. As long as your MSI can call a batch file, this article should help out. [This article](http://www.winscripter.com/WSH/ADSI/272.aspx) also has a complete script file that creates a website.
Here's some C# code for programmatically creating a site: ``` 1 using System.DirectoryServices; 2 using System; 3 4 public class IISAdmin 5 { 6 public static int CreateWebsite(string webserver, string serverComment, string serverBindings, string homeDirectory) 7 { 8 DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/w3svc"); 9 10 //Create a website object array 11 object[] newsite = new object[]{serverComment, new object[]{serverBindings}, homeDirectory}; 12 13 //invoke IIsWebService.CreateNewSite 14 object websiteId = (object)w3svc.Invoke("CreateNewSite", newsite); 15 16 return (int)websiteId; 17 18 } 19 20 public static void Main(string[] args) 21 { 22 int a = CreateWebsite("localhost", "Testing.com", ":80:Testing.com", "C:\\inetpub\\wwwroot"); 23 Console.WriteLine("Created website with ID: " + a); 24 } 25 26 } ``` reference: <http://www.it-notebook.org/iis/article/cs_create_website_iis6.htm>
How do I Programatically add a Web Site (C#) to IIS 6.0?
[ "", "c#", "iis", "web", "installation", "" ]
[This question](https://stackoverflow.com/questions/539568/binding-ilistimyinterfacetype-doesnt-display-members-of-interfaces-that-imyint) (along with its answer) explains why you can't easily bind a DataGridView to an interface type and get columns for properties inherited from a base interface. The suggested solution is to implement a custom TypeConverter. My attempt is below. However, creating a DataSource and DataGridView bound to ICamel still only results in one column (Humps). I don't think that my converter is being used by .NET to decide which properties it can see for ICamel. What am I doing wrong? ``` [TypeConverter(typeof(MyConverter))] public interface IAnimal { string Name { get; set; } int Legs { get; set; } } [TypeConverter(typeof(MyConverter))] public interface ICamel : IAnimal { int Humps { get; set; } } public class MyConverter : TypeConverter { public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { if(value is Type && (Type)value == typeof(ICamel)) { List<PropertyDescriptor> propertyDescriptors = new List<PropertyDescriptor>(); foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(ICamel))) { propertyDescriptors.Add(pd); } foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(IAnimal))) { propertyDescriptors.Add(pd); } return new PropertyDescriptorCollection(propertyDescriptors.ToArray()); } return base.GetProperties(context, value, attributes); } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return true; } } ```
`DataGridView` does not use `TypeConverter`; **`PropertyGrid`** uses `TypeConverter`. If it relates to list-controls like `DataGridView`, then the other answer is wrong. To provide custom properties on a list, you need one of: * `ITypedList` on the data-source * `TypeDescriptionProvider` on the type Both are non-trivial.
My Workaround happens in the binding of the dgv. I do need that the base interfaces and the inheriting interfaces remain in the same structure, just because i do other things width the final concerete class, not only show the data on a DataGridView. So, for example: ``` interface IGenericPerson { int ID { get; set; } string Name { get; set; } } interface IOperator : IGenericPerson { bool IsAdmin { get; set; } } ``` the concrete class: ``` class Operator : IOperator { public Operator(){} public Operator(int id, string name, bool isAdmin) { this.ID = id; this.Name = name; thsi.IsAdmin = isAdmin; } public int ID { get; set; } public string name { get; set; } public bool IsAdmin { get; set; } } ``` and in a Gateway Class: ``` public IList<IOperator> GetOperators() { IList<IOperator> list = new List<IOperator>(); list.add(new Operator(112, "Mark Twain", false); list.add(new Operator(112, "Charles Manson", false); list.add(new Operator(112, "Richard Nixon", true); return list; } ``` Now, if i try to bind a datagridView like this: ``` Gateway gt = new Gateway(); dgv.DataSource = gt.GetOperators(); ``` I get a DataGridView with the only bool IsAdmin column from the IOperator Interface, not the ID, neither the Name propertys from its base interface. but if I do this: ``` Gateway gt = new Gateway(); IList<IOperator> list = gt.GetOperators(); IList<Operator> ds = new List<Operator>(); foreach(IOperator op in list) ds.add((Operator)op); dgv.DataSource = ds; ``` Everything works in the right way. In this way i don't need to change the structure of the intarfaces chain, useful for other purposes, and only qhen displaying data i just insert the snippet above.
Binding to interface and displaying properties in base interface
[ "", "c#", "datagridview", "interface", "datasource", "" ]
Is there any way to pre compile stored procedures in SQL Server? My requirement goes like this.. I have some stored procedures, which take more time in compiling than executing. So I want to precompile all the stored procedures. It would be nice to precompile them when the db server is started and running. Any ideas on this would be greatly helpful!
you can force a recompile, but it will not happen until the next time it is run [EXEC SP\_RECOMPILE YourProcedureName](http://msdn.microsoft.com/en-us/library/ms181647.aspx) [more info here...](http://www.devx.com/tips/Tip/13386) force it to recompile each time it is run: CREATE PROCEDURE YourProcedureNameWITH RECOMPILE ..... force it to recompile this time: EXEC YourProcedureName WITH RECOMPILE [here is a good article on Optimizing SQL Server Stored Procedures to Avoid Recompiles](http://www.sql-server-performance.com/articles/per/optimizing_sp_recompiles_p1.aspx) [and another...](http://www.databasejournal.com/features/mssql/article.php/2203601/Identifying-Stored-Procedure-Recompilation-Problems-in-SQL-Server-2000.htm) **EDIT** based on OP's comments: why don't you manually run it (outside the application) with bogus data (not so bogus that the execution plan is bad though, google: sql server parameter spoofing and sniffing) the first time, that can force a compile, then run some sql to delete out what was inserted. when the users run it for the first time, it will have already run and have been compiled.
Write a script that executes each stored procedure using "SET FMTONLY ON". The procedure will be compiled, but no permanent changes will be made to the DB during execution. You can't use this with procedures that use temporary tables (#table syntax). That's how Microsoft does it in Visual Studio to determine what the output of your stored procedure should be.
How to precompile stored procedures in SQL server?
[ "", "sql", "sql-server", "" ]
How can we count space between text in PHP? ``` example: hi how are you? spaces: 3 ``` Is there a way to count spaces? Language: Only PHP
Use this: ``` substr_count($text, ' '); ```
You're looking for [`preg_match_all`](http://php.net/manual/en/function.preg-match-all.php). ``` $numSpaces = preg_match_all('/[ ]/', $testStr, $matches); ```
How to count space in a text statement in PHP
[ "", "php", "text", "count", "spaces", "" ]
I want to hide the Next button on my ASP.NET Wizard control using JavaScript. Can anybody tell me if this is possible and post a javascript snippet on how to do this? Thanks!
2 options here... 1. TemplatedWizardStep - that way you create the buttons yourself and can then use either the control name or a css class on the button to turn it on & off with javascript or jQuery. 2. use StartNextButtonStyle to set a css class on your next button so you can grab the button with jQuery. Example of this one is below (I'm checking to see whether a checkbox is checked before enabling the button) Wizard markup... ``` <asp:Wizard ... > <StartNextButtonStyle CssClass="StandardButton StartNextButton" /> <WizardSteps> <asp:WizardStep runat="server" ID="AgreementStep" StepType="Start"> <asp:CheckBox runat="server" ID="AcceptAgreement" Text="I agree to the agreement terms." TextAlign="Left" onclick='EnableNextButton();' CssClass="NormalTextBox AcceptedAgreement" /> </asp:WizardStep> </WizardSteps> </asp:Wizard> ``` Javascript (using jQuery) to enable/disable the next button: ``` <script type="text/javascript"> function EnableNextButton() { var button = jQuery(".StartNextButton") var checkBox = jQuery(".AcceptedAgreement input:checkbox"); if (checkBox.is(':checked')) button.removeAttr("disabled"); else button.attr("disabled", "disabled"); } </script> ```
You should be able to use the answer from [question #267191](https://stackoverflow.com/questions/267191/how-do-you-set-the-visible-property-of-a-asp-net-control-from-a-javascript-func) to resolve your issue. From the link (slightly modified): ``` var theControl = document.getElementById("btnNext"); theControl.style.display = "none"; // to show it again: theControl.style.display = ""; ```
Hide asp.net Wizard next button in javascript
[ "", "asp.net", "javascript", "" ]
As a "newbie" to Python, and mainly having a background of writing scripts for automating system administration related tasks, I don't have a lot of sense for where to use certain tools. But I am very interested in developing instincts on where to use specific tools/techniques. I've seen a lot mentioned about templating engines, included [zedshaw](http://www.zedshaw.com) talking about using Jinja2 in [Lamson](http://lamsonproject.org/) So I thought I would ask the community to provide me with some advice as to where/when I might know I should consider using a templating engine, such as [Jinja2](http://jinja.pocoo.org/2/documentation/), [Genshi](http://genshi.edgewall.org/), [Mako](http://www.makotemplates.org/), and co.
As @mikem says, templates help generating whatever form of output you like, in the right conditions. Essentially the first meaningful thing I ever wrote in Python was a templating system -- [YAPTU](http://code.activestate.com/recipes/52305/), for Yet Another Python Templating Utility -- and that was 8+ years ago, before other *good* such systems existed... soon after I had the honor of having it enhanced by none less than Peter Norvig (see [here](http://aima.cs.berkeley.edu/yaptu.py)), and now it sports almost 2,000 hits on search engines;-). Today's templating engines are much better in many respects (though most are pretty specialized, especially to HTML output), but the fundamental idea remains -- why bother with a lot of `print` statements and hard-coded strings in Python code, when it's even easier to hve the strings out in editable template files? If you ever want (e.g.) to have the ability to output in French, English, or Italian (that was YAPTU's original motivation during an intense weekend of hacking as I was getting acquainted with Python for the first time...!-), being able to just get your templates from the right directory (where the text is appropriately translated) will make everything SO much easier!!! Essentially, I think a templating system is more likely than not to be a good idea, whenever you're outputting text-ish stuff. I've used YAPTU or adaptations thereof to smoothly switch between JSON, XML, and human-readable (HTML, actually) output, for example; a really good templating system, in this day and age, should in fact be able to transcend the "text-ish" limit and output in [protobuf](http://code.google.com/p/protobuf/) or other binary serialization format. Which templating system is best entirely depend on your specific situation -- in your shoes, I'd study (and experiment with) a few of them, anyway. Some are designed for cases in which UI designers (who can't program) should be editing them, others for programmer use only; many are specialized to HTML, some to XML, others more general; etc, etc. But SOME one of them (or your own Yet Another one!-) is sure to be better than a bunch of `print`s!-)
A templating engine works on templates to programmatically generate artifacts. A template specifies the skeleton of the artifact and the program fills in the blanks. This can be used to generate almost anything, be it HTML, some kind of script (ie: an RPM SPEC file), Python code which can be executed later, etc.
When to use a Templating Engine in Python?
[ "", "python", "templates", "template-engine", "" ]
Is it possible to find PHP tmp folder at run time? I am uploading files and I am making use of: ``` $_FILES['upfile']['tmp_name'] ``` However, one of the APIs I am making use of requires that I have to give the full file path of the uploaded file relative to my script! A bit annoying but it has to be done. Any ideas on how I can do this? ## EDIT Currently. I am doing this, as I know how many levels to go up but I am sure the tmp folder can be at different locations for different servers. ``` $file = '../..'.$_FILES['upfile']['tmp_name']; ``` Thanks all
Not sure if this is a foolproof way but it works on my server. In addition, there is probably a way to replace folder names with .. but that is beyond me. ``` $folders = explode('/', $_SERVER['SCRIPT_FILENAME']); for ($i = 2; $i < count($folders); $i++) $dir .= '../'; $dir = substr($dir,0,-1); $dir = $dir.$_FILES['upfile']['tmp_name']; ```
Really, if possible, I'd recommend you move the uploaded file into its permanent location before you start interacting with other APIs regarding it. You're going to have to anyway, and then you know its relative location easily. If you can't do that, I suppose you can work out the relative path by analyzing `dirname($_FILES['upfile']['tmp_name'])` and `dirname(__FILE__)`.
How to find PHPs tmp folder relative to script running?
[ "", "php", "file", "upload", "" ]
Ok, I've got a list like this (just a sample of data): ``` data = {"NAME": "James", "RANK": "3.0", "NUM": "27.5" ... } ``` Now, if I run something like this: ``` sortby = "NAME" //this gets passed to the function, hence why I am using a variable sortby instead data.sort(key=itemgetter(sortby)) ``` I get all the strings sorted properly - alphabetically. However, when "sortby" is any of the floating values (RANK or NUM or any other), sort is done again, alphabetically, instead of numerically, so my sorted list looks something like this then: 0.441 101.404 107.558 107.558 108.48 108.945 11.195 12.143 12.801 131.73 which is obviously wrong. Now, how can I do a sort like that (most efficiently in terms of speed and resources/computations taken) but have it cast the value somehow to float when it's a float, and leave it as a string when it's a string... possible? And no, removing quotes from float values in the list is not an option - I don't have control over the source list, unfortunately (and I know, that would've been an easy solution).
If you want a general function which you can pass as a parameter to `sort(key=XXX)`, then here's a candidate complete with test: ``` DATA = [ { 'name' : 'A', 'value' : '10.0' }, { 'name' : 'B', 'value' : '2.0' }, ] def get_attr(name): def inner_func(o): try: rv = float(o[name]) except ValueError: rv = o[name] return rv return inner_func for attrname in ('name', 'value'): DATA.sort(key=get_attr(attrname)) print "%r-sorted: %s" % (attrname, DATA) ``` When you run the above script, you get: ``` 'name'-sorted: [{'name': 'A', 'value': '10.0'}, {'name': 'B', 'value': '2.0'}] 'value'-sorted: [{'name': 'B', 'value': '2.0'}, {'name': 'A', 'value': '10.0'}] ```
if you cant save your data properly ( floats as *floats* ), something like this ``` sorters = { "NAME" : itemgetter("NAME"), "RANK" : lambda x: float(x["RANK"]), "NUM" : lambda x: float(x["NUM"]) } data.sort(key=sorters[sortby]) ```
Sorting a Python list by key... while checking for string OR float?
[ "", "python", "list", "sorting", "" ]
I had a Java program that I run thousand times based on a loop (according to the number of files to be compiled to build a linux kernel) in a bash script. There was a performance problem since the jvm was started several times... What i've done then is implementing a wrapper in java that does the same as my bash script, reads one line from a file and then calls the main of my previous program... This way, I only have one jvm running... The problem now is that only one core of my box is used which is another performance issue... Do I have to start some threads or can I use the same method but maybe calling the "former" main in a different way ? If i have to start some threads, how I dispatch them throughout the multiple cores ? thanks...
Your java program needs to become multi-threaded, in order to take advantage of many cores. For example, create a thread pool using java.util.concurrent.Executors, encapsulate your data items as a Runnable, and submit the Runnable to the threadpool.
At the risk of oversimplifying it, just have your old class implement Runnable, taking what was in main() and putting it in Run(), then create a new thread with that class and start the thread. In reality it might be more complicated than that if the threads need to share data, but based on what you said you are doing here, it doesn't seem like they would. So it might actually be just that easy.
how to execute a java program on several cores?
[ "", "java", "multithreading", "jvm", "" ]
I am building a autocomplete feature for input text field. Currently I could use mouse click to choose the selection, I'd like to add keyboard control to allow autocomplete control. I monitored the keycode in onkeyup event, it appears for up/down key, the key codes are both 0. I am wondering whether there is any better way to do so. Thanks.
Keycodes 37 - 40 should do it for you. They map as 37=left, 38=up, 39=right, 40=down.
Look at the example at <http://www.w3schools.com/jsref/jsref_onkeydown.asp>. It works for me in both FF3.5 and IE8.
Is it possible to handle up/down key in HTML input field?
[ "", "javascript", "html", "events", "autocomplete", "key", "" ]
By default it will not print out anything until the whole page has finished executing. Is there any function that can make it flush out right away? But not by calling `ob_end_flush()` multiple times, which is not what I want. Hope you guys got me?
If output buffering is on, then flushing it is the only way to output anything to the browser. If you want to output right away then turn of output buffering. If that is not in your control you can just call ob\_end\_flush() at the srart of your script which will turn the output buffering off. There is no way however to let some messages pass, and some not (without writing custom echo/print functions) calling ob\_end\_flush() will flush and turn off the top most output buffer. To make sure all output buffers are turned off and flushes you can easily do this: ``` while (@ob_end_flush()); ```
It will depend on your webserver. Calling [flush](http://en.php.net/flush) will flush the output of whatever current buffer is open, however, as it says on the linked page: > flush() has no effect on the buffering scheme of your web server or the browser on the client side. Thus you need to call both ob\_flush() and flush() to flush the output buffers. > > Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser. > > Server modules for Apache like mod\_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.
how to make echo print out right away in PHP?
[ "", "php", "flush", "" ]
In Java, I'm using the String split method to split a string containing values separated by semicolons. Currently, I have the following line that works in 99% of all cases. ``` String[] fields = optionsTxt.split(";"); ``` However, the requirement has been added to include escaped semicolons as part of the string. So, the following strings should parse out to the following values: ``` "Foo foo;Bar bar" => [Foo foo] [Bar bar] "Foo foo\; foo foo;Bar bar bar" => [Foo foo\; foo foo] [Bar bar bar] ``` This should be painfully simple, but I'm totally unsure about how to go about it. I just want to not tokenize when there is a \; and only tokenize when there is a ;. Does anyone out there know the magic formula?
try this: ``` String[] fields = optionsTxt.split("(?<!\\\\);"); ```
There's probably a better way but the quick-and-dirty method would be to first replace \; with some string that won't appear in your input buffers, like {{ESCAPED\_SEMICOLON}}, then do the tokenize on ;, and then when you pull out each token do the original substitution in reverse to put back the \;
How do I split a string using a regular expression that excludes an escaped version of my token?
[ "", "java", "regex", "" ]
Basically, I would like to decode a given HTML document, and replace all special characters, such as `"&nbsp;"` → `" "` and `"&gt;"` → `">"`. In [.NET](https://en.wikipedia.org/wiki/.NET_Framework), we can make use of the [HttpUtility.HtmlDecode](https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.htmldecode) method. What's the equivalent function in Java?
I have used the Apache Commons [StringEscapeUtils.unescapeHtml4()](https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html#escapeHtml4-java.lang.String-) for this: > Unescapes a string containing entity > escapes to a string containing the > actual Unicode characters > corresponding to the escapes. Supports > HTML 4.0 entities.
The libraries mentioned in other answers would be fine solutions, but if you already happen to be digging through real-world HTML content in your project, the [`Jsoup`](http://jsoup.org) project has a lot more to offer than just managing *"ampersand pound FFFF semicolon"* things. ``` // textValue: <p>This is a&nbsp;sample. \"Granny\" Smith &#8211;.<\/p>\r\n // becomes this: This is a sample. "Granny" Smith –. // with one line of code: // Jsoup.parse(textValue).getText(); // for older versions of Jsoup Jsoup.parse(textValue).text(); // Another possibility may be the static unescapeEntities method: boolean strictMode = true; String unescapedString = org.jsoup.parser.Parser.unescapeEntities(textValue, strictMode); ``` And you also get the convenient API for extracting and manipulating data, using the best of DOM, CSS, and [jQuery](https://en.wikipedia.org/wiki/JQuery)-like methods. It's open source and [MIT License](https://en.wikipedia.org/wiki/MIT_License).
How can I unescape HTML character entities in Java?
[ "", "java", "html", "string", "eclipse", "decode", "" ]
The JDBC `java.sql.Statement` class has a `cancel()` method. This can be called in another thread to cancel a currently running statement. How can I achieve this using Spring? I can't find a way to get a reference to a statement when running a query. Nor can I find a cancel-like method. Here's some sample code. Imagine this takes up to 10 seconds to execute, and sometimes on the user's request, I want to cancel it: ``` final int i = simpleJdbcTemplate.queryForInt("select max(gameid) from game"); ``` How would I modify this so I have a reference to a `java.sql.Statement` object?
Let me simplify oxbow\_lakes's answer: you can use the `PreparedStatementCreator` variant of the query method to gain access to the statement. So your code: ``` final int i = simpleJdbcTemplate.queryForInt("select max(gameid) from game"); ``` Should turn into: ``` final PreparedStatement[] stmt = new PreparedStatement[1]; final int i = (Integer)getJdbcTemplate().query(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { stmt[0] = connection.prepareStatement("select max(gameid) from game"); return stmt[0]; } }, new ResultSetExtractor() { public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException { return resultSet.getString(1); } }); ``` Now to cancel you can just call ``` stmt[0].cancel() ``` You probably want to give a reference to `stmt` to some other thread before actually running the query, or simply store it as a member variable. Otherwise, you can't really cancel anything...
You can execute stuff via `JdbcTemplate` methods which allow you to pass in a `PreparedStatementCreator`. You could always use this to intercept invocations (perhaps using a `Proxy`) which caused a `cancel` to happen on a separate thread by some `cond` became `true`. ``` public Results respondToUseRequest(Request req) { final AtomicBoolean cond = new AtomicBoolean(false); requestRegister.put(req, cond); return jdbcTemplate.query(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection conn) { PreparedStatement stmt = conn.prepareStatement(); return proxyPreparedStatement(stmt, cond); } }, new ResultSetExtractor() { ... }); } ``` This `canceller` could itself be cancelled upon successful completion; for example ``` private final static ScheduledExecutorService scheduler = Executors.newSingleThreadedScheduledExecutor(); PreparedStatement proxyPreparedStatement(final PreparedStatement s, AtomicBoolean cond) { //InvocationHandler delegates invocations to the underlying statement //but intercepts a query InvocationHandler h = new InvocationHandler() { public Object invoke(Object proxy, Method m, Object[] args) { if (m.getName().equals("executeQuery") { Runnable cancel = new Runnable() { public void run() { try { synchronized (cond) { while (!cond.get()) cond.wait(); s.cancel(); } } catch (InterruptedException e) { } } } Future<?> f = scheduler.submit(cancel); try { return m.invoke(s, args); } finally { //cancel the canceller upon succesful completion if (!f.isDone()) f.cancel(true); //will cause interrupt } } else { return m.invoke(s, args); } } } return (PreparedStatement) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[]{PreparedStatement.class}, h); ``` So now the code that is responding to a user's cancellation would look like: ``` cond.set(true); synchronized (cond) { cond.notifyAll(); } ```
How can I cancel a long-running query using Spring and JDBCTemplate?
[ "", "java", "spring", "jdbctemplate", "" ]
I have various time-series I'd like to correlate and present as either a csv-file or in-memory datatable (.NET). These time-series are arrays of time-value-pairs (actually these are objects containing more than just time and value). The time-series may span across different overlapping periods, and some might even have holes (missing values for given timestamps). For those interested, I'm using the OPC HDA .NET library to extract historic time-series from an OPC HDA server. The resulting datatable should have one column for each time-series all in chronological order based on a timestamp column. See example below: ``` |-------|-------|-------|-------|-------| TIME TS1 TS2 TS3 TS4 |-------|-------|-------|-------|-------| 1 X X X |-------|-------|-------|-------|-------| 2 X X X X |-------|-------|-------|-------|-------| 3 X X X |-------|-------|-------|-------|-------| 4 X X X |-------|-------|-------|-------|-------| 5 X X X |-------|-------|-------|-------|-------| ``` What would be the most effective way of achieving this? With "effective" I mean with the least amount of code. But considering that the timeseries could become quite large, memory usage might also be an issue.
You might go with a data structure like a nested dictionary and iterate over the contents: ``` Dictionary <TimeSeries, Dictionary<DateTime, Value>> dict = new Dictionary<TimeSeries, Dictionary<DateTime, Value>>(); foreach (TimeSeries series in dict.Keys) { //table row output code goes here Dictionary<DateTime, Value> innerDict = dict[series]; foreach (DateTime date in innerDict.Keys) { Value seriesValueAtTimeT = innerDict[date]; //table column output code goes here } } ``` Where your output code is writing out to something else, depending on your needs, and you replace the datatypes TimeSeries, Value, etc., with your actual data types.
You can first scan all present series for the distinct values (for example, aggregating them in a HashSet), then simply dump them into an array of dates (storing a match between date and index position in a dictionary). ``` var distinctDates = allSeries .SelectMany(s => s.Values.Select(v => v.Date)) .Distinct() .OrderBy(d => d) .ToArray(); var datePositions = distinctDates .Select((d,index) => new { Date = d, Index = index }). .ToDictionary(x => x.Date, x => x.Index); ``` Then, create a jagged array that has width of "NumberOfSeries" and length of "NumberOfDates". After that, do a second scan of all the data and dump them to their positions. ``` var values = new float[allSeries.Length][]; for (var i=0;i<allSeries.Length;i++) { values[i] = new float[distinctDates.Length]; var currentSerie = allSeries[i]; foreach(var value in currentSerie.Values) { var index = datePositions[value.Date]; values[i][index] = value.Value; } } ``` I wrote this code without touching VisualStudio, so I may have a few typos. Or there may be used a few LINQ methods that are not present in the .NET (just look in [Lokad.Shared.dll](http://abdullin.com/shared-libraries/)). But you should be able to get the idea. Some more notes, while I'm at the topic: 1. Go for the jagged array, if you have to keep everything in the memory at once. It is way more efficient than a dictionary and has a lot less memory problems than a rectangular array. 2. Keep Value objects as small as possible (i.e.: float instead of double). 3. If number of time serie values is expected to go large in the future, then never store values in database in a "one row per value". It is recommended to either go for something like [HDF](http://www.hdfgroup.org/) (which has a .NET interface) or use persist time serie fragments in binary form in DB (as in [time serie databases](http://en.wikipedia.org/wiki/Time_series_database)) Sticking to these should allow you to scale up to hundreds of millions of time values without a lot of problems (done that).
Time-series and correlation strategies
[ "", "c#", "algorithm", "time-series", "" ]
This is in C, but I tagged it C++ incase it's the same. This is being built with: Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.220 for 80x86 if that makes any different Why does this work? (inVal is 0x80) ``` float flt = (float) inVal; outVal = *((unsigned long*)&flt); ``` (results in outVal being 0x43000000 -- correct) But this doesn't? ``` outVal = *((unsigned long*)&((float)inVal)); ``` (results in outVal being 0x00000080 -- NOT CORRECT :( ) Before asking this question I googled around a bit and found [this function](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Float.html#floatToIntBits(float)) in java that basically does what I want. If you're a bit confused about what I'm trying to do, this program might help explain it: ``` class hello { public static void main(String[] args) { int inside = Float.floatToIntBits(128.0f); System.out.printf("0x%08X", inside); } } ```
You're trying to take the address of a non-const temporary (the result of your `(float)` conversion) – this is illegal in C++ (and probably also in C). Hence, your code results in garbage. In your first, working, code, you're not using a temporary so your code is working. Notice that from a standards point of view this is still ill-defined since the size and internal representation of the involved types isn't specified and may differ depending on platform and compiler. You're probably safe, though.
In C99, you may use compound literals to make this work inline: ``` unsigned long outVal = *((unsigned long *)&((float){ inVal })); ``` The literal `(float){ inVal }` will create a variable with automatic storage duration (ie stack-allocated) with a well-defined address. Type punning may also be done using unions instead of pointer casts. Using compound literals and the non-standard `__typeof__` operator, you can even do some macro magic: ``` #define wicked_cast(TYPE, VALUE) \ (((union { __typeof__(VALUE) src; TYPE dest; }){ .src = VALUE }).dest) unsigned long outVal = wicked_cast(unsigned long, (float)inVal); ``` GCC prefers unions over pointer casts in regard to optimization. This might not work at all with the MS compiler as its C99 support is rumored to be non-existant.
Inline float to uint "representation" type-punning not working?
[ "", "c++", "c", "" ]
I have thousands of IP addresses of visitors to my site, what tools can I use to convert these into lat/lng coordinates? I will then be able visualise the data on a map with filters for further demographics gathered.
For one of my sites I made use of maxmind's free geolite country database which can be downloaded here: <http://www.maxmind.com/app/geolitecountry> They also provide a city level version which includes the long/lat: <http://www.maxmind.com/app/geolitecity> but note that the accuracy on the free version is a lot lower than the paid version.
I suggest using Google Analytics to your problem, but if you want to try yourself here is a starting point: Take a look at this link <http://www.geoplugin.net/php.gp>, you get a full list of details about that ip address position, including latitude and longitude. It is not that acurate but it works, and I use it. Here is a php script actually in use : ``` <?php $ip_addr = $_SERVER['REMOTE_ADDR']; $geoplugin = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip_addr) ); if ( is_numeric($geoplugin['geoplugin_latitude']) && is_numeric($geoplugin['geoplugin_longitude']) ) { $lat = $geoplugin['geoplugin_latitude']; $long = $geoplugin['geoplugin_longitude']; } echo $ip_addr.';'.$lat.';'.$long; ?> ``` You can see it working at <http://whateverhappens.org/ip-addr/> And that a look at the Geoplugin website examples.
Tool or PHP code to convert IP address into lat/lng coordinates
[ "", "php", "ip-address", "latitude-longitude", "" ]
In C#, are lambda expressions objects? If so, what sort of object are they?
Lambda expressions themselves only exist in source code. They don't have a type themselves, which is why the compiler always insists they're convert to a specific type. That's why this code doesn't compile: ``` // No idea what type to convert to! object x = y => y.Length; ``` But this does: ``` Func<string, int> x = y => y.Length; ``` Lambda expressions are always converted to *either* a delegate type *or* an expression tree type. Similarly, anonymous methods are always converted to a delegate type.
Yes, lambda expressions are converted to either a [`delegate`](http://msdn.microsoft.com/en-us/library/system.delegate.aspx) or an [expression tree](http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.aspx) - both of which are objects.
In C#, are Lambda Expressions objects?
[ "", "c#", "lambda", "" ]
I want to do something like this: ``` class Cls { function fun($php) { return 'The rain in Spain.'; } } $ar = array(1,2,3); $instance = new Cls(); print_r(array_map('$instance->fun', $ar)); // ^ this won't work ``` but the first argument to array\_map is supposed to be the name of the function. I want to avoid writing a wrapper function around $instance->fun, but it doesn't seem like that's possible. Is that true?
Yes, you can have callbacks to methods, like this: ``` array_map(array($instance, 'fun'), $ar) ``` see [the callback type](https://www.php.net/manual/en/language.types.callable.php) in PHP's manual for more info
You can also use ``` array_map('Class::method', $array) ``` syntax.
Can a method be used as an array_map function
[ "", "php", "methods", "array-map", "" ]
How can I use Process.Start(), but have the launched process not in the same process tree as the launching process? Consider this sample console application: ``` using System; using System.Diagnostics; using System.Threading; internal class Program { private static void Main(string[] args) { Console.WriteLine("Starting ie..."); Process.Start("c:\\Program Files\\Internet Explorer\\iexplore.exe", "http://www.google.com"); Console.WriteLine("Waiting for 15 seconds"); Thread.Sleep(15000); Console.WriteLine("Exiting..."); } } ``` When this program exits normally, Internet Explorer will continue to run. However, if during the 15 second sleep period you go to Task Manager and select this program and select "End Process Tree", Internet Explorer will also close. (This is directly related to [my question from earlier today](https://stackoverflow.com/questions/1033483/windows-xp-screen-saver-launched-process-dies-with-screen-saver) that, as yet, has no replies. In Windows XP, when the screen saver process ends, it appears to end the process tree, whereas in Vista, just the screen saver process is ended.)
Eric is correct: Windows does not expose any method of changing a processes parent. However, if the parent dies, there is no link back to grandparent so you can achieve your goal with an intermediate process that starts the child, then dies. So: Proc A starts proc B, then proc B starts proc C and immediately dies. When proc B dies, proc C will be a root node on the process tree - proc C will NOT be in proc A's tree after proc B dies.
Try setting Process.StartInfo.UseShellExecute to False (it is True by default) before calling Process.Start(). That way, CreateProcess() is used internally instead of ShellExecute().
Process.Start() and the Process Tree
[ "", "c#", ".net", "" ]
In the ADO.Net Entity Framework, I have an object which has 4 references to other objects. For some reason, when I query those references, two of them load automatically (as expected), and two of them always return null. Bizarrely enough, when I *manually* ask the references to load, they load just dandy. As an example: ``` if (account.HoldingEntity == null && account.HoldingEntityReference.EntityKey != null) { account.HoldingEntityReference.Load(); account.HoldingEntity = account.HoldingEntityReference.Value; } ``` When I first check the `HoldingEntity` it is always null, however the Load will return the HoldingEntity without problem. Any clues? Thanks!
Using ADO.NET Entities, you need to specify what entities you want to load automatically with `Include`, as in ``` Dim entity = (From e in db.Entities.Include("SubEntity")) ```
As others have said you need to `.Include()` in v1 to avoid needing to call `.Load()` In 4.0 you will be able to set `DeferredLoadingEnable`d on your `ObjectContext` (I think we are changing this name to the more appropriate `LazyLoadingEnabled` in time for Beta2). As for why you get 2 relationships already loaded anyway. That is probably a side-effect of something called Relationship Fix-up. When two related entities are in the same Context, they automatically get their relationship's fixed to point to each other. So if (as I suspect) 2 of the 4 entities are already in your context, when you do the query, you will end up in a situation where 2 of your relationships are loaded, even though you didn't call `.Include()` or `.Load()`. Hope this helps Cheers Alex
Entity Framework references not loading automatically
[ "", "c#", "entity-framework", "ado.net", "" ]
In Java, is there any way to get (catch) all `exceptions` instead of catching the exceptions individually?
If you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the `exceptions` later (perhaps at the same time as other `exceptions`). The code looks like: ``` public void someMethode() throws SomeCheckedException { // code } ``` Then later you can deal with the `exceptions` if you don't wanna deal with them in that method. To catch all exceptions some block of code may throw you can do: (This will also catch `Exceptions` you wrote yourself) ``` try { // exceptional block of code ... // ... } catch (Exception e){ // Deal with e as you please. //e may be any type of exception at all. } ``` The reason that works is because `Exception` is the base class for all exceptions. Thus any exception that may get thrown is an `Exception` (Uppercase 'E'). If you want to handle your own exceptions first simply add a `catch` block before the generic Exception one. ``` try{ }catch(MyOwnException me){ }catch(Exception e){ } ```
While I agree it's not good style to catch a raw Exception, there are ways of handling exceptions which provide for superior logging, and the ability to handle the unexpected. Since you are in an exceptional state, you are probably more interested in getting good information than in response time, so instanceof performance shouldn't be a big hit. ``` try{ // IO code } catch (Exception e){ if(e instanceof IOException){ // handle this exception type } else if (e instanceof AnotherExceptionType){ //handle this one } else { // We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy. throw e; } } ``` However, this doesn't take into consideration the fact that IO can also throw Errors. Errors are not Exceptions. Errors are a under a different inheritance hierarchy than Exceptions, though both share the base class Throwable. Since IO can throw Errors, you may want to go so far as to catch Throwable ``` try{ // IO code } catch (Throwable t){ if(t instanceof Exception){ if(t instanceof IOException){ // handle this exception type } else if (t instanceof AnotherExceptionType){ //handle this one } else { // We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy. } } else if (t instanceof Error){ if(t instanceof IOError){ // handle this Error } else if (t instanceof AnotherError){ //handle different Error } else { // We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy. } } else { // This should never be reached, unless you have subclassed Throwable for your own purposes. throw t; } } ```
How can I catch all exceptions thrown through reading / writing a file?
[ "", "java", "file", "exception", "try-catch", "" ]