Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have an Arduino application (well actually a library) that has a number of status flags in it - and originally I simply declared them as ints (well uint8\_t so 8 bit unsigned chars in this case). But I could have combined them all into one integer and used bitmask operations to set and test the status. An example of the former: ``` if (_shift == HIGH) { _shift = LOW; } else { _shift = HIGH; } ``` an example of the latter ``` #define SHIFT_BIT 0 if (bitRead(_flags, SHIFT_BIT) == HIGH) { bitWrite(_flags, SHIFT_BIT, LOW); } else { bitWrite(_flags, SHIFT_BIT, HIGH); } ``` The former reads better, but the latter is more efficient (space and time). Should the space and time efficiency always win in this situation or is this a kind of optimization that should only happen when needed? (Added) For completeness here's the Wiring definition of those bitWrite etc. macros: ``` #define bitRead(value, bit) (((value) >> (bit)) & 0x01) #define bitSet(value, bit) ((value) |= (1UL << (bit))) #define bitClear(value, bit) ((value) &= ~(1UL << (bit))) #define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit)) ```
Check out [Raymond Chen's excellent take](http://blogs.msdn.com/oldnewthing/archive/2008/11/26/9143050.aspx) on this issue. In summary, you need to do some detailed calculation to find out whether the latter case is actually more efficient, depending on how many objects there are vs. how many callsites actually set these states. As far as readability, it looks like you're doing this with member variables, which means you've probably encapsulated them in nice functions. In that case, I'm not as concerned with readability because at least the code for the people using the class looks nice. However, you could always encapsulate it in private functions if it's a concern.
Depending on the compliance of the AVR-GCC compiler, which I'm unsure about, you can do something like this and keep things nice and clean. ``` struct flags { unsigned int flag1 : 1; //1 sets the length of the field in bits unsigned int flag2 : 4; }; flags data; data.flag1 = 0; data.flag2 = 12; if (data.flag1 == 1) { data.flag1 = 0; } else { data.flag1 = 1; } ``` If you also want access to the entire flag int at once, then: ``` union { struct { unsigned int flag1 : 1; //1 sets the length of the field in bits unsigned int flag2 : 4; } bits; unsigned int val; } flags; ``` You can then access a bit with 2 levels of indirection: `variable.bits.flag1`<--returns single bit flag or with a single level to get the entire int worth of flags: `variable.val` <--returns int
Bit setting and code readability
[ "", "c++", "embedded", "performance", "arduino", "" ]
I need to know when a new file appears in a directory. Obviously, I could poll the file system periodically, but that has all the normal downsides of polling mechanisms. I know that [windows supports file system events](http://msdn.microsoft.com/en-us/library/28y7bbdc(VS.71).aspx), and this project is already constrained to the Windows platform by other requirements. Does anyone have experience receiving Windows filesystem events inside a JVM? If so what are the best practices, patterns, and/or libraries you have used? A quick google turns up [this library](http://www2.hawaii.edu/~qzhang/FileSystemWatcher/index.html). Does anyone have experience with it (or any other) that they'd be willing to share?
I think this is one of the key features of Java 7 when it is more available. Example code from Sun's [blog on Java 7:](http://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes) import static java.nio.file.StandardWatchEventKind.\*; ``` Path dir = ...; try { WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); } catch (IOException x) { System.err.println(x); } ```
For Java 6 or older use [JNA](http://jna.dev.java.net/)'s com.sun.jna.platform.win32.FileMonitor.
How can I receive Windows filesystem events in Java?
[ "", "java", "windows", "filesystems", "" ]
I'm often conflicted about how to approach this problem in my applications. I've used any number of options including: * A generic multiselect - This is my least favorite and most rarely used option. I find the usability to be atrocious, a simple mis-click can screw up all your hard work. * An "autocomplete" solution - Downside: user must have spelling abilities to find the damn values they need, aren't exposed to ones they may not have in mind, and the potential backend performance of substring searching. * Two adjacent multiselects, with an add/remove button - Downsides: still "ugly" imo * Any number of fancy javascript solutions (<http://livepipe.net/control/selectmultiple>, <http://loopj.com/2009/04/25/jquery-plugin-tokenizing-autocomplete-text-entry/>, etc.) I haven't been able to find any usability studies done on the best approach to this problem. Many of these alternate solutions are great when you're going from <10 elements to a hundred, but may break down completely when you are going from a hundred to a thousand. What do you guys use? Why do you use it? Can you point me to usability case studies? Is there a "magic" solution that has yet to be discovered?
My advice is don't use generic multiple select controls. I've been running User Experience Research for my whole career, and every single time I test a site with multiple select controls, it always turns out to cause problems for end users. I did a post on this a while back: [Multiple Select Controls Must Evolve or Die](http://www.90percentofeverything.com/2008/12/03/multiple-select-controls-must-evolve-or-die/) Sounds like you knew this anyway, though. Your real question is "what do I use instead?" Well, to answer this question you have to work out whether the user's task leans towards **recall** or **recognition**. **(i) By recall**, I mean the user knows what they want to pick before they have even seen the list. In this case, it's probably easiest for them if you offer an autocomplete tool (as used very effectively on facebook, for example). This solution is even better when the list of options is also impossibly long to present on a page (e.g. location names, etc). **(ii) Moving on to recognition** - by this I mean a task that involves the user not knowing what they want to pick until they've seen the list of options. In this case, autocomplete doesn't give them any hints. An array of checkboxes would be much more helpful. If you can show them all at once, this is helpful to the user. Scrolling DIVs are more compact but they create a memory load for the user - i.e. once they've scrolled down, they have to remember which items they picked. This is particularly evident when users save a form and come back to it later. So - thinking about your problem, do you need a solution for recall or recognition?
I can't point you to any case studies, unfortunately, but what I can tell you is that I personally prefer large checkbox arrays in two-to-five column layouts. Sure, they take up a lot of space, but they are extremely precise and uncomplicated. I think for *any* control - be it basic multiselect, double list, checkbox array, or any other solution - once you go over a certain threshold of items it's going to be challenging for the user no matter what.
Alternatives to a single <select multiple="multiple"> element for large datasets
[ "", "javascript", "html", "usability", "" ]
I've been working on this for 3 hours and have given up. I am simply trying to send data to an ASP.NET WebMethod, using jQuery. The data is basically a bunch of key/value pairs. So I've tried to create an array and adding the pairs to that array. My WebMethod (aspx.cs) looks like this (this may be wrong for what I'm building in JavaScript, I just don't know): ``` [WebMethod] public static string SaveRecord(List<object> items) { ... } ``` Here is my sample JavaScript: ``` var items = new Array; var data1 = { compId: "1", formId: "531" }; var data2 = { compId: "2", formId: "77" }; var data3 = { compId: "3", formId: "99" }; var data4 = { status: "2", statusId: "8" }; var data5 = { name: "Value", value: "myValue" }; items[0] = data1; items[1] = data2; items[2] = data3; items[3] = data4; items[4] = data5; ``` Here is my jQuery AJAX call: ``` var options = { error: function(msg) { alert(msg.d); }, type: "POST", url: "PackageList.aspx/SaveRecord", data: { 'items': items }, contentType: "application/json; charset=utf-8", dataType: "json", async: false, success: function(response) { var results = response.d; } }; jQuery.ajax(options); ``` I get the error: ``` Invalid JSON primitive: items. ``` So, if I do this: ``` var DTO = { 'items': items }; ``` and set the data parameter like this: ``` data: JSON.stringify(DTO) ``` Then I get this error: ``` Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.List`1[System.Object]\u0027 ```
When using AJAX.NET I always make the input parameter just a plain old object and then use the javascript deserializer to covert it to whatever type I want. At least that way you can debug and see what type of object the web method in is recieving. You need to convert your object to a string when using jQuery ``` <!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 runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true"> <Scripts> <asp:ScriptReference Path="~/js/jquery.js" /> </Scripts> </asp:ScriptManager> <div></div> </form> </body> </html> <script type="text/javascript" language="javascript"> var items = [{ compId: "1", formId: "531" }, { compId: "2", formId: "77" }, { compId: "3", formId: "99" }, { status: "2", statusId: "8" }, { name: "Value", value: "myValue"}]; //Using Ajax.Net Method PageMethods.SubmitItems(items, function(response) { var results = response.d; }, function(msg) { alert(msg.d) }, null); //using jQuery ajax Method var options = { error: function(msg) { alert(msg.d); }, type: "POST", url: "WebForm1.aspx/SubmitItems", data: {"items":items.toString()}, // array to string fixes it * contentType: "application/json; charset=utf-8", dataType: "json", async: false, success: function(response) { var results = response.d; } }; jQuery.ajax(options); </script> ``` And the Code Behind ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Script.Serialization; using System.Web.Script.Services; using System.Web.UI; using System.Web.UI.WebControls; namespace CustomEquip { [ScriptService] public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static void SubmitItems(object items) { //break point here List<object> lstItems = new JavaScriptSerializer().ConvertToType<List<object>>(items); } } } ```
In your example, it should work if your data parameter is: ``` data: "{'items':" + JSON.stringify(items) + "}" ``` Keep in mind that you need to send a JSON string to ASP.NET AJAX. If you specify an actual JSON object as jQuery's data parameter, it will serialize it as &k=v?k=v pairs instead. It looks like you've read it already, but take another look at my [example of using a JavaScript DTO with jQuery, JSON.stringify, and ASP.NET AJAX](http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/). It covers everything you need to make this work. *Note: You should never use JavaScriptSerializer to manually deserialize JSON in a "ScriptService" (as suggested by someone else). It automatically does this for you, based on the specified types of the parameters to your method. If you find yourself doing that, you are doing it wrong.*
Sending JSON object successfully to ASP.NET WebMethod, using jQuery
[ "", "asp.net", "javascript", "jquery", "ajax", "json", "" ]
I was recently visiting [a site](http://blog.creonfx.com/linux/mdadm-raid-failed-after-upgrade-from-ubuntu-810-to-904) and noticed that the page had a section that said it noticed that I was using AdBlocking software and could I kindly turn it off to help support a small site like that. I was just wondering how you would do that? Would it be best done client-side or server-side?
This is something that simply can't be done server side - there's zilch reason for person to knock on your door and say "Look at me, I have AdblockPlus!". When on the client side, adblock is actively trying to influence the page content, which is something you can see happen and see that they are using an adblocker. Anyway, I happened to know that newgrounds.com is doing this too. (their new layout was screwed up for adblock plus users - as a response they made a contest for the best "if you're not going to help us through our ads, go and buy something in the store"-banner. A quick look in the source of newgrounds told me they are doing this with some simple javascript. First in the document: `var user_is_leecher = true;` Next there is a external script tag: `src=checkabp?thisistotrickabp=***adress of ad affilliate***` Now the joke: they simply trust adblock plus to filter that script out, as all that's in there is: `user_is_leecher = false;` From there, they can do just about anything.
All off the methods mentioned here rely on the ad blockers to strip out code. This doesn't work for some adblockers(like NetBarrier on Mac). You also have to keep updating your code when the adblockers catch on. To detect if the user is blocking ads, all you have to do is find a function in the ad javascript and try testing for it. It doesn't matter what method they're using to block the ad. Here's what it looks like for Google Adsense ads: ``` if(typeof(window.google_render_ad)=="undefined") { //They're blocking ads, do something else. } ``` This method is outlined here: <http://www.metamorphosite.com/detect-web-popup-blocker-software-adblock-spam>
Detecting AdBlocking software?
[ "", "php", "jquery", "adblock", "" ]
I want to take an interest in writing my own simple emulator for the [Z80](https://en.wikipedia.org/wiki/Zilog_Z80) processor. I have no experience with this type of programming. I am mostly fine with using C-based languages as they are the ones I know best. What do I need to accomplish this and what are some good tutorials/references that could aid me in this project? I would also like a tutorial for coding a ROM-dumping application for my [TI-84 Plus](https://en.wikipedia.org/wiki/TI-84_Plus_series) calculator so I can use its ROM with this emulator.
Perhaps start by looking at these: A good tutorial can be found here: [Independent Z80 Assembly Guide](http://www.ticalc.org/pub/text/z80/z80asmg.zip) [Z80 DOCUMENTATION](http://www.ticalc.org/pub/text/z80/index.html) [The Undocumented Z80 Documented v0.91](http://www.myquest.nl/z80undocumented/z80-documented-v0.91.pdf) (pdf) [The Complete Z80 Instruction Reference](http://www.ticalc.org/archives/files/fileinfo/128/12883.html) [Z80 Microprocessor Instruction Set Summary](http://www.ticalc.org/archives/files/fileinfo/1/109.html)
It's a bit of a side trip, but since you say you have no experience with this type of programming, you might want to start by building an emulator for the [Universal Virtual Machine](http://www.boundvariable.org/um-spec.txt) from the [2006 ICFP programming contest](http://www.boundvariable.org/). This is a task that takes an experienced programmer 90 minutes, but many teams with no experience were able to complete it in a few days. When you finish the emulator it unlocks a bunch of fun stuff, and it might be a good warmup before you tackle the Z80.
Writing a graphical Z80 emulator in C or C++
[ "", "c++", "c", "emulation", "z80", "" ]
If I know the database server name, instance name and the SQL Server job name, how to delete a SQL Server job by its name in a simple way? I am writing scripts which will be called by sqlcmd to delete SQL jobs. Appreciate if anyone could show me a sample? :-) thanks in advance, George
``` USE msdb; GO EXEC sp_delete_job @job_name = N'NightlyBackups' ; GO ```
You're looking for [`sp_delete_job`](http://technet.microsoft.com/en-us/library/ms188376.aspx): ``` [srv].[master].[dbo].sp_delete_job @job_name = 'MyJob' ``` So this four part name only works with linked servers. Otherwise, you'll have to connect to the server, and run that command against it (with everything right of `[dbo].`.
Looking for T-SQL scripts to delete a SQL Job
[ "", "sql", "sql-server", "t-sql", "sql-server-2008", "sql-server-agent", "" ]
We've pretty much moved over to using `boost::shared_ptr` in all of our code, however we still have some isolated cases where we use `std::auto_ptr`, including singleton classes: ``` template < typename TYPE > class SharedSingleton { public: static TYPE& Instance() { if (_ptrInstance.get() == NULL) _ptrInstance.reset(new TYPE); return *_ptrInstance; } protected: SharedSingleton() {}; private: static std::auto_ptr < TYPE > _ptrInstance; }; ``` I've been told that there's a very good reason why this hasn't been made a `shared_ptr`, but for the life of me I can't understand why? I know that `auto_ptr` will eventually get marked as depreciated in the next standard, so I'd like to **know what/how I can replace this implementation**. **Also, are there any other reasons why you'd consider using an `auto_ptr` instead of a `shared_ptr`?** And do you see any problems moving to shared\_ptr in the future? --- **Edit:** 1. So in answer to "can I safely replace `auto_ptr` with `shared_ptr` in the above code", the answer is yes - however I'll take a small performance hit. 2. When `auto_ptr` is eventually marked as depreciated and we move over to `std::shared_ptr`, we'll need to thoroughly test our code to make sure we're abiding by the different ownership semantics.
`auto_ptr` and `shared_ptr` solve entirely different problems. One does not replace the other. `auto_ptr` is a thin wrapper around pointers to implement [RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization) semantics, so that resources are always released, even when facing exceptions. `auto_ptr` does not perform any reference counting or the like at all, it does not make multiple pointers point to the same object when creating copies. In fact, it's very different. `auto_ptr` is one of the few classes where the assignment operator modifies the **source** object. Consider this shameless plug from the [auto\_ptr wikipedia page](http://en.wikipedia.org/wiki/Auto_ptr): ``` int *i = new int; auto_ptr<int> x(i); auto_ptr<int> y; y = x; cout << x.get() << endl; // Print NULL cout << y.get() << endl; // Print non-NULL address i ``` Note how executing ``` y = x; ``` modifies not only y but also x. The `boost::shared_ptr` template makes it easy to handle multiple pointers to the same object, and the object is only deleted after the last reference to it went out of scope. This feature is not useful in your scenario, which (attempts to) implement a [Singleton](http://en.wikipedia.org/wiki/Singleton_pattern). In your scenario, there's always either 0 references to 1 reference to the only object of the class, if any. In essence, `auto_ptr` objects and `shared_ptr` objects have entirely different semantics (that's why you cannot use the former in containers, but doing so with the latter is fine), and I sure hope you have good tests to catch any regressions you introduced while porting your code. :-}
Others have answered why this code uses an `auto_ptr` instead of a `shared_ptr`. To address your other questions: *What/how I can replace this implementation?* Use either `boost::scoped_ptr` or `unique_ptr` (available in both Boost and the new C++ standard). Both `scoped_ptr` and `unique_ptr` provide strict ownership (and no reference counting overhead), andthey avoid the surprising delete-on-copy semantics of `auto_ptr`. *Also, are there any other reasons why you'd consider using an `auto_ptr` instead of a `shared_ptr`? And do you see any problems moving to `shared_ptr` in the future?* Personally, I would not use an `auto_ptr`. Delete-on-copy is just too non-intuitive. [Herb Sutter seems to agree](http://www.ddj.com/cpp/184401839). Switching to `scoped_ptr`, `unique_ptr`, or `shared_ptr` should offer no problems. Specifically, `shared_ptr` should be a drop-in replacement if you don't care about the reference counting overhead. `scoped_ptr` is a drop-in replacement if you aren't using `auto_ptr`'s transfer-of-ownership capabilities. If you are using transfer-of-ownership, then `unique_ptr` is almost a drop-in replacement, except that you need to instead explicitly call `move` to transfer ownership. See [here](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=400) for an example.
When would you use an std::auto_ptr instead of boost::shared_ptr?
[ "", "c++", "stl", "boost", "shared-ptr", "auto-ptr", "" ]
How to fetch the images from a folder and display it in the page, whether i can resize it in php itself or i have to resize it and upload it separtely to display it as thumbnails?
Here's the basic structure for traversing a directory and doing something with the image files (given `'images'` is a directory in the same directory of your script) ``` $image_types = array( 'gif' => 'image/gif', 'png' => 'image/png', 'jpg' => 'image/jpeg', ); foreach (scandir('images') as $entry) { if (!is_dir($entry)) { if (in_array(mime_content_type('images/'. $entry), $image_types)) { // do something with image } } } ``` From here, you can send the images directly to browser, generate tags for HTML page or create thumbnails with [GD functions](http://www.php.net/gd) and store them for displaying.
i think this may help you! ``` <? $string =array(); $filePath='directorypath/'; $dir = opendir($filePath); while ($file = readdir($dir)) { if (eregi("\.png",$file) || eregi("\.jpg",$file) || eregi("\.gif",$file) ) { $string[] = $file; } } while (sizeof($string) != 0){ $img = array_pop($string); echo "<img src='$filePath$img' width='100px'/>"; } ?> ```
How to get the pictures from folder one by one and display in the page using PHP
[ "", "php", "image", "" ]
I would like to get a regexp that will extract out the following. I have a regexp to validate it (I pieced it together, so it may not be the the best or most efficient). ``` some.text_here:[12,34],[56,78] ``` The portion before the colon can include a period or underline. The bracketed numbers after the colon are coordinates [x1,y1],[x2,y2]... I only need the numbers from here. And here is the regexp validator I was using (for javascript): ``` ^[\w\d\-\_\.]*:(\[\d+,\d+],\[\d+,\d+]) ``` I'm fairly new to regexp but I can't figure out how to extract the values so I can get ``` name = "some.text_here" x1 = 12 y1 = 34 x2 = 56 y2 = 78 ``` Thanks for any help!
Try this regular expression: ``` /^([\w\d-_.]*):\[(\d+),(\d+)],\[(\d+),(\d+)]/ var str = "some.text_here:[12,34],[56,78]"; var match = str.match(/^([\w\d-_.]*):\[(\d+),(\d+)],\[(\d+),(\d+)]/); alert("name = " + match[1] + "\n" + "x1 = " + match[2] + "\n" + "x2 = " + match[3] + "\n" + "y1 = " + match[4] + "\n" + "y2 = " + match[5]); ```
You can use the [match](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/match) method of string: ``` var input = "some.text_here:[12,34],[56,78]"; var matches = input.match(/(.*):\[(\d+),(\d+)\],\[(\d+),(\d+)\]/); var output = { name: matches[1], x1: matches[2], y1: matches[3], x2: matches[4], y2: matches[5] } // Object name=some.text_here x1=12 y1=34 x2=56 y2=78 ```
Help with regexp to extract values from inside brackets
[ "", "javascript", "regex", "parsing", "" ]
I want to insert a image in blob format to db. how to write a program in zend framework. a simple form just choose one image and insert into db.
In your Zend form create a file element: ``` $element = new Zend_Form_Element_File('fileElement'); ``` Then you can insert the uploaded image to your DB in BLOB format like this: ``` $conn = new PDO("mysql:host='host';dbname='database'", 'userName', 'password'); $imagePath = $zendForm->fileElement->getFileName(); $image = file_get_contents('$imagePath'); $sql = "INSERT INTO images (data) values(?)"; $q = $conn->prepare($sql); $q->bindParam(1, $image, PDO::PARAM_LOB); $q->execute(); ```
Read it in as a string using [`file_get_contents`](http://www.php.net/file_get_contents) and store that. That said, it is seldom a good idea to store the actual image data in the database. It is better practice to generate a unique filename and store that in the DB instead.
how to insert a image into Db as blob in ZendFramework
[ "", "php", "zend-framework", "" ]
I want to include some charts on my website and I'm looking for a good cross-browser charting package - what are my options?
I prefer jQuery one: <http://www.flotcharts.org/> Examples: <http://people.iola.dk/olau/flot/examples/>
Google Chart API is really powerful, and unlike flot does not rely on javascript being enabled. <http://code.google.com/apis/chart/>
What cross-browser charting packages are available?
[ "", "javascript", "browser", "charts", "" ]
Use case: the "I forgot my password" button. We can't find the user's original password because it's stored in hashed form, so the only thing to do is generate a new random password and e-mail it to him. This requires cryptographically unpredictable random numbers, for which mt\_rand is not good enough, and in general we can't assume a hosting service will provide access to the operating system to install a cryptographic random number module etc. so I'm looking for a way to generate secure random numbers in PHP itself. The solution I've come up with so far involves storing an initial seed, then for each call, ``` result = seed seed = sha512(seed . mt_rand()) ``` This is based on the security of the sha512 hash function (the mt\_rand call is just to make life a little more difficult for an adversary who obtains a copy of the database). Am I missing something, or are there better known solutions?
You can also consider using OpenSSL openssl\_random\_pseudo\_bytes, it's available since PHP 5.3. ``` string openssl_random_pseudo_bytes ( int $length [, bool &$crypto_strong ] ) ``` > Generates a string of pseudo-random bytes, with the number of bytes determined by the length parameter. > It also indicates if a cryptographically strong algorithm was used to produce the pseudo-random bytes, and does this via the optional crypto\_strong parameter. It's rare for this to be FALSE, but some systems may be broken or old. <http://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php> Since PHP 7 there is also `random_bytes` function available ``` string random_bytes ( int $length ) ``` <http://php.net/manual/en/function.random-bytes.php>
I strongly recommend targeting /dev/urandom on unix systems or the crypto-api on the windows platform as an entropy source for passwords. I can't stress enough the importance of realizing hashes are NOT magical entropy increasing devices. Misusing them in this manner is no more secure than using the seed and rand() data before it had been hashed and I'm sure you recognize that is not a good idea. The seed cancels out (deterministic mt\_rand()) and so there is no point at all in even including it. People think they are being smart and clever and the result of their labor are fragile systems and devices which put the security of their systems and the security of other systems (via poor advice) in unecessary jeopardy. Two wrongs don't make a right. A system is only as strong as its weakest part. This is not a license or excuse to accept making even more of it insecure. --- Here is some PHP code to obtain a secure random 128-bit string, from [this comment at php.net by Mark Seecof](http://www.php.net/manual/en/function.mt-rand.php#83655): > "If you need some pseudorandom bits for security or cryptographic purposes (e.g.g., random IV for block cipher, random salt for password hash) mt\_rand() is a poor source. On most Unix/Linux and/or MS-Windows platforms you can get a better grade of pseudorandom bits from the OS or system library, like this: > > ``` > <?php > // get 128 pseudorandom bits in a string of 16 bytes > > $pr_bits = ''; > > // Unix/Linux platform? > $fp = @fopen('/dev/urandom','rb'); > if ($fp !== FALSE) { > $pr_bits .= @fread($fp,16); > @fclose($fp); > } > > // MS-Windows platform? > if (@class_exists('COM')) { > // http://msdn.microsoft.com/en-us/library/aa388176(VS.85).aspx > try { > $CAPI_Util = new COM('CAPICOM.Utilities.1'); > $pr_bits .= $CAPI_Util->GetRandom(16,0); > > // if we ask for binary data PHP munges it, so we > // request base64 return value. We squeeze out the > // redundancy and useless ==CRLF by hashing... > if ($pr_bits) { $pr_bits = md5($pr_bits,TRUE); } > } catch (Exception $ex) { > // echo 'Exception: ' . $ex->getMessage(); > } > } > > if (strlen($pr_bits) < 16) { > // do something to warn system owner that > // pseudorandom generator is missing > } > ?> > ``` > > NB: it is generally safe to leave both the attempt to read /dev/urandom and the attempt to access CAPICOM in your code, though each will fail silently on the other's platform. Leave them both there so your code will be more portable."
Secure random number generation in PHP
[ "", "php", "security", "hash", "random", "" ]
I'm thinking about learning ruby and python a little bit, and it occurred to me, for what ruby/python is good for? When to use ruby and when python, or for what ruby/python is not for? :) What should I do in these languages? thanks
They are good for mostly for rapid prototyping, quick development, dynamic programs, web applications and scripts. They're general purpose languages, so you can use them for pretty much everything you want. You'll have smaller development times (compared to, say, Java or C++), but worse performance and less static error-checking. You can also develop desktop apps on them, but there may be some minor complications on shipping (since you'll usually have to ship the interpreter too). You shouldn't do critical code or heavy computations on them - if you need these things, make them on a faster language (like C) and make a binding for the code. I believe Python is better for this than Ruby, but I could be wrong. (OTOH, Ruby has a stronger metaprogramming)
If you want to know what people actually use them for, check out [Python Package Index](http://pypi.python.org/pypi), [RubyForge](http://rubyforge.org/), and search [SourceForge](http://web.sourceforge.com/) or even StackOverflow. As shylent says, you can easily get into holy wars about what they *should* be used for. Both Ruby and Python are popular especially for prototyping, but you can also build production software like [Ruby on Rails](http://rubyforge.org/), [Zope](http://www.zope.org/), and [Mercurial](http://mercurial.selenic.com/wiki/). What one would not use them for is code that is performance-critical (most isn't) or close to the metal.
python and ruby - for what to use it?
[ "", "python", "ruby", "" ]
I'm creating a tree-structure of categories with parentid's which can be called from children in such a way: ``` ID | Name | ParentID 1 1 0 2 2 1 3 3 2 4 4 1 ``` Resulting in this: ``` 1 = 1 2 = 1 -> 2 3 = 1 -> 2 -> 3 4 = 1 -> 4 ``` which means **3 is a child of 2**, which is a child of 1. when trying to get this idea (with the -> to show what relations are set) I only get to the second grade (1 -> 2) but not to the third (1->2->3) because of the looping function I use for it. ``` //put all ID's in an array while ($row2 = $connector->fetchArray($result2)){ $id = $row2['ID']; $parents[$id] = $row2['name']; } // show the tree-structure while ($row = $connector->fetchArray($result)){ if($row['parentid']!=0)echo $parents[$row['parentid']].' -&gt; '; echo $row['name'].' - &nbsp;&nbsp; '; echo '<br>'; } ``` I'd like two things to change: > 1. have the code automatically generate a tree sized as necessary. > 2. in the while-loops i have to select the $result twice (once as $result, once as $result2) to make it work. these $result's have exactly the same database-query: > `SELECT ID,name,parentid FROM categories` to fetch results from. I'd like to only declare this once. **Thanks for all the good answers. I've gone with the easiest, less-code-to-implement approach:** ``` $result = $connector->query('SELECT ID,name,parentid FROM categories'); // Get an array containing the results. $parents = array(); while ($row = $connector->fetchArray($result)){ $id = $row['ID']; $parents[$id] = array('ID' => $row['ID'],'name' => $row['name'],'parentid' => $row['parentid']); } foreach ($parents as $id => $row){ $pid=$id; $arrTmp= array(); do { // iterate through all parents until top is reached $arrTmp[]=$pid; $pid = $parents[$pid]['parentid']; }while ($pid != 0); $arrTmp = array_reverse($arrTmp); foreach($arrTmp as $id){ echo $parents[$id]['name'].' -&gt; '; } echo '<br>'; } ```
If you really want to do hierachies with parent ids(suitable only for small number of items/hierachies) I modified your code a little bit(I did not test it so there may be some syntax errors): ``` //put all recordsets in an array to save second query while ($row2 = $connector->fetchArray($result2)){ $id = $row2['ID']; $parents[$id] = array('name' => $row2['name'],'parent' => $row2['parentid']); } // show the tree-structure foreach ($parents as $id => $row){ $pid = $row['parentid']; while ($pid != 0){ // iterate through all parents until top is reached echo $parents[$pid]['name'].' -&gt; '; $pid = $parents[$pid]['parentid']; } echo $parents[$id]['name'].' - '; echo '<br>'; } ``` To answer your comment: ``` $parents = array(); $parents[2] = array('ID'=>2,'name'=>'General','parentid'=>0); $parents[3] = array('ID'=>3,'name'=>'Gadgets','parentid'=>2); $parents[4] = array('ID'=>4,'name'=>'iPhone','parentid'=>3); foreach ($parents as $id => $row){ $pid=$id; $arrTmp= array(); do { // iterate through all parents until top is reached $arrTmp[]=$pid; $pid = $parents[$pid]['parentid']; }while ($pid != 0); $arrTmp = array_reverse($arrTmp); foreach($arrTmp as $id){ echo $parents[$id]['name'].' -&gt; '; } echo '<br>'; } ``` Prints out: > General -> > > General -> Gadgets -> > > General -> Gadgets -> iPhone ->
Rather than have PHP organize the items into a tree, why not ask the database to do it for you? I found this [article on hierarchical data](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/) to be very good and the examples are almost identical to yours. --- **EDIT** The SQL for getting the full tree using the Adjacency Model is not ideal. As the article explains it requires rather a lot of joins for even a small hierarchy. Is it not possible for you to use the Nested Set approach? The SQL stays the same regardless of the size of the hierarchy and INSERT and DELETE shouldn't be very difficult either.
how to loop over looped elements in Php?
[ "", "php", "recursion", "tree", "while-loop", "" ]
I was just wondering if any one knew a function to remove ALL classes from a string in php.. Basically I only want ``` <p> ``` tags rather than ``` <p class="..."> ``` If that makes sense :)
A fairly naive regex will probably work for you ``` $html=preg_replace('/class=".*?"/', '', $html); ``` I say naive because it would fail if your body text happened to contain class="something" for some reason!. It could be made a little more robust by looking for class="" inside angled bracketted tags if need be.
Maybe it's a bit overkill for your need, but, to parse/validate/clean HTML data, the best tool I know is [HTML Purifier](http://htmlpurifier.org/) It allows you to define which tags, and which attributes, are OK ; and/or which ones are not ; and it gives valid/clean (X)HTML as output. *(Using regexes to "parse" HTML seems OK at the beginning... And then, when you want to add specific stuff, it generally becomes hell to understand/maintain)*
strip all classes from p tags
[ "", "php", "class", "strip", "" ]
My query is used in cases that "(function() {...})();" Given that I am not a plugin. For example "<http://piecesofrakesh.blogspot.com/2009/03/downloading-javascript-files-in.html>" ``` (function() { var s = [ "/javascripts/script1.js", "/javascripts/script2.js" ]; var sc = "script", tp = "text/javascript", sa = "setAttribute", doc = document, ua = window.navigator.userAgent; for(var i=0, l=s.length; i<l; ++i) { if(ua.indexOf("MSIE")!==-1 || ua.indexOf("WebKit")!==-1) { doc.writeln("<" + sc + " type=\"" + tp + "\" src=\"" + s[i] + "\" defer></" + sc + ">"); } else { var t=doc.createElement(sc); t[sa]("src", s[i]); t[sa]("type", tp); doc.getElementsByTagName("head")[0].appendChild(t); } } })(); ``` Or ``` var s = [ "/javascripts/script1.js", "/javascripts/script2.js" ]; ... ``` Thank you.
This is done to avoid naming conflicts. When you declare a function, that function has its own namespace for variables. By wrapping the code in a function that is immediately invoked, you avoid overwriting global variables with your own values. In this case `s` and `sc` are assigned a value. If you did that at the global scope and other scripts were already using variables with those names for a different purpose, that would cause those other scripts to fail. By introducing the new scope, the identifiers `s` and `sc` now refer to different (locally-bound) variables than the variables named `s` and `sc` that exist at the global scope.
Maybe these questions will help you out: * [Difference between (function(){})(); and function(){}();](https://stackoverflow.com/questions/423228/difference-between-function-and-function) * [What do parentheses surrounding a JavaScript object||function||class declaration mean?](https://stackoverflow.com/questions/440739/what-do-parentheses-surrounding-a-javascript-objectfunctionclass-declaration) * [Javascript: var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname)
When should I use the syntax "(function() {...})();"?
[ "", "javascript", "" ]
I had this idea of registering an event in a base custom page on every button. I can check if it was a save or edit and then do an authorization and validation. Derived pages would still handle the click event to do the specifics for saving on that page. I wasn't sure which events would happen first. (but it probably is in order of wireup) If the parent page runs first, I can get expected behavior by setting an IsAuthorized or IsValidated property and checking that in each derived page's click handler. Anyhow, is there a way to ensure the base page's event handler runs and completes first, or is there any way to salvage this? **EDIT: Am I overlooking a simpler design that doesn't require adding boiler plate code to every edit/save/update button hander in the application? And what is the right way for one event hander to communicate with another? For example the base page needs to communicate success or failure validation, the derived class needs to communicate success or failure of the save so it can be recorded in the audit.** ``` //Base page-- seems like this will work if events happen in order of wireup. protected override void OnInit(EventArgs e) { foreach (Control possibleButton in Controls) { if(possibleButton is Button) { Button button = (Button) possibleButton; button.Command += ButtonCommandPreconditions; } } base.OnInit(e); foreach (Control possibleButton in Controls) { if(possibleButton is Button) { Button button = (Button) possibleButton; button.Command += ButtonCommandPostconditions; } } } void ButtonCommandPreconditions(object sender, CommandEventArgs e) { if(e.CommandName=="Save" || e.CommandName=="Edit") { //Stuff that needs to happen before other handler //Validate, display failures-- maybe set IsValdated property //Check for POST/GET, throw exception on GET. //Check for ID, throw exception on anonymous user //Check for authorization //Display authorization failures-- maybe set IsAuthorized property } } void ButtonCommandPostconditions(object sender, CommandEventArgs e) { if(e.CommandName=="Save" || e.CommandName=="Edit") { //Stuff that needs to happen *after* other handler //Log save } } ``` Edit: Modified code to reflect that event handers are supposed to be handled in order of wireup.
While I am not prepared to offer a solution (as that would require rather involved understanding of your design), aside from telling you to separate your "Save" (and similar events') logic into their own class hierarchy, and call them in one life from the event handlers. However, I can comment on your original question (before your edit in bold). The problem with your setup is that while you can raise events in a specific order, no event in any .Net Framework is guaranteed order of delivery. They may look ordered when you test on your dev machine, but in practical deployment, the moment the system load goes high the events will be the first things to get deferred in favor of other operations. Event **arrival** to their listeners can essentially become random. You should never build your logic based on the order in which events are received. Each event must only consider current state, it cannot assume anything about any other event. Your chaining of events will break when you need it the most.
Events are just multicast delegates, so the event handlers would be raised in the order that they were added to the event. I would advise against this to be honest. Even if it works, it's pretty opaque - you've got two separate event handlers in different classes handling the same event with no apparent tie between them. It would be a better practice to bubble the event to the parent handler for processing from each of your inherited pages before doing their own processing. That way there is a clear connection, the code is easy to follow, and you don't have to rely on assumptions about event ordering. --- **EDIT for new questions:** > And what is the right way for one > event hander to communicate with > another? You should see my answer in [this post.](https://stackoverflow.com/questions/1081642/how-do-you-manage-the-order-of-firing-events-in-asp-net/1081655#1081655) Event handlers are really not meant to communicate with one another in ASP.Net (at least for WebControl/page lifecycle event handlers), as there is no guarantee on firing order. If you have event handlers relying on information being set in sibling event handlers, there is probably a flaw in your design. > For example the base page needs to > communicate success or failure > validation, the derived class needs to > communicate success or failure of the > save so it can be recorded in the > audit. There's really a couple of ways to handle this. First off, simply make your base class call abstract or virtual methods that can be overridden in the derived pages. During the button click handler in your base page, do all your validation, then call into the abstract "DoSave()" method of your derived pages, and check to make sure it succeeded. Or, write your own events, and raise them when need be. Create a "Validation" event in your base class, and have your derived pages subscribe to it if they need to respond. Make sure your base class raises it when it's done validating. Create a "Saved" event in your base class, an event handler for it, and have your base class subscribe to it. Have your [derived classes raise the event](https://stackoverflow.com/questions/756237/c-raising-an-inherited-event) when they are done saving. Now the base class can handle the logging of it. --- I would like to add that it seems like you're loading an awful lot of stuff into the base class button clicks. Can you do the anonymous ID and GET/POST check when the page renders, and just not render the buttons if they don't have permission?
How to get events to be handled in a particular order in C#?
[ "", "c#", "asp.net", "events", "event-handling", "" ]
I have my templated container class that looks like this: ``` template< class KeyType, class ValueType, class KeyCompareFunctor = AnObnoxiouslyLongSequenceOfCharacters<KeyType>, class ValueCompareFunctor = AnObnoxiouslyLongSequenceOfCharacters<ValueType> > class MyClass { [...] } ``` Which means that when I instantiate an object of this class, I can do it several different ways: ``` MyClass<MyKeyType, MyValueType> myObject; MyClass<MyKeyType, MyValueType, MyCustomKeyCompareFunctor> myObject; MyClass<MyKeyType, MyValueType, MyCustomKeyCompareFunctor, MyCustomValueCompareFunctor> myObject; ``` Those are all good. The problem comes when I want to instantiate a MyClass that uses a non-default version of the ValueCompareFunctor argument, but I still want to use the default value of the KeyCompareFunctor argument. Then I have to write this: ``` MyClass<MyKeyType, MyValueType, AnObnoxiouslyLongSequenceOfCharacters<MyKeyType>, MyCustomValueCompareFunctor> myObject; ``` It would be much more convenient if I could somehow omit the third argument and just write this: ``` MyClass<KeyType, ValueType, MyCustomValueCompareFunctor> myObject; ``` Since the MyCustomValueCompareFunctor works only on objects of type MyValueType and not on objects of type MyKeyType, it seems like the compiler could at least theoretically work out what I meant here. Is there a way to do this in C++?
In general, both in templates and functions or methods, C++ lets you use default for (and thereby omit) only *trailing* parameters -- no way out. I recommend a template or macro to shorten `AnObnoxiouslyLongSequenceOfCharacters<MyKeyType>` to `Foo<MyKeyType>` -- not perfect, but better than nothing.
No. The closest you can come is to allow users to specify some sentinel type - like `void` - meaning "use default value here", and use template metamagic inside your class to `typedef` the real default if `void` was given to you. But this probably isn't a good idea from readability point of view.
C++: Default values for template arguments other than the last ones?
[ "", "c++", "templates", "arguments", "default", "" ]
When I need to get the class name inside of one of its methods I just call: ``` typeid(*this).name() ``` (then I split the result into tokens and get the class name) Now I have to define a static member variable and need to get the class name for that. But I`m not in a method! So, I cannot use (\*this). Initially, I thought I could do something like: ``` #define INIT_STAT_VAR const char * cname = typeid(*this).name; int cname##::var = 1; ``` Any idea how I could get the class name for the static member variable definition? ( no, I cannot just write the name of the class directly for the definition ;] ) thanks!
I don't think it is directly possible to do what you want - as a static method doesn't get an object pointer it can't call `typeid` on it. You could create a temporary object in the static method and use that on typeid, but that pretty much goes against having it as a static method. Another solution (if you can guarantee that at least 1 instance of the class is defined) would be to create a static member variable which you initialise once in the Constructor, and then access from a static method. It's a little hacky, but works: ``` #include <typeinfo> #include <string> class Foo { public: Foo() { if (name == NULL) { const std::type_info& id = typeid(*this); name = new std::string(id.name()); } // Normal object creation. } static std::string getName() { return *name; } private: static std::string* name; }; std::string* Foo::name = NULL; ```
Use the `__class__` macro, if your compiler supports it.
get static int variable class name with typeid(*this).name for its own definition - C++
[ "", "c++", "visual-studio", "" ]
While reading a book on C#, I have come across code that uses the @ to "overload" or use a C# keyword as an identifier. I am guessing this is not a good practice, as it leads to ambiguity. Am I correct in thinking this, or are there times where this should be used ?
Indeed, it is almost always worth avoiding this. The main **valid** time it might be useful is when dealing with an external library (from another language) that has a class / etc that happens to be a C# keyword, but I'll admit I've **never** had this problem in reality. It helps that C# allows you to rename method argument names when overriding / implementing interfaces, so that avoids one common set of cases. Another (arguably lazy) use is in code generation; if you always prefix fields / variables / etc with @theName, then you don't have to worry about special cases. Personally, I simply cross-check against a list of C# keywords / contextual keywords, and add something like underscore. The @ symbol's other use (verbatim string literals) is @"much more useful".
I've used it in asp.net MVC Views where you are defining a css class using a HtmlHelper. ``` <%= Html.TextBox("Name", null, new { @class = "form-field" }) %> ```
Best practices for using @ in C#
[ "", "c#", "keyword", "" ]
What is a class, an object and an instance in Java?
Java (and any other programming language) is modeled in terms of *types* and *values*. At the theoretical level, a *value* is a representation for some quantum of information, and a *type* is a set of values. When we say value X *is an instance* of type Y, we are simply saying that X is a member of the set of values that is the type Y. So that's what the term "instance" really means: it describes a relationship not a thing. The type system of the Java programming language supports two kinds of types, *primitive types* and *reference types*. The reference types are further divided into the *classes* and *array types*. A Java *object* is an instance of a reference type. > An object is a class instance or an array. ([JLS 4.3.1](https://docs.oracle.com/javase/specs/jls/se10/html/jls-4.html#jls-4.3.1)) That's the type theoretic view. In practice, most Java developers treat the words "instance" and "object" as synonyms. (And that includes me then I'm trying to explain something quickly.) And most developers use the word "value" rather than "instance" to refer to an instance of a primitive type.
A **class** is a blueprint which you use to create **objects**. An object is an **instance** of a class - it's a concrete 'thing' that you made using a specific class. So, 'object' and 'instance' are the same thing, but the word 'instance' indicates the relationship of an object to its class. This is easy to understand if you look at an example. For example, suppose you have a class `House`. Your own house is an object and is an instance of class `House`. Your sister's house is another object (another instance of class `House`). ``` // Class House describes what a house is class House { // ... } // You can use class House to create objects (instances of class House) House myHouse = new House(); House sistersHouse = new House(); ``` The class `House` describes the concept of what a house is, and there are specific, concrete houses which are objects and instances of class `House`. Note: This is exactly the same in Java as in all object oriented programming languages.
The difference between Classes, Objects, and Instances
[ "", "java", "class", "object", "instance", "" ]
I'm struggling with creating a SQL query involving aggregates using PostgreSQL. Consider the following tables: ``` CREATE TABLE thing ( id INT NOT NULL PRIMARY KEY, price NUMERIC(10,2) NOT NULL, description VARCHAR(255) NOT NULL, url VARCHAR(255) NOT NULL, location_id INT NOT NULL REFERENCES location(id) ) CREATE TABLE location ( id INT NOT NULL PRIMARY KEY, type INT NOT NULL, name VARCHAR(255) NOT NULL ) ``` Now, I would like to get all the thing records for each location with location.type = xxx that have the lowest price. Something like: ``` SELECT min(price) FROM thing INNER JOIN location ON (thing.location_id = location.id) WHERE type = xxx GROUP BY location_id ``` This will list me the lowest price for each location with type xxx, but how can I get the rows (or their primary keys) of these columns from table thing?
Use this `PostgreSQL` extension: ``` SELECT DISTINCT ON (location.id) thing.* FROM location JOIN thing ON thing.location_id = location_id WHERE type = 1 ORDER BY location.id ASC, price ASC ``` This will select only the first row for each `location.id`. Since your rows are sorted by `location.id` then by `price`, this will be the row with the minimal price. In new `PostgreSQL 8.4`, you can also use window functions: ``` SELECT * FROM ( SELECT thing.*, ROW_NUMBER() OVER (PARTITION BY location_id ORDER BY price) AS rn FROM location JOIN thing ON thing.location_id = location_id WHERE type = 1 ) q WHERE rn = 1 ```
Perhaps use a sub query ``` SELECT t.id,t.description,t.price FROM ( SELECT location_id, min(price) FROM thing INNER JOIN location ON (thing.location_id = location.id) WHERE type = xxx GROUP BY location_id ) AS lowest INNER JOIN thing AS t ON t. location_id = lowest.location_id; ```
Get primary key of aggregated, group by SQL query using PostgreSQL
[ "", "sql", "postgresql", "" ]
I've got a situation where I have two different webapps running on a single server, using different ports. They're both running Java's Jetty servlet container, so they both use a cookie parameter named JSESSIONID to track the session id. These two webapps are fighting over the session id. * Open a Firefox tab, and go to WebApp1 * WebApp1's HTTP response has a set-cookie header with JSESSIONID=1 * Firefox now has a Cookie header with JSESSIONID=1 in all it's HTTP requests to WebApp1 * Open a second Firefox tab, and go to WebApp2 * The HTTP reqeust to WebApp2 also has a Cookie header with JSESSIONID=1, but in the doGet, when I call `req.getSession(false);` I get `null`. And if I call `req.getSession(true)` I get a new Session object, but then the HTTP response from WebApp2 has a set-cookie header with JSESSIONID=20 * Now, WebApp2 has a working Session, but WebApp1's session is gone. Going to WebApp1 will give me a new session, blowing away WebApp2's session. * Continue forever So the Sessions are thrashing between each web app. I'd really like for the `req.getSession(false)` to return a valid session if there's already a JSESSIONID cookie defined. One option is to basically reimplement the Session framework with a HashMap and cookies called WEBAPP1SESSIONID and WEBAPP2SESSIONID, but that sucks, and means I'll have to hack the new Session stuff into ActionServlet and a few other places. This must be a problem others have encountered. Is Jetty's `HttpServletRequest.getSession(boolean)` just crappy?
I had a similar problem: One or more instances of the same application on localhost on different ports, choosen at application start time, each using its own jetty instance. After a while, I came up with this: * Wait for jetty to initialize * use jetty's SocketManager to get the port (`socketManager.getLocalPort()`) * set the cookie name through the SessionManager `(sessionHandler.getSessionManager().setSessionCookie(String)`) This way I have a difference cookie name for each instance - thus no interference anymore.
It's not Jetty's problem, it's how the cookie specification was defined. Beside the name/value pair, a cookie may also contain an expiration date, a path, a domain name, and whether the cookie is secure (i.e. intended only for SSL connections). The port number is not listed in the above ;-) so you'll need to vary either the path or the domain, as stepancheg says in his answer.
JSESSIONID collision between two servers on same ip but different ports
[ "", "java", "http", "cookies", "jetty", "" ]
I've registered a message filter using ``` Application.AddMessageFilter(m_messageFilter); ``` using this I can log all of the mouse clicks a user makes in the application's user interface. However, one dialog is run on a separate thread, with code something like: ``` void Run() { using( MyDialog dialog = new MyDialog() ) { dialog.ShowDialog(); } } Thread thread = new Thread(Run); ``` The message filter I set up doesn't get to see messages that go to this window. How can I get them (ideally without being too intrusive)? I tried to override MyDialog.PreProcessMessage, but I'm confused that this never seems to get called. Thanks.
Pretty much all Application methods, including AddMessageFilter, are thread specific. So, if you want to filter the messages on the other thread you have to call AddMessageFilter on that thread. Just change your Run method to: ``` void Run() { using( MyDialog dialog = new MyDialog() ) { Application.AddMessageFilter(new MyMessageFilter()); Application.Run(dialog); } } ```
I suppose you should rewrite your code in the following way ``` void Run() { using( MyDialog dialog = new MyDialog() ) { Application.Run(); dialog.ShowDialog(); } } ``` Or may be ``` Application.Run(dialog); ``` inside using { ... } will also work Application.Run() begins running a standard application message loop on the **current** thread. Usually message loop is working only in the main thread. Without Application.Run() standard message loop will not start in the second thread. Here is an article [Creating a Splash Screen Form on a Separate Thread](http://msdn.microsoft.com/en-us/library/aa446493.aspx) where similar technique was used - second form (SlpashScreen) is started in another thread and they call Application.Run(splash); in this second thread. As one can get from this article, running forms in different threads requires from a developer to be very careful regarding how you will close/dispose forms.
How to see windows messages of a dialog shown with a second thread?
[ "", "c#", "winforms", "multithreading", "messaging", "" ]
I would like to try and build a Skype Addon in C#. Is there an API?
<https://developer.skype.com/Download> youll need a c# wrapper to use their sdks
I am talking about July 2010. 1. Skype has a very bad documentation out there. Putting more or less business tricks rather then developers freedom 2. Personally i dont prefer this, but its ok to use for C#: <http://code.msdn.microsoft.com/SEHE> 3. Working in Linux/Unix is nightmare to make things for Skype. God bless skype for linux.
Skype Addon in C#
[ "", "c#", "skype", "add-on", "" ]
Which function should I use to output text to the "Output" window in Visual Studio? I tried `printf()` but it doesn't show up.
[OutputDebugString](http://msdn.microsoft.com/en-us/library/aa363362%28VS.85%29.aspx) function will do it. example code ``` void CClass::Output(const char* szFormat, ...) { char szBuff[1024]; va_list arg; va_start(arg, szFormat); _vsnprintf(szBuff, sizeof(szBuff), szFormat, arg); va_end(arg); OutputDebugString(szBuff); } ```
If this is for debug output then [OutputDebugString](http://msdn.microsoft.com/en-us/library/aa363362%28VS.85%29.aspx) is what you want. A useful macro : ``` #define DBOUT( s ) \ { \ std::ostringstream os_; \ os_ << s; \ OutputDebugString( os_.str().c_str() ); \ } ``` This allows you to say things like: ``` DBOUT( "The value of x is " << x ); ``` You can extend this using the `__LINE__` and `__FILE__` macros to give even more information. For those in Windows and wide character land: ``` #include <Windows.h> #include <iostream> #include <sstream> #define DBOUT( s ) \ { \ std::wostringstream os_; \ os_ << s; \ OutputDebugStringW( os_.str().c_str() ); \ } ```
How to write to the Output window in Visual Studio?
[ "", "c++", "visual-c++", "" ]
Can you tell me what's the best way to send objects through NamedPipes in .net 3.5?
Use WCF on a [NetNamedPipeBinding](http://msdn.microsoft.com/en-us/library/system.servicemodel.netnamedpipebinding.aspx). See also [Expose a WCF Service through a Named Pipes binding](https://stackoverflow.com/questions/184878/expose-a-wcf-service-through-a-named-pipes-binding).
Serialize your object by [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx) than [send it as a text](http://www.davidthielen.info/programming/2008/12/named-pipes-in-net.html) and deserialize in the other side, or use WCF named pipes binding as Remus suggests
How to send object through NamedPipe in .NET 3.5?
[ "", "c#", ".net", ".net-3.5", "named-pipes", "" ]
I am writing a simple profanity filter in PHP. Can anyone tell my why, in the following code, the filter works (it will print [explicit]) for the $vowels array and not the $lines array which I constructing from a text file? ``` function clean($str){ $handle = fopen("badwords.txt", "r"); if ($handle) { while (!feof($handle)) { $array[] = fgets($handle, 4096); } fclose($handle); } $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U"); $filter = "[explicit]"; $clean = str_replace($array, $filter, $str); return $clean; } ``` When using $vowels in replace of $array, it works except for lowercase vowels which return: ``` [[expl[explicit]c[explicit]t]xpl[explicit]c[explicit]t] instead of [explicit] ``` Not sure why that is going on, either. Any ideas? Thanks!
I modified Davethegr8's solution to get the following working example: ``` function clean($str){ global $clean_words; $replacement = '[explicit]'; if(empty($clean_words)){ $badwords = explode("\n", file_get_contents('badwords.txt')); $clean_words = array(); foreach($badwords as $word) { $clean_words[]= '/(\b' . trim($word) . '\b)/si'; } } $out = preg_replace($clean_words, $replacement, $str); return $out; } ```
Because the output of the filter contains lower case vowels, which are also the characters you're filtering. Namely you're creating a feedback loop.
Trouble with simple PHP profanity filter
[ "", "php", "filter", "" ]
I am trying to write an SSL client that sends mail using the javax.mail API. The problem I am having is that the server request that I use SSL, but the server is also configured with a non-standard SSL certificate. The web pages I have found say that I need to install the certificate into the trust store. I don't want to do that (I don't have the necessary permissions.) 1. Is there a way to get Java to just ignore the certificate error and accept it? 2. Failing that, is there a way to have the trust store be local for my program, and not installed for the whole JVM?
You need to create a fake TrustManager that accepts all certificates, and register it as a manager. Something like this: ``` public class MyManager implements com.sun.net.ssl.X509TrustManager { public boolean isClientTrusted(X509Certificate[] chain) { return true; } public boolean isHostTrusted(X509Certificate[] chain) { return true; } ... } com.sun.net.ssl.TrustManager[] managers = new com.sun.net.ssl.TrustManager[] {new MyManager()}; com.sun.net.ssl.SSLContext.getInstance("SSL"). .init(null, managers, new SecureRandom()); ```
Working code ( in jdk1.6.0\_23) for #1. Imports ``` import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.cert.X509Certificate; ``` The actual trust all TrustManager code. ``` TrustManager trm = new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { trm }, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); ```
Is it possible to get Java to ignore the "trust store" and just accept whatever SSL certificate it gets?
[ "", "java", "ssl", "truststore", "" ]
I am trying to access stored procedures from my ASP.NET / C# web-application. Is there a particularly good way to do so (also a good way to pass parameters to it)? I followed following steps and absolutely don't like the approach, as you enter the procedure as a string (un-debugable): <http://www.c-sharpcorner.com/UploadFile/dclark/InsOutsinCS11302005072332AM/InsOutsinCS.aspx>
If you were to use LinqToSQL, ScottGU has some excellent [blog posts](http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx) on the subject.
I like [SubSonic](http://subsonicproject.com/docs/Main_Page). SubSonic will generate a DAL for you based on your database schema. Most folks use the generated SubSonic objects with the activerecord or simplerepository pattern to work with the database, but Subsonic also generates strongly-typed methods to wrap your stored procedures and views. It is a rather basic example, but you can make a stored procedure call similar to the following: ``` SubSonic.StoredProcedure sp = Dal.StoredProcedures.UpdatePassword(id, pw); DataSet ds = sp.GetDataSet(); ``` In the code above, the StoredProcedures class includes a strongly-typed method for the UpdatePassword stored procedure. It works great for me. The [SubSonic Docs are here.](http://subsonicproject.com/docs/Main_Page)
A good way to access stored procedure on SQL Server 2008 from C#
[ "", "c#", "asp.net", "ado.net", "" ]
getc (stdin) reads keyboard input to integers, but what if I want to read keyboard input to character strings? ``` #include "stdafx.h" #include "string.h" #include "stdio.h" void CharReadWrite(FILE *fin); FILE *fptr2; int _tmain(int argc, _TCHAR* argv[]) { char alpha= getc(stdin); char filename=alpha; if (fopen_s( &fptr2, filename, "r" ) != 0 ) printf( "File stream %s was not opened\n", filename ); else printf( "The file %s was opened\n", filename ); CharReadWrite(fptr2); fclose(fptr2); return 0; } void CharReadWrite(FILE *fin){ int c; while ((c=fgetc(fin)) !=EOF) { putchar(c);} } ```
Continuing with the theme of getc you can use `fgets` to read a line of input into a character buffer. E.g. ``` char buffer[1024]; char *line = fgets(buffer, sizeof(buffer), stdin); if( !line ) { if( feof(stdin) ) { printf("end of file\n"); } else if( ferror(stdin) ) { printf("An error occurerd\n"); exit(0); } } else { printf("You entered: %s", line); } ``` Note that ryansstack's answer is a much better, easier and safer solution given you are using C++.
A character (ASCII) is just an unsigned 8 bit integral value, ie. it can have a value between 0-255. If you have a look at an ASCII table you can see how the integer values map to characters. But in general you can just jump between the types, ie: ``` int chInt = getc(stdin); char ch = chInt; // more simple char ch = getc(stdin); // to be explicit char ch = static_cast<char>(getc(stdin)); ``` **Edit:** If you are set on using getc to read in the file name, you could do the following: ``` char buf[255]; int c; int i=0; while (1) { c = getc(stdin); if ( c=='\n' || c==EOF ) break; buf[i++] = c; } buf[i] = 0; ``` This is a pretty low level way of reading character inputs, the other responses give higher level/safer methods, but again if you're set on getc...
How can I read keyboard input to character strings? (C++)
[ "", "c++", "integer", "character", "" ]
i'm just trying to create this little simulator. in a gui, i have two main components - a map, taking up most of the window, and a control panel on the right hand side. now, i'd like to add a time slider across the bottom of the window (running only under the map, not under the control panel). i can do it in the runner class (which initialises the main window), but it should logically belong to the control panel - it fires all the relevant events. is there a way to do it? what swing components should i use and how should i wrap them? (i tried using netbeans for this, but, this being the first time i ever used it, i had little luck). thanks a lot for your help
You could use BorderLayout to achieve the desired result very simply; e.g. ``` JPanel pnl = new JPanel(new BorderLayout()); pnl.add(mapPnl, BorderLayout.CENTER); pnl.add(controlPnl, BorderLayout.EAST); pnl.add(timerPnl, BorderLayout.SOUTH); ``` If you anticipate more components being added to your top level `JPanel` I would suggest looking into `GridBagLayout` as it offers greater flexibility. The fact that your controls and timer are related isn't relevant for the layout of the visual components. Typically you would maintain this relationship at the business object level; e.g. ``` Controller controller = new Controller(); JPanel controlPnl = new MyControlPanel(controller); JPanel timerPnl = new MyTimerPanel(controller.getTimer()); ```
A layout manager like [MiG layout](http://www.miglayout.com/) or [DesignGridLayout](https://designgridlayout.dev.java.net/) will help you layout your controls better. Layout of the controls is one thing and logical separation is another. You can have all the controls in the control panel at the right side and the slider at the bottom be members of the same logical unit.
java gui - overlapping panels?
[ "", "java", "user-interface", "" ]
When I developed a piece of (academic) software using Java, I was forced to use an API that was rather badly implemented. This means that calls to this API for a certain set of input data would sometimes never return. This must have been a bug in the software as the algorithms that it offered were deterministic ones, and sometimes it would terminate on a set of data, sometimes it would run into an infinite loop on the same set of data... However, fixing the API or reimplementing it was simply beyond scope. I even had the source but the API heavily relied on other APIs which were undocumented and without source and had by the time vanished from the web (or never been there?). On the other hand, this "bad" API was the only one out there that solved the specific problem I had, so I really had to stick with it. The question is: what is the cleanest way of dealing with an API that behaves that, well, nasty? When I faced this problem I decided to put the calls to the API into a separate thread. Another thread would then occasionally check if this thread had terminated. If a certain amount of time had passed, I would kill the processing thread using `Thread#stop()` and start the processing again, hoping that it would return the next time. Now, I know (and knew back then) that this method is deprecated and must not be used. But in this academic context it was acceptable to have the software *potentially* run into an undefined state instead of having it crash. It was also not acceptable to just ignore the processing thread that had run into an infinite loop because it did some quite CPU-intensive operations that would slow down the user's machine significantly. Another way which I didn't try is to start the processing in a separate *process* instead of a thread, because a sub-process can be killed cleanly without putting the software in an inconsistent state. Or could the new `SwingWorker` class (which wasn't yet available) have done the job? It has a `cancel()` method, but the docs say that it *"Attempts to cancel execution of this task"*, so it doesn't look like a reliable approach either.
I would recommend the use of a separate process. There is essentially no safe way for one thread to kill a second thread in Java unless the second thread is periodically checking to see if it has been interrupted. The ideal solution would be to use isolates. An isolate is essentially a private virtual machine that a Java app can create, managed and communicate with. In particular, the parent app can safely kill an isolate and all its threads. Reference: [JSR-000121 Application Isolation API Specification - Final Release](https://jcp.org/aboutJava/communityprocess/final/jsr121/index.html) The problem is finding a JVM that supports Isolates.
I'm a big fan of separate processes for this kind of thing. Spawn a sub process and wait for results. If the API is non-deterministic, put the timer thread in a wrapper that makes the bad API into a main program. That way, the subprocess always ends within the given time. It either produces a useful result or a system exit code that indicates failure.
How to isolate your program from calls to a "bad" API?
[ "", "java", "multithreading", "multiprocessing", "" ]
Take the following C code (*K&R pg. 77*) : ``` push(pop() - pop()); /* WRONG */ ``` The book says that since `-` and `/` are not commutative operators, the order in which the 2 `pop` functions are evaluated is necessary (obviously, to get the correct result)...and thus you have to put the result of the first function in a variable first and then proceed with the arithmetic, like such: ``` op2 = pop(); push(op2 - pop()); ``` Apparently this is because the compiler can't guarantee in which order the functions are evaluated (...why?) --- My question is, does C# do this same thing? as in, do I have to worry about this sort of thing when working with C# ? and for that matter, any of the other higher level languages ?
In C# it is left to right: <http://blogs.msdn.com/oldnewthing/archive/2007/08/14/4374222.aspx> --- Re: C++ order > Apparently this is because the compiler can't guarantee in which order the functions are evaluated (...why?) Any particular compiler can guarantee the order. The problem is that the language spec does not specify an order, so each compiler can do whatever it wants. This means you have to add a sequence point between the two method calls if you want to guarantee ordering.
To answer your question about why C doesn't define the order of operation, it's simply because the inventors of C decided it would be valuable to give compiler implementors the opportunity to optimize expression evaluation. They also decided that it was more valuable than giving programmers certainty in expression evaluation. Remember that when C was originally developed, machines were much less capable than today, and there was more interest in giving compilers the optimization leeway. Today, there is often more weight given to safer, more predicatble code.
C#: Order of function evaluation (vs C)
[ "", "c#", "c", "math", "" ]
I have a *simple* requirement: * One browse button opens multiple file choosers. * When file is chosen, its filename gets added to an order list. This works just fine in IE, because i can programatically click on hidden file inputs, but firefox does not let the click event open the file choose dialog. **Question:** What options do i have? I noticed that gmail uses a piece of flash to make this happen, this isnt really an option for me, i need to stick to an html/javascript solution if possible. Thanks.
There's a reason GMail uses a piece of Flash: it is the ~~best~~ least-worst option. Some other sites I've seen use Java applets or their own browser add-on or Active-X component, which I find much more intrusive to the user than Flash. If it were possible with HTML/javascript, you wouldn't see so many sites (like GMail) going out of their way to use flash or Java. **If you're stuck to HTML/Javasctipt**, the next best thing you can do is the way GMail used to do it: put an "attach another file" link below the file selection input field, when the user clicks it another file selection input field is added to the page with javascript, so that they can add an unlimited number of files without navigating away from the page, but they still have to pick them one at a time.
There is not much you can do aside from Flash because the file input fields have been locked down for security over the past few years. If you want, there are several freely available Flash uploaders that will do the trick you want.
gmail type filechooser for firefox
[ "", "javascript", "html", "internet-explorer", "firefox", "webforms", "" ]
I frequent wrap code in a [System.nanoTime()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#nanoTime()) pair in order to timing it. Something like: ``` long start = System.nanoTime(); methodToBeTimed(); long elapsedTime = System.nanoTime() - start; ``` There is any good timing library that helps with this problem? Also homegrown code will be accepted. NB A profiler is not a solution here, since I want to enforce some time constraints in my unit tests, so I want to timing methods **programmatically**.
**Ignore this answer as the project is no longer active** I haven't used it but I came across [perf4j](https://github.com/perf4j/perf4j) recently.
Not a direct answer to your question, but I am also often using this tip to time my code and just wrote the following simple Eclipse -> Surround With template: ``` long startTime = System.currentTimeMillis(); ${line_selection}${cursor} long totalTime = System.currentTimeMillis() - startTime; System.out.println("Total time = " + totalTime); System.out.println(); ```
Java performance timing library
[ "", "java", "performance", "timing", "" ]
I understand you can use the inline keyword or just put a method in a class declaration ala short ctor or a getter method, but does the compiler make the final decision on when to inline my methods? For instance: ``` inline void Foo::vLongBar() { //several function calls and lines of code } ``` Will the compiler ignore my inline declaration if it thinks it will make my code inefficient? As a side issue, if I have a getter method declared outside my class like this: ``` void Foo::bar() { std::cout << "baz"; } ``` Will the compiler inline this under the covers?
Whether or not a fiunction is inlined is, at the end of the day, entirely up to the compiler. Typically, the more complex a function is in terms of flow, the less likely the compiler is to inline it. and some functions, such as recursive ones, simply cannot be inlined. The major reason for not inlining a function is that it would greatly increase the overall size of the code, preventing iot from being held in the processor's cache. This would in fact be a pessimisation, rather than an optimisation. As to letting the programmer decide to shoot himself in the foot, or elsewhere, you can inline the function yourself - write the code that would have gone in the function at what would have been the function's call site.
Yes, the final decision of whether or not to inline your code lies in the C++ compiler. The inline keyword is a suggestion, not a requirement. Here are some details as to how this decision is processed in the Microsoft C++ Compiler * <http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx>
Does the compiler decide when to inline my functions (in C++)?
[ "", "c++", "compiler-theory", "compiler-optimization", "" ]
What's the correct way to get a `JFrame` to close, the same as if the user had hit the `X` close button, or pressed `Alt + F4` (on Windows)? I have my default close operation set the way I want, via: ``` setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ``` It does exactly what I want with the aforementioned controls. This question isn't about that. What I really want to do is cause the GUI to behave in the same way as a press of `X` close button would cause it to behave. Suppose I were to extend `WindowAdaptor`, then add an instance of my adapter as a listener via `addWindowListener()`. I would like to see the same sequence of calls through `windowDeactivated()`, `windowClosing()`, and `windowClosed()` as would occur with the `X` close button. Not so much tearing up the window as telling it to tear itself up, so to speak.
If you want the GUI to behave as if you clicked the `X` close button then you need to dispatch a window closing event to the `Window`. The `ExitAction` from [Closing An Application](http://tips4java.wordpress.com/2009/05/01/closing-an-application/) allows you to add this functionality to a menu item or any component that uses `Action`s easily. ``` frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); ```
``` setVisible(false); //you can't see me! dispose(); //Destroy the JFrame object ``` Not too tricky.
How to programmatically close a JFrame?
[ "", "java", "swing", "jframe", "" ]
I would like to increment two variables in a `for`-loop condition instead of one. So something like: ``` for (int i = 0; i != 5; ++i and ++j) do_something(i, j); ``` What is the syntax for this?
A common idiom is to use the [comma operator](http://en.wikipedia.org/wiki/Comma_operator) which evaluates both operands, and returns the second operand. Thus: ``` for(int i = 0; i != 5; ++i,++j) do_something(i,j); ``` ## But is it really a comma operator? Now having wrote that, a commenter suggested it was actually some special syntactic sugar in the for statement, and not a comma operator at all. I checked that in GCC as follows: ``` int i=0; int a=5; int x=0; for(i; i<5; x=i++,a++){ printf("i=%d a=%d x=%d\n",i,a,x); } ``` I was expecting x to pick up the original value of a, so it should have displayed 5,6,7.. for x. What I got was this ``` i=0 a=5 x=0 i=1 a=6 x=0 i=2 a=7 x=1 i=3 a=8 x=2 i=4 a=9 x=3 ``` However, if I bracketed the expression to force the parser into really seeing a comma operator, I get this ``` int main(){ int i=0; int a=5; int x=0; for(i=0; i<5; x=(i++,a++)){ printf("i=%d a=%d x=%d\n",i,a,x); } } i=0 a=5 x=0 i=1 a=6 x=5 i=2 a=7 x=6 i=3 a=8 x=7 i=4 a=9 x=8 ``` Initially I thought that this showed it wasn't behaving as a comma operator at all, but as it turns out, this is simply a precedence issue - the comma operator has the [lowest possible precedence](http://www.cppreference.com/wiki/operator_precedence), so the expression x=i++,a++ is effectively parsed as (x=i++),a++ Thanks for all the comments, it was an interesting learning experience, and I've been using C for many years!
Try this ``` for(int i = 0; i != 5; ++i, ++j) do_something(i,j); ```
How do I put two increment statements in a C++ 'for' loop?
[ "", "c++", "for-loop", "comma-operator", "" ]
I have two `IList<ICat>` and I'm trying to create a method which takes an `IList<ICat>` and does some work. I'm having problems trying to pass either an `IList<PussyCat>` or `IList<OtherCat>` to it, both `PussyCat` and `OtherCat` implement `ICat`. I've tried: ``` List<PussyCat> cats = ... DoWork((IList<ICat>)cats); ``` and just ``` DoWork(cats); ``` But neither compile. Any ideas?
C# generics are invariant. It means `List<string>` is not a `List<object>`. C# 4.0 introduces [*safe* covariance/contravariance](http://community.bartdesmet.net/blogs/bart/archive/2009/04/13/c-4-0-feature-focus-part-4-generic-co-and-contra-variance-for-delegate-and-interface-types.aspx) but still, you wouldn't be able to pass `List<string>` as `List<object>`. The reason is: ``` List<string> x = new List<string>(); List<object> o = x; // assume this statement is valid o.Add(5); // Adding an integer to a list of strings. Unsafe. Will throw. ``` Arrays, on the other hand are covariant. You can pass a `string[]` to a method that expects `object[]`.
There are two alternatives: 1. Make your method like this: ``` public void DoWork< T > (IList< T > cats_) where T : ICat { //Do work; } ``` 2. The other possibility is to have a method like ``` public void DoWork(IList< ICat > cats_) { //Do work; } ``` and call it in the following manner: ``` { //....Assuming: IList<PussyCat> iListOfPussyCats List<PussyCat> pussyCats = new List<PussyCats>(iListOfPussyCats); DoWork(pussyCats.ConvertAll<ICat>( c => c as ICat); } ```
IList<IWhatever> as a method parameter
[ "", "c#", "generics", "interface", "" ]
How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?
Tested on WinXP, Python 2.6 (3.x also tested) after installing [pywin32](http://sourceforge.net/projects/pywin32/files/) (pywin32-214.win32-py2.6.exe in my case): ``` import win32api, win32con def click(x,y): win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0) click(10,10) ```
Try with the [PyAutoGUI](https://pypi.org/project/PyAutoGUI/) module. It's multiplatform. ``` pip install pyautogui ``` And so: ``` import pyautogui pyautogui.click(100, 100) ``` It also has other features: ``` import pyautogui pyautogui.moveTo(100, 150) pyautogui.moveRel(0, 10) # move mouse 10 pixels down pyautogui.dragTo(100, 150) pyautogui.dragRel(0, 10) # drag mouse 10 pixels down ``` This is much easier than going through all the win32con stuff.
Controlling mouse with Python
[ "", "python", "mouse", "" ]
I'm doing some unit tests for a controller, and I'm mocking the business component. The BC has a public event that I have the controller listening to when the controller is constructed. The problem I'm having is I keep getting an Expectation error stating: "IBC.add\_MessageRaised(MessageEventHandler) Expected#:1 Actual#:0". However, I don't have any expectation of that kind in my test. I'm wondering if it has to do with setting the Controller to listen to an event on a mocked object (the BC in this case). Is there another way I can get the Controller to listen to an event coming from a mock? I'm also trying to think of a way to get the mock to raise the MessageRaised event, but that might be another question altogether. Here is the code: Business Component Interface ``` public interface IBC { event MessageEventHandler MessageRaised; XmlDocument GetContentXml(string path); } ``` Controller ``` private readonly IBC _bc; public Controller(IBC bc) { _bc = bc; _bc.MessageRaised += MessageWatch; } private void MessageWatch(object sender, MessageEventArgs e) { if (MessageRaised != null) MessageRaised(sender, e); } ``` Unit Test ``` MockRepository Mockery = new MockRepository(); TFactory _tFac; IView _view; Presenter _presenter = new Presenter(); IBC _bc = Mockery.DynamicMock<IBC>(); Controller _controller = new Controller(_bc); _tFac = new TFactory(Mockery); _tFac.Create(ref _view, ref _presenter, ref _controller); [Test] public void View_OnGetContentXmlButtonClick_Should_SetXmlInView() { //SETUP XmlDocument xmlDocument = new XmlDocument(); using ( Mockery.Record() ) { SetupResult.For(_view.FilePath).Return("C:\Test.txt"); Expect.Call(_bc.GetContentXml("C:\Test.txt")).Return(xmlDocument); _view.Xml = xmlDocument.InnerXml; } //EXECUTE using ( Mockery.Playback() ) { _presenter.View_OnGetContentXmlButtonClick(); } } ```
I got it to work by combining a few things (not entirely sure how it works, but it does): ``` IEventRaiser _raiser; MockRepository Mockery = new MockRepository(); TFactory _tFac; IView _view; Presenter _presenter = new Presenter(); IBC _bc = Mockery.DynamicMock<IBC>(); _bc.MessageRaised += null; _raiser = LastCall.GetEventRaiser(); Controller _controller = new Controller(_bc); Mockery.BackToRecord(_bc,BackToRecordOptions.None); _tFac = new TFactory(Mockery); _tFac.Create(ref _view, ref _presenter, ref _controller); ``` This made the test in the question work, as well as letting me raise an event from the Mock object in other tests, like: ``` [Test] public void View_OnGetContentXmlButtonClick_When_FileDoesNotExist_Should_RelayMessage() { //SETUP XmlDocument xmlDocument = new XmlDocument(); using (Mockery.Record()) { SetupResult.For(_view.FilePath).Return("C:\Test.txt"); Expect.Call(_bc.GetContentXml("C:\Test.txt")).Return(null); _view.Xml = xmlDocument.InnerXml; _view.Message = MESSAGE_FILE_NOT_EXIST; } //EXECUTE using (Mockery.Playback()) { _presenter.View_OnGetContentXmlButtonClick(); _raiser.Raise(_bc, new MessageEventArgs(MESSAGE_FILE_NOT_EXIST)); } } ``` Hope others find this useful!
It seems the following code uses a mock object and, by using it, causes an expectation to be recorded: ``` Controller _controller = new Controller(_bc); ``` You are using the mock object like this: ``` _bc.MessageRaised += MessageWatch; ``` As a result, you have set up an expectation that an event handler is added to \_bc.MessageRaised. This does not happen in the playback block, so an error is raised. See also [this question](https://stackoverflow.com/questions/519666/is-there-a-way-to-decide-when-a-rhinomocks-mock-starts-recording) about when an object enters the record state. To be honest, I also don't understand why there is an explicit record syntax if objects enter the record state implicitly anyway.
How do I listen to a mocked object's event?
[ "", "c#", "unit-testing", "rhino-mocks", "" ]
I've enjoyed building out a couple simple applications on the GAE, but now I'm stumped about how to architect a music collection organizer on the app engine. In brief, I can't figure out how to filter on multiple properties while sorting on another. Let's assume the core model is an Album that contains several properties, including: * Title * Artist * Label * Publication Year * Genre * Length * List of track names * List of moods * Datetime of insertion into database Let's also assume that I would like to filter the entire collection using those properties, and then sorting the results by one of: * Publication year * Length of album * Artist name * When the info was added into the database I don't know how to do this without running into the exploding index conundrum. Specifically, I'd love to do something like: ``` Albums.all().filter('publication_year <', 1980).order('artist_name') ``` I know that's not possible, but what's the workaround? This seems like a fairly general type of application. The music albums could be restaurants, bottles of wine, or hotels. I have a collection of items with descriptive properties that I'd like to filter and sort. Is there a best practice data model design that I'm overlooking? Any advice?
There's a couple of options here: You can filter as best as possible, then sort the results in memory, as Alex suggests, or you can rework your data structures for equality filters instead of inequality filters. For example, assuming you only want to filter by decade, you can add a field encoding the decade in which the song was recorded. To find everything before or after a decade, do an IN query for the decades you want to span. This will require one underlying query per decade included, but if the number of records is large, this can still be cheaper than fetching all the results and sorting them in memory.
Since storage is cheap, you could create your own ListProperty based indexfiles with key\_names that reflect the sort criteria. ``` class album_pubyear_List(db.Model): words = db.StringListProperty() class album_length_List(db.Model): words = db.StringListProperty() class album_artist_List(db.Model): words = db.StringListProperty() class Album(db.Model): blah... def save(self): super(Album, self).save() # you could do this at save time or batch it and do # it with a cronjob or taskqueue words = [] for field in ["title", "artist", "label", "genre", ...]: words.append("%s:%s" %(field, getattr(self, field))) word_records = [] now = repr(time.time()) word_records.append(album_pubyear_List(parent=self, key_name="%s_%s" %(self.pubyear, now)), words=words) word_records.append(album_length_List(parent=self, key_name="%s_%s" %(self.album_length, now)), words=words) word_records.append(album_artist_List(parent=self, key_name="%s_%s" %(self.artist_name, now)), words=words) db.put(word_records) ``` Now when it's time to search you create an appropriate WHERE clause and call the appropriate model ``` where = "WHERE words = " + "%s:%s" %(field-a, value-a) + " AND " + "%s:%s" %(field-b, value-b) etc. aModel = "album_pubyear_List" # or anyone of the other key_name sorted wordlist models indexes = db.GqlQuery("""SELECT __key__ from %s %s""" %(aModel, where)) keys = [k.parent() for k in indexes[offset:numresults+1]] # +1 for pagination object_list = db.get(keys) # returns a sorted by key_name list of Albums ```
Filter and sort music info on Google App Engine
[ "", "python", "google-app-engine", "django-models", "model", "" ]
Given: ``` int i = 42; int j = 43; int k = 44; ``` By looking at the variables addresses we know that each one takes up 4 bytes (on most platforms). However, considering: ``` int i = 42; int& j = i; int k = 44; ``` We will see that variable `i` indeed takes 4 bytes, but `j` takes **none** and `k` takes again 4 bytes on the stack. What is happening here? It looks like `j` is simply non-existent in runtime. And what about a reference I receive as a function argument? That *must* take some space on the stack... And while we're at it - why can't I define an array or references? ``` int&[] arr = new int&[SIZE]; // compiler error! array of references is illegal ```
everywhere the reference **j** is encountered, it is replaced with **the address of i**. So basically the reference content address is resolved at compile time, and there is not need to dereference it like a pointer at run time. *Just to clarify what I mean by the address of i* : ``` void function(int& x) { x = 10; } int main() { int i = 5; int& j = i; function(j); } ``` In the above code, **j** should not take space on the ***main stack***, but the reference **x** of **function** will take a place on its stack. That means when calling **function** with **j** as an argument, **the address of i** that will be pushed on the stack of **function**. The compiler can and should not reserve space on the **main stack** for **j**. For the array part the standards say :: > **C++ Standard 8.3.2/4:** > > There shall be no references to references, no arrays of references, > and no pointers to references. [Why arrays of references are illegal?](https://stackoverflow.com/questions/1164266/why-arrays-of-references-are-illegal)
> How does a C++ reference look, > memory-wise? It doesn't. The C++ standard only says how it should behave, not how it should be implemented. In the general case, compilers usually implement references as pointers. But they generally have more information about what a reference may point to, and use that for optimization. Remember that the only requirement for a reference is that it behaves as an alias for the referenced object. So if the compiler encounters this code: ``` int i = 42; int& j = i; int k = 44; ``` what it sees is not "create a pointer to the variable `i`" (although that is how the compiler may choose to implement it in some cases), but rather "make a note in the symbol table that `j` is now an alias for `i`." The compiler doesn't have to create a new variable for `j`, it simply has to remember that whenever `j` is referenced from now on, it should really swap it out and use `i` instead. As for creating an array of references, you can't do it because it'd be useless and meaningless. When you create an array, all elements are default-constructed. What does it mean to default-construct a reference? What does it point to? The entire point in references is that they re *initialized* to reference another object, after which they can not be reseated. So if it could be done, you would end up with an array of references to *nothing*. And you'd be unable to change them to reference *something* because they'd been initialized already.
How does a C++ reference look, memory-wise?
[ "", "c++", "memory-management", "reference", "" ]
I've been told by my hosting company that Python is installed on their servers. How would I go about using it to output a simple HTML page? This is just as a learning exercise at the moment, but one day I'd like to use Python in the same way as I currently use PHP.
If your server is running Apache HTTP server, then you need something like **mod\_wsgi** or **mod\_python** installed and running as a module (your server signature may tell you this). Once running, you may need to add a **handler** to your apache config, or a default may be setup. After that, look at the documentation for the **middleware** of the module you are running, then maybe go on and use something like Django.
When I used shared hosting I found that if I renamed the file to .py and prefixed it with a shebang line then it would be executed as Python. ``` #!/usr/bin/python ``` Was probably pretty bad practice, but it did work. Don't expect to be able to spit out any extensive web apps with it though.
How do I use Python serverside with shared hosting?
[ "", "python", "server-side", "" ]
I know how to use g++ and all that to compile c++ programs. My question is, if I have some code which depends on various libraries, how can I compile it into a simple executable that I can send anyone. For this I would be happy with just keeping it on os x. I would like to know how to compile a "real" program not just an executable I can run locally. I have tried googling this but haven't found much. Do I have to use installing software? I know in windows you can make some simple .exe stuff that use common DLL files.
You a looking for "static linking". That will import all the needed code from the libraries into your executable. Note the executable will get larger. If you are using standard libraries, they should be present on standard OS installation. You should try "-static" flag of g++. Running "ldd your\_executable\_name" should display all libraries your executable uses (linked dynamically).
Since you are talking about Mac OS X, you probably want to make a bundle. Qt Software has a very useful [deployment guide](http://qt-project.org/doc/qt-4.7/deployment-mac.html) for getting started with this kind of activity.
compiling c++ into "real" programs
[ "", "c++", "macos", "g++", "packaging", "compilation", "" ]
I have a table and I want to get the row before the last one. Eg ``` KeyboardID KeyboardName 1 "DELL" 2 "HP" 3 "Viewsonic" 4 "Samsung" ``` select max(keyboardid) from keyboard -> will get the Samsung My Question is how to get the Viewsonic Keyboard...
``` SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY KeyboardId DESC) AS rn FROM Table ) AS t WHERE rn = 2; ``` or ``` WITH cte AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY KeyboardId DESC) AS rn FROM Table) SELECT * FROM cte WHERE rn = 2; ``` or ``` SELECT TOP(1) * FROM ( SELECT TOP(2) * FROM Table ORDER BY KeyboardId DESC) AS t ORDER BY KeyboardId; ```
``` SELECT TOP 1 * FROM Keyboard WHERE KeyboardID < (SELECT MAX(KeyboardID) FROM Keyboard) ORDER BY KeyboardID DESC ```
SQL Server 2005 Query Help
[ "", "sql", "sql-server-2005", "" ]
Im a newbie in javascript and i really aprecciate any ideas of how i can do this... I have one select box. Depending on the option i choose, the other select boxes that are supposed to be "invisible" one of them becomes visible. I dont want to use jquery, because im still a newbie in js. Sorry for my english :P I will put some code for give the example: ``` <select id="tipos_evento"> <option value="">choose an option to see the corresponding select box</option> <option value="tipoe01">option_one</option> <option value="tipoe02">option_two</option> <option value="tipoe03">ssss</option> <option value="tipoe04">ddd</option> </select> <select id="option_one"> <option value="">ss</option> <option value="c">Cffs</option> <option value="d">s</option> <option value="tipoe03">ssss</option> <option value="tipoe04">ddd</option> </select> <select id="option_two"> <option value="">ss</option> <option value="c">Cffs</option> <option value="d">s</option> <option value="tipoe03">ssss</option> <option value="tipoe04">ddd</option> </select> ``` But i think the challenge for me is to show the one that i choosed and to hide the other ones... Thank u for the replies Ive been trying to work out the Justin Johnson function, but it didnt work for internet explorer 7 and 8. I will post the code for anyone that can help me. Ive changed the `style.display = "none"; for`style.cssText='display: none';but only worked when the page loaded. Now when i change the select box, nothing happens. Here is the code(its big, i will optimize it with loops when this works): ``` var attachEvento = function(node, event, listener, useCapture) { // Method for FF, Opera, Chrome, Safari if (window.addEventListener ) { node.addEventListener(event, listener, useCapture || false); } // IE has its own method else { node.attachEvent('on'+event, listener); } }; // Once the window loads and the DOM is ready, attach the event to the main attachEvento(window, "load", function() { var main_select = document.getElementById("tipos_evento"); var option1 = document.getElementById("temas_conferencias"), option2 = document.getElementById("temas_cursos"), option3 = document.getElementById("temas_provas"), option4 = document.getElementById("temas_visitas"), option5 = document.getElementById("temas_ciencias"), option6 = document.getElementById("temas_dancas"), option7 = document.getElementById("temas_exposicoes"), option8 = document.getElementById("temas_multi"), option9 = document.getElementById("temas_musica"), option10 = document.getElementById("temas_teatro"), option11 = document.getElementById("temas_cultura"), option12 = document.getElementById("temas_desporto"), option13 = document.getElementById("temas_todos"); option1.style.cssText='display: none'; option2.style.cssText='display: none'; option3.style.cssText='display: none'; option4.style.cssText='display: none'; option5.style.cssText='display: none'; option6.style.cssText='display: none'; option7.style.cssText='display: none'; option8.style.cssText='display: none'; option9.style.cssText='display: none'; option10.style.cssText='display: none'; option11.style.cssText='display: none'; option12.style.cssText='display: none'; option13.style.cssText='display: block'; var selectHandler = function() { // Show and hide the appropriate select's switch(this.value) { case "8": // Conferências / colóquios option1.style.display = ""; option2.style.display = "none"; option3.style.display = "none"; option4.style.display = "none"; option5.style.display = "none"; option6.style.display = "none"; option7.style.display = "none"; option8.style.display = "none"; option9.style.display = "none"; option10.style.display = "none"; option11.style.display = "none"; option12.style.display = "none"; option13.style.display = "none"; break; case "10": // Cursos/workshops option1.style.cssText='display: none'; option2.style.cssText='display: block'; option3.style.cssText='display: none'; option4.style.cssText='display: none'; option5.style.cssText='display: none'; option6.style.cssText='display: none'; option7.style.cssText='display: none'; option8.style.cssText='display: none'; option9.style.cssText='display: none'; option10.style.cssText='display: none'; option11.style.cssText='display: none'; option12.style.cssText='display: none'; option13.style.cssText='display: none'; break; case "7": // provas option1.style.cssText='display: none'; option2.style.cssText='display: none'; option3.style.cssText='display: block'; option4.style.cssText='display: none'; option5.style.cssText='display: none'; option6.style.cssText='display: none'; option7.style.cssText='display: none'; option8.style.cssText='display: none'; option9.style.cssText='display: none'; option10.style.cssText='display: none'; option11.style.cssText='display: none'; option12.style.cssText='display: none'; option13.style.cssText='display: none'; break; case "9": // visitas/observações option1.style.cssText='display: none'; option2.style.cssText='display: none'; option3.style.cssText='display: none'; option4.style.cssText='display: block'; option5.style.cssText='display: none'; option6.style.cssText='display: none'; option7.style.cssText='display: none'; option8.style.cssText='display: none'; option9.style.cssText='display: none'; option10.style.cssText='display: none'; option11.style.cssText='display: none'; option12.style.cssText='display: none'; option13.style.cssText='display: none'; break; case "12": // ciencia option1.style.cssText='display: none'; option2.style.cssText='display: none'; option3.style.cssText='display: none'; option4.style.cssText='display: none'; option5.style.cssText='display: block'; option6.style.cssText='display: none'; option7.style.cssText='display: none'; option8.style.cssText='display: none'; option9.style.cssText='display: none'; option10.style.cssText='display: none'; option11.style.cssText='display: none'; option12.style.cssText='display: none'; option13.style.cssText='display: none'; break; case "2": // danças option1.style.cssText='display: none'; option2.style.cssText='display: none'; option3.style.cssText='display: none'; option4.style.cssText='display: none'; option5.style.cssText='display: none'; option6.style.cssText='display: block'; option7.style.cssText='display: none'; option8.style.cssText='display: none'; option9.style.cssText='display: none'; option10.style.cssText='display: none'; option11.style.cssText='display: none'; option12.style.cssText='display: none'; option13.style.cssText='display: none'; break; case "1": // exposiçoes option1.style.cssText='display: none'; option2.style.cssText='display: none'; option3.style.cssText='display: none'; option4.style.cssText='display: none'; option5.style.cssText='display: none'; option6.style.cssText='display: none'; option7.style.cssText='display: block'; option8.style.cssText='display: none'; option9.style.cssText='display: none'; option10.style.cssText='display: none'; option11.style.cssText='display: none'; option12.style.cssText='display: none'; option13.style.cssText='display: none'; break; case "3": // multi option1.style.cssText='display: none'; option2.style.cssText='display: none'; option3.style.cssText='display: none'; option4.style.cssText='display: none'; option5.style.cssText='display: none'; option6.style.cssText='display: none'; option7.style.cssText='display: none'; option8.style.cssText='display: block'; option9.style.cssText='display: none'; option10.style.cssText='display: none'; option11.style.cssText='display: none'; option12.style.cssText='display: none'; option13.style.cssText='display: none'; break; case "4": // musica option1.style.cssText='display: none'; option2.style.cssText='display: none'; option3.style.cssText='display: none'; option4.style.cssText='display: none'; option5.style.cssText='display: none'; option6.style.cssText='display: none'; option7.style.cssText='display: none'; option8.style.cssText='display: none'; option9.style.cssText='display: block'; option10.style.cssText='display: none'; option11.style.cssText='display: none'; option12.style.cssText='display: none'; option13.style.cssText='display: none'; break; case "5": // teatro option1.style.cssText='display: none'; option2.style.cssText='display: none'; option3.style.cssText='display: none'; option4.style.cssText='display: none'; option5.style.cssText='display: none'; option6.style.cssText='display: none'; option7.style.cssText='display: none'; option8.style.cssText='display: none'; option9.style.cssText='display: none'; option10.style.cssText='display: block'; option11.style.cssText='display: none'; option12.style.cssText='display: none'; option13.style.cssText='display: none'; break; case "6": // Cultura(outros) option1.style.cssText='display: none'; option2.style.cssText='display: none'; option3.style.cssText='display: none'; option4.style.cssText='display: none'; option5.style.cssText='display: none'; option6.style.cssText='display: none'; option7.style.cssText='display: none'; option8.style.cssText='display: none'; option9.style.cssText='display: none'; option10.style.cssText='display: none'; option11.style.cssText='display: block'; option12.style.cssText='display: none'; option13.style.cssText='display: none'; break; case "48": // Desporto option1.style.cssText='display: none'; option12.style.cssText='display: block'; option2.style.cssText='display: none'; option3.style.cssText='display: none'; option4.style.cssText='display: none'; option5.style.cssText='display: none'; option6.style.cssText='display: none'; option7.style.cssText='display: none'; option8.style.cssText='display: none'; option9.style.cssText='display: none'; option10.style.cssText='display: none'; option11.style.cssText='display: none'; option13.style.cssText='display: none'; break; default: // Hide all option1.style.cssText='display: none'; option2.style.cssText='display: none'; option3.style.cssText='display: none'; option4.style.cssText='display: none'; option5.style.cssText='display: none'; option6.style.cssText='display: none'; option7.style.cssText='display: none'; option8.style.cssText='display: none'; option9.style.cssText='display: none'; option10.style.cssText='display: none'; option11.style.cssText='display: none'; option13.style.cssText='display: block'; } }; // Use the onchange and onkeypress events to detect when the // value of main_select has changed attachEvento(main_select, "change", selectHandler); attachEvento(main_select, "keypress", selectHandler); }); ```
I generally use mootools, but this should be generic. I can't speak to cross-browser issues, though. ``` <select id='main_select' onchange='show_select()'> <option>1</option> <option>2</option> </select> <select id='select_1' style='display:none'></select> <select id='select_2' style='display:none'></select> function show_select() { var main_select = document.getElementById("main_select"); var select_1 = document.getElementById("select_1"); var select_2 = document.getElementById("select_2"); var desired_box = main_select.options[main_select.selectedIndex].value; if(desired_box == 1) { select_1.style.display = ''; select_2.style.display = 'none'; } else { select_2.style.display = ''; select_1.style.display = 'none'; } } ```
You can handle the change event: ``` document.getElementById('selectBox').onchange = function () { var selectedValue = this.options[this.selectedIndex].value; // get the selected value // Depending on the value selected you can show or hide other elements: if (selectedValue == "1") { document.getElementById('element1').style.display = 'none'; // hide element1 document.getElementById('element2').style.display = ''; // show element2 } }; ``` **Note:** In your edit, the last two select boxes have **invalid characters** for the **ID** attribute. > ID and NAME tokens must begin with a > letter ([A-Za-z]) and may be followed > by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("\_"), colons (":"), and periods ("."). More information [here](http://www.w3.org/TR/html4/types.html).
How to hide/show select boxes depending on other choosed select box option?
[ "", "javascript", "" ]
**How can I make comments like on stackoverflow?** What I mean more specificly, I use php/mysql how would I add a comment without reloading the page, I know this is a simple process of using AJAX but when you post a comment on SO it also has the option to delete it right away, when I insert comments into my DB there ID number is auto increment, so my real question now is After posting the comment, is the comment posted, just added to the page with some javascript to append the contents to the page OR Does it use AJAX to retrieve that comment you just posted and then display it on the page? The reason I am wondering is because since my system uses auto increment ID then if I did it the first method which would be faster to just ad the contents I posted on submit but this method would not give me the ID which is needed to be able to delete the comment by ID number Hope that makes sense **UPDATE** I posted below what I think now after reading other post on here
**UPDATE** After reading answers here is my basic idea, I don't know how to write javascrpt but you will get the design flow idea: ``` POST comment input to script with AJAX { if commentID is returned{ Insert comment DIV into page, userID and userPicture are in a user session variable and commentID is returned from ajax post }ELSE IF error is returned{ Insert an error message DIV into page } } ``` > Then the comment div or whatever that > is inserted would include > - a users name from session variable > - userID from session variable for linking to there profile > - user picture from session variable > **- comment ID for allowing the user to delete that comment** Then for deleting ANY comment on the page that a user published ``` POST comment ID and userID to DELETION script with AJAX {         if commentID is deleted{         REMOVE comment DIV from page     }ELSE IF error is returned{         Insert an error message DIV into page     } } ```
I'm going to go out on a limb and say it's right in between the two. The content of the comment is just posted from what you typed... ...but the page waits to append your comment until the AJAX magic has occurred and the page has the ID of your new comment. (that should read: Here's how I would do it if I were you...fast, lightweight, and functional)
How can I make comments like on stackoverflow?
[ "", "php", "ajax", "comments", "" ]
I'm using LINQPad to create LINQ queries in an application I'm bulding. I noticed that in the downloaded **LINQ in Action** samples, e.g. example 4.04, intellisense shows a class "Books" but I don't see any **references** or "**using**" statements in the LINQPad tool, here is the sample: ``` List<Book> books = new List<Book>() { new Book { Title="LINQ in Action" }, new Book { Title="LINQ for Fun" }, new Book { Title="Extreme LINQ" } }; var titles = books .Where(book => book.Title.Contains("Action")) .Select(book => book.Title); titles.Dump(); ``` In "LinqBooks.Common, Business Objects, **Book.linq**" is where the class seems to be defined: ``` public class Book { public IEnumerable<Author> Authors {get; set;} public String Isbn {get; set;} public String Notes {get; set;} public Int32 PageCount {get; set;} public Decimal Price {get; set;} public DateTime PublicationDate {get; set;} public Publisher Publisher {get; set;} public IEnumerable<Review> Reviews {get; set;} public Subject Subject {get; set;} public String Summary {get; set;} public String Title {get; set;} public String Test {get; set;} public override String ToString() { return Title; } } ``` **But how does this work so that I can copy in my classes and use LINQPad to quickly build LINQ statements that I can then copy back into my application?**
If you right click in the code editor in LINQPad and choose Advanced Query Properties, there are two dialogs: Additional References and Additional Namespace Imports. 1) In **Additional References**, choose **Add** then click **Browse** and navigate to your custom assembly. 2) Then, in **Additional Namespace Imports**, type the **namespaces** you want to import from that assembly.
LINQPad allows you to reference custom assemblies through the *Advanced Query Properties* dialog which can be opened by pressing `F4`.
How does LINQPad reference other classes, e.g. Books in the LINQ in Action samples
[ "", "c#", "linq", "linq-to-objects", "linqpad", "" ]
I have a situation. I read in a html page using php using this piece of code `$body = file_get_contents('index.htm');` Now in the index.htm file is a piece of html code like below that I sometimes need to remove/depends on criteria, so sometimes it needs to be removed and other times not. ``` <td><table><tr><td></td></tr></table></td> ``` How do I remove the whole **table** section between the **td** tags using **PHP**.
One way to do it can be ``` $str = '<td><table><tr><td></td></tr></table></td>'; preg_match('/(<td>)(<table>.*<\/table>)(<\/td>)/',$str,$matches); ``` the resulting array ``` Array ( [0] => <td><table><tr><td></td></tr></table></td> [1] => <td> [2] => <table><tr><td></td></tr></table> [3] => </td> ) ``` can be used to recreate the ``` '<td></td>' ``` without the table section
If you are lucky enough that your page is XML then you could form a DOM and remove the from the DOM. Otherwise a regular expression should be easy as long as you don't have nested `<table>`s (in which case it's still possible but more tricky).
How to remove a piece of HTML tags in a HTML page using PHP
[ "", "php", "html-parsing", "" ]
I am looking for an python inbuilt function (or mechanism) to segment a list into required segment lengths (without mutating the input list). Here is the code I already have: ``` >>> def split_list(list, seg_length): ... inlist = list[:] ... outlist = [] ... ... while inlist: ... outlist.append(inlist[0:seg_length]) ... inlist[0:seg_length] = [] ... ... return outlist ... >>> alist = range(10) >>> split_list(alist, 3) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] ```
You can use list comprehension: ``` >>> seg_length = 3 >>> a = range(10) >>> [a[x:x+seg_length] for x in range(0,len(a),seg_length)] [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] ```
How do you need to use the output? If you only need to iterate over it, you are better off creating an iterable, one that yields your groups: ``` def split_by(sequence, length): iterable = iter(sequence) def yield_length(): for i in xrange(length): yield iterable.next() while True: res = list(yield_length()) if not res: return yield res ``` Usage example: ``` >>> alist = range(10) >>> list(split_by(alist, 3)) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] ``` This uses far less memory than trying to construct the whole list in memory at once, if you are only looping over the result, because it only constructs one subset at a time: ``` >>> for subset in split_by(alist, 3): ... print subset ... [0, 1, 2] [3, 4, 5] [6, 7, 8] [9] ```
Segment a list in Python
[ "", "python", "list", "segments", "" ]
My brother would like to learn some programming to find out if he'd enjoy doing it. He's 16 and doesn't know much about computers in general and knows nothing about programming in particular. I'm thinking about picking either [Alice](http://www.alice.org) or Python. I see [Think Python](http://www.greenteapress.com/thinkpython/html/) is the often recommended read, but isn't it a bit too much (size-wise) for a beginner? It's certainly not too complicated, but I'm not that optimistic about my brother... :) Anything else he could try that would be smaller and VERY simple? Also, has anyone had any experience with Alice? I myself wouldn't really want to start programming this way, but I can see why the visual aspect might be more attractive to certain people. I'm just not sure how limiting it is and if the time used learning the pseudo language wouldn't be better spent learning a real one. EDIT: Thank you for your replies. I guess we'll go with Python. However, as I mentioned above, isn't "Think Python" a bit too extensive for a complete "newbie"? Any other, but simpler Python programming introductions you could recommend?
The advantage of Python is that - should he be bitten by the bug - there's massive a community and lots of resources to drawn on and explore. If he's not bitten by Python, then programming might be a hard sell anyway, so I don't see the advantage of starting on logo-likes, even 3D ones like Alice. Alice can of course be fun, as can writing Lua scripts to extend a mainstream game title. But all the hardcore programmers in their thirties now seem to have started on Turbo Pascal or even assembler when they were around 16, and Python offers an approachable modern-day equiv.
Use Python. It's very simple. It will let you make "Hello World" in one line, and also let you do any range of powerful things down the road. It's great for beginners because of the minimalist syntax, and it also forces you to indent your code properly. Even a non-programmer can understand Python: ``` print "hello world" you = True if you: print "I bet you think this program is about you, don't you, don't you?" a = 1 b = 1 c = a + b ``` Another nice thing about Python is it is interpreted, so you can open up a terminal and just play around.
Alice vs Python for someone with zero experience
[ "", "python", "alice", "" ]
I've got a javascript timer that is making XMLHTTP requests on a constant basis (once every 10 seconds). I'd love to be able to pause the timer when the window or tab loses focus. I'm fully aware of the `onFocus` and `onBlur` events on the `window` object, but they don't fire reliably across all browsers. For instance, [in Safari, tabs don't trigger the events](http://lists.macosforge.org/pipermail/webkit-unassigned/2009-February/101708.html). Simple code below distills the functionality I'm looking for: ``` <html> <head> <title>Testing</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js"></script> </head> <body> <div id="console"></div> <script type="text/javascript"> window.onfocus = function(event) { $('console').insert('Window gained focus<br />'); } window.onblur = function(event) { $('console').insert('Window lost focus<br />'); } </script> </body> </html> ``` Does anyone out there have a technique for determining when a browser window or tab loses/gains focus that works across across all popular browsers?
The above code is working fine in `Safari v3.0.4` (WebKit 530+), the bug has been resolved it seems. I've checked it in `Google Chrome v3.0.195.27` and it has the same Safari bug, although it has a newer version of WebKit.
There is another Stack Overflow question regarding this topic. They didn't address the tabbed browsing issue there. They do give a link which goes into some detail, although without using jquery. [Is there a way to detect if a browser window is not currently active?](https://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active) I don't think focus/blur events work with tabbed browsing in Safari at all. Some people have suggested mouse events, like mouseleave/mouseenter for this. I've got some UI issues like this myself, so if I discover anything I'll follow up here.
Is there a reliable way to determine if a browser tab or window is inactive or not in focus?
[ "", "javascript", "browser", "cross-browser", "" ]
How to raise custom events and handle in Java. Some links will be helpful. Thanks.
The following linked helped me to understand. <http://www.javaworld.com/javaworld/javaqa/2002-03/01-qa-0315-happyevent.html>
There are no first-class events in Java. All event handling is done using interfaces and listener pattern. For example: ``` // Roughly analogous to .NET EventArgs class ClickEvent extends java.util.EventObject { public ClickEvent(Object source) { super(source); } } // Roughly analogous to .NET delegate interface ClickListener extends java.util.EventListener { void clicked(ClickEvent e); } class Button { // Two methods and field roughly analogous to .NET event with explicit add and remove accessors // Listener list is typically reused between several events private EventListenerList listenerList = new EventListenerList(); void addClickListener(ClickListener l) { clickListenerList.add(ClickListener.class, l) } void removeClickListener(ClickListener l) { clickListenerList.remove(ClickListener.class, l) } // Roughly analogous to .net OnEvent protected virtual method pattern - // call this method to raise the event protected void fireClicked(ClickEvent e) { ClickListener[] ls = listenerList.getListeners(ClickEvent.class); for (ClickListener l : ls) { l.clicked(e); } } } ``` Client code typically uses anonymous inner classes to register handlers: ``` Button b = new Button(); b.addClickListener(new ClickListener() { public void clicked(ClickEvent e) { // handle event } }); ```
Event raise-handling in Java
[ "", "java", "events", "" ]
E.G.: I want to store output of `system("dir");`
You can either use redirection to a file (system( "dir > file" )), read that file and delete it or go the unnamed pipes way as in Unix - call CreatePipe() to create a pipe and attach it as the input/output stream in PROCESS\_INFORMATION structure and pass that structure into CreateProcess().
Yes, look at capturing stdout from CreateProcess: * [Creating a Child Process with Redirected Input and Output](http://msdn.microsoft.com/en-us/library/ms682499.aspx) Note that `dir` is a built in command under DOS. So you'll have to do something like the following system command: * `cmd.exe /c dir c:\path\to\directory` rather than just calling `dir`. Type `cmd /?` for more information on the `/c` parameter.
is it possible to store output of system call in windows?
[ "", "c++", "c", "windows", "" ]
So we've hired a company to migrate our three websites from custom built CMS solutions to Typo3. One of our sites is still in classic ASP while the other two are in ASP.net 1.1 & 2.0. Typo3 wasn't my choice, but the choice of those with the purse strings. Anyway, the migration of the sites is progressing but I have a problem that nobody seems to be able to answer. How do we handle page redirects? For example, on our classic ASP site, we have a lot of tracking links from our newsletters (7 years worth) that have urls like: tracklink.asp?ID=23421 How can we handle these links on the new PHP setup that Typo3 is running on? I can build a PHP page to handle the classic tracking similar to the PHP page, but if you go to the .asp page in the example above, we get a 404 error, even if the page is there, since by default, the system doesn't handle ASP pages. Is there a way to do some sort of redirect that will still pass the querystring variable to the new PHP tracking page? Also, we'll need to do this with our .aspx pages on the .net sites as well. Any ideas??
You could simply use the power of mod\_rewrite to do this. Take a look at the htaccess file in the TYPO3 root directory and change it to your needs. What you want to do is sending an 311 Location changed permanenlty status code to the clients and redirecting them to the new URL. I think this is a cleaner solution...
You should be able to configure your webserver to let PHP handle pages ending in `.asp` just as it handles `.php`. How these associations are configured depends on your web server.
Migrating from custom ASP & ASP.NET applications to PHP (Typo3)
[ "", "php", "asp.net", "redirect", "asp-classic", "" ]
Well, encountered the need of a line-height coding a plugin, so, can you give an advice, please? Thanks)
``` $('selector').css('line-height'); ```
You can't be assured to get a calculated line height in pixels cross-browser. Sometimes the value is 'normal' or 'inherit', which gets calculated in Firefox, but not in IE, for example. One workaround for this (depending of course on your use case) is to get the calculated font-size (which you *can* see), and multiply it by 1.5, which is fairly [standard](http://www.smashingmagazine.com/2009/08/20/typographic-design-survey-best-practices-from-the-best-blogs/#optimal): ``` var fontSize = $(el).css('font-size'); var lineHeight = Math.floor(parseInt(fontSize.replace('px','')) * 1.5); ``` Yeah, it's a bit gross, but it will work just fine for things like determining the correct height of an element based on some number of text lines, for example. Keep in mind, that you can/should replace 1.5 with any standard line-height/font-size ratio you may already be using on your site. If you don't know, you can find out by inspecting any copy element in firebug and looking at the calculated a)font-size and b)line-height. Then, replace 1.5 with b/a. :-) Hope this is helpful!
How to determine a 'line-height' using Javascript (jQuery)?
[ "", "javascript", "jquery", "dom", "" ]
Is Template Metaprogramming faster than the equivalent C code ? ( I'm talking about the runtime performance) :)
First, a disclaimer: What I *think* you're asking about is not just template metaprogramming, but also generic programming. The two concepts are closely related, and there's no exact definition of what each encompasses. But in short, template metaprogramming is essentially writing a program using templates, which is evaluated at compile-time. (which makes it entirely free at runtime. Nothing happens. The value (or more commonly, type) has already been computed by the compiler, and is available as a constant (either a const variable, or an enum), or as a typedef nested in a class (if you've used it to "compute" a type). Generic programming is using templates and when necessary, template metaprogramming, to create generic code which works the same (and with no loss in performance), with all and any type. I'm going to use examples of both in the following. A common use for template metaprogramming is to enable types to be used in generic programming, even if they were not designed for it. Since template metaprogramming technically takes place entirely at compile-time, your question is a bit more relevant for generic programming, which still takes place at runtime, but is efficient because it can be specialized for the precise types it's used with at compile-time. Anyway... --- Depends on how you define "the equivalent C code". The trick about template metaprogramming (or generic programming in general) is that it allows a lot of computation to be moved to compile-time, and it enables flexible, parametrized code that is just as efficient as hardcoded values. The code displayed [here](http://blog.cplusplus-soup.com/2007/11/cross-platform-and-template-meta.html) for example computes a number in the fibonacci sequence at compile-time. The C++ code '`unsigned long fib11 = fibonacci<11uL>::value`', relies on the template metaprogram defined in that link, and is as efficient as the C code '`unsigned long fib11 = 89uL`'. The templates are evaluated at compile-time, yielding a constant that can be assigned to a variable. So at runtime, the code is actually identical to a simple assignment. So if that is the "equivalent C code", the performance is the same. If the equivalent C code is "a program that can compute arbitrary fibonacci numbers, applied to find the 11th number in the sequence", then the C version will be much slower, because it has to be implemented as a function, which computes the value at runtime. But this is the "equivalent C code" in the sense that it is a C program that exhibits the same flexibility (it is not just a hardcoded constant, but an actual function that can return *any* number in the fibonacci sequence). Of course, this isn't often useful. But it's pretty much the canonical example of template metaprogramming. A more realistic example of generic programming is sorting. In C, you have the `qsort` standard library function taking an array and a comparator function pointer. The call to this function pointer can not be inlined (except in trivial cases), because at compile-time, it is not known which function is going to be called. Of course the alternative is a hand-written sorting function designed for your specific datatype. In C++, the equivalent is the function template `std::sort`. It too takes a comparator, but instead of this being a function pointer, it is a function object, looking like this: ``` struct MyComp { bool operator()(const MyType& lhs, const MyType& rhs) { // return true if lhs < rhs, however this operation is defined for MyType objects } }; ``` and this can be inlined. The `std::sort` function is passed a template argument, so it knows the exact type of the comparator, and so it knows that the comparator function is not just an unknown function pointer, but `MyComp::operator()`. The end result is that the C++ function `std::sort` is *exactly* as efficient as your hand-coded implementation in C of the same sorting algorithm. So again, if that is "the equivalent C code", then the performance is the same. But if the "equivalent C code" is "a generalized sorting function which can be applied to *any* type, and allows user-defined comparators", then the generic programming-version in C++ is vastly more efficient. That's really the trick. Generic programming and template metaprogramming are not "faster than C". They are methods to achieve *general, reusable code* which is as fast as *handcoded, and hardcoded C* It is a way to get the best of both worlds. The performance of hardcoded algorithms, and the flexibility and reusability of general, parameterized ones.
Template Metaprogramming (TMP) is 'run' at compile time, so it's not really comparing apples to apples when comparing it to normal C/C++ code. But, if you have something evaluated by TMP, then there's no runtime cost at all.
Is Template Metaprogramming faster than the equivalent C code?
[ "", "c++", "c", "language-agnostic", "templates", "metaprogramming", "" ]
I need a way to split a UK postcode from user entry. This means the postocode could be nicely formatted full code like so "AB1 1BA" or it could be anything you could imagine. I've seen some regex to check the format of the postcode but it's knowing where to split it if I'm given something like "AB111AD" etc.. This is to return the first part of the postcode, in the example above would be "AB11". Any thoughts? Thanks..
I'm not sure how UK Post Codes work, so is the last part considered the last 3 characters with the first part being everything before? If it is, something like this should work, assuming you've already handled appropriate validation: (Edited thanks to Jon Skeets commment) ``` string postCode = "AB111AD".Replace(" ", ""); string firstPart = postCode.Substring(0, postCode.Length - 3); ``` That will return the Post Code minus the last 3 characters.
I've written something similar in the past. I *think* you can just split before the last digit. (e.g. remove all spaces, find the last digit and then insert a space before it): ``` static readonly char[] Digits = "0123456789".ToCharArray(); ... string noSpaces = original.Replace(" ", ""); int lastDigitIndex = noSpaces.LastIndexOfAny(Digits); if (lastDigitIndex == -1) { throw new ArgumentException("No digits!"); } string normalized = noSpaces.Insert(lastDigitIndex, " "); ``` The [Wikipedia entry](http://en.wikipedia.org/wiki/Postal_codes_in_the_United_Kingdom) has a lot of detail including regular expressions for validation (after normalisation :)
c# UK postcode splitting
[ "", "c#", "string", "" ]
Without learning new programing languages, can we using Java get .exe (executable windows file) software directly? And is there away to make .jar (Java ARchive) software transform to.exe (executable windows file)? Would this conversion effect the performance of the software?
One of the important points of Java is that it'll run on any platform (e.g. Windows, Linux, etc) that has a suitable Java Virtual Machine (JVM) installed. A .exe file is compiled to work on only one platform. What you think you want is to turn a .jar into an .exe so you can launch it easily. What I expect you *really* want is just an easy way of launching a Java app that anybody can understand, including your parents. The easiest way of doing this is to create a Windows batch file that launches your Java app. One of line of script, one new file, one new instruction to your users - "Double click on runme.bat" There are ways of turning a .jar into an .exe, but you should think about whether that's really what you want, and if so, why. Note: you can launch a .jar in Windows by just double clicking on it, as long as the main class is specified in the manifest. You might want to look into tools like Apache Ant to simplify building .jars and their manifests. Just a thought. EDIT: A batch file in Windows is a simple text file that contains commands. You can test the commands by running them in the command prompt (Start -> Run -> cmd). When you run a batch file the commands in it are just fed to the command prompt one at a time. How to run a Jar from the command prompt: "java -jar myfile.jar" If you create a batch file (.bat - use Notepad or your favourite text editor) containing "java -jar myfile.jar" (without the quotes!) then double-clicking it will launch the main class specified in the manifest of myfile.jar. myfile.jar has to be in the same folder as the batch file, though. If you use the command "java -jar lib\myfile.jar" (again, without the quotes) then your batch file will run myfile.jar, which needs to be in a folder called lib that's in the same folder as the batch file. Use this approach when you have a whole load of Jars with your application and you don't want to shove them in the user's face :) Note that moving the batch file will break it, unless it uses absolute paths to the jar file - e.g. "java -jar C:\dev\myfile.jar". Of course, if you use absolute paths then moving the Jar will break the batch file anyway :) Also, note that you should be able to run a Jar file just by doubling clicking on it in Windows, as long as the main class is specified in the manifest. Give it a try. Of course, convincing your users that they can double click on it is another matter entirely... As a final note, if you use a batch file, your users will get a nice command prompt window sitting in the background until your Java app closes. That is, unless you start your batch file command with "start". E.g. "start java -jar myfile.jar". If you have your app configured to log to System.out or System.err, you will still get a command prompt when your app writes to either of those streams, though. Final final note, in the Linux world the equivalent of batch files are shell scripts.
You can launch a .exe from java with Runtime.exec() or ProcessBuilder. You can make a .exe launcher with <http://launch4j.sourceforge.net/>
Can my Java software be transformed to .exe software?
[ "", "java", "jar", "exe", "" ]
I'm looking for a function to properly capitalize names like McDonald, FitzGerald, MacArthur, O'Lunney's, Theo de Raadt, etc. Does anyone know of one that works resonably well? I'm guessing any function is not going to support every possibility. Of course ucwords alone doesn't work for this because it just capitalize the first letter of every word. **Edit:** I know there are going to be problems and all the possibility are not going to be supported. But the issue right now is I have a database of around 50 000 names that are mostly entered in all caps and it would be a pain in the ass to have to edit each one without causing spelling errors. Having a script that causes a problem with 20% would be a whole lot faster and result in a lot fewer errors.
Maybe you need something like this [ucwords function note](http://www.php.net/manual/en/function.ucwords.php#60064)
You're probably aware of this, but one huge problem you'll face is that there's more than one "correct" capitalisation of some names - in your example I'd disagree with FitzGerald, for example.
Does someone have a PHP function to properly capitalize people names?
[ "", "php", "" ]
I've been looking around for a way to programmatically parse XSD files to generate an XML mapping so that I can take any XSD file and create a parser that will parse any XML file that conforms to it, and my google-fu has been coming up short. [XSOM](https://xsom.dev.java.net/) looks promising, as it will parse an XSD file and make all its attributes available in a straight forward way. Are there any other options or standard libraries available that will produce an XML file parser from an XSD file? **[Conclusion]** Thanks everyone for your responses, they were a real help. I was able to write implementations using JAXP, Eclipses EMF and in XSOM that all worked as desired. JAXP was very straight forward and easy to learn and do. EMF was actually a pain to get going properly, there were so many jars that had to be included for it to work standalone that I would not recommend it. XSOM was even simpler than the JAXP implementation, so I went with it in the end.
Yes, there's a standard way. You're looking for [JAXB](http://jaxb.java.net/).
I've used the Eclipse XSD libraries to parse XML Schema in the past. <http://eclipse.org/modeling/mdt/?project=xsd>, and found it very straighforward to use There are a ton of jar files that come down, but you will only need 5 of them at runtime to do the parsing.
Is there a standard Java utility to parse XSD files at runtime?
[ "", "java", "xml", "xsd", "" ]
I wonder what % and & in the following PHP code do. ``` $num_one = rand() % 10; $num_two = rand() & 10; ```
% is modulo, so ``` $num_one = rand() % 10 ``` gives you a number between in [0..10), while & means bitwise and, such that ``` $num_one = rand() & 10 ``` gives you a random number with only a combination of the bits 2 and 4 set, like in [2,8,10].
% is [modulus](http://us.php.net/manual/en/language.operators.arithmetic.php) (remainder after division). & is [bitwise and](http://us.php.net/manual/en/language.operators.bitwise.php).
What % and & in this code?
[ "", "php", "" ]
I have a table called table1 which has a composite primary key using 'ScreenId' and 'ActivityItemId'. I have added a new field 'ProductId' which has a NOT NULL constraint. I want to add ProductId to the composite primary key. I thought that this would work db.execute "ALTER TABLE table1 PRIMARY KEY (ScreenId, ActivityItemId, ProductId)" but i get an error, i think this syntax only works when creating a table. Can anyone help me out with the SQL? (i can't use a visual basic solution here btw, i'm actually using a ruby interface in order to run the sql, so it needs to be just in SQL) thanks max
Try to drop your current primary key and then create new one: ALTER TABLE table1 DROP CONSTRAINT pk\_name ALTER TABLE table1 ADD CONSTRAINT pk\_name PRIMARY KEY (ScreenId, ActivityItemId, ProductId)
Think about a surrogate key instead of a composite key. You don't want to have to change your schema every time your business logic changes. It might be worth it to keep those relationships as unique constraints and add a surrogate key.
SQL (access) - add a new field to a composite primary key
[ "", "sql", "ms-access", "database-design", "" ]
How do I force a loop to check its condition after every line of execution instead of only when the entire block finishes? I have a while(!**statement**) { } loop, but **statement** can be changed by several different methods and should force the loop to break immediately after the current line in the loop has finished executing; instead of when the entire loop block has completed a cycle. Is there any way to do this?
Depending on what you are doing, you could consider having each statement be a delegate, create an array of delegates, and run a for loop across the array. That way the loop is just two lines: one that checks the condition, and when that executes the delegate at the current array position.
yes, but you won't like it... just put a `if (!condition) break;` after each instruction ;)
c# Force loop to check condition
[ "", "c#", "loops", "" ]
In PHP, how do you use an external $var for use within a function in a class? For example, say $some\_external\_var sets to true and you have something like ``` class myclass { bla .... bla .... function myfunction() { if (isset($some_external_var)) do something ... } } $some_external_var =true; $obj = new myclass(); $obj->myfunction(); ``` Thanks
`Global $some_external_var;` ``` function myfunction() { Global $some_external_var; if (!empty($some_external_var)) do something ... } } ``` But because Global automatically sets it, check if it isn't empty.
You'll need to use the [`global`](http://php.net/manual/en/language.variables.scope.php) keyword inside your function, to make your external variable visible to that function. For instance : ``` $my_var_2 = 'glop'; function test_2() { global $my_var_2; var_dump($my_var_2); // string 'glop' (length=4) } test_2(); ``` You could also use the `$GLOBALS` array, which is always visible, even inside functions. But it is generally not considered a good practice to use global variables: your classes should not depend on some kind of external stuff that might or might not be there ! A better way would be to pass the variables you need as parameters, either to the methods themselves, or to the constructor of the class...
PHP access external $var from within a class function
[ "", "php", "global-variables", "" ]
I have an admin page to search for products to edit, but the page keeps returning the error: > Microsoft OLE DB Provider for SQL Server error '80040e14' Ambiguous > column name 'prod\_id'. /\_\_admin/searchproducts.asp, line 89 I'm unsure why this error is cropping up, because the page and site is a direct copy of another website and associated MSSQL database and the search product page works on that site. This is the code in question (not sure if it will be easy to read here though); ``` if request("fldSubmitted") <> "" then if request("fldprodid") <> "" and isNumeric(request("fldprodid")) then SQL = "select * from products where prod_id = " & cdbl(request("fldprodid")) else SQL = "select " if request("showtop") <> "all" then SQL = SQL & " top " & request("showtop") & " " & replace(replace(request("orderby")," asc","")," desc","") & ", " end if SQL = SQL & "prod_name, prod_id, prod_code, prod_icon, prod_thumb, prod_numViews, prod_archived" if request("fldLabel") <> "" then SQL = SQl & ", label_name" if request("fldCat") <> "" then SQL = SQL & ", cat_name" if request("fldSubcat") <> "" then SQL = SQL & ", subcat_name" SQL = SQL & " from products" if request("fldLabel") <> "" then SQL = SQL & ", labels" if request("fldCat") <> "" then SQL = SQL & ", categories" if request("fldSubcat") <> "" then SQL = SQl & ", subcategories" sql = sql & " where 1=1" if request("fldLabel")<> "" then SQL = SQL & "and prod_label = label_id " if request("fldCat") <> "" then SQL = SQL & "and prod_category = cat_id " if request("fldSubcat") <> "" then SQL = SQL & "and prod_subcategory = subcat_id " if request("fldName") <> "" then SQL = SQL & " and (prod_name like '%" & replace(request("fldName"),"'","''") & "%')" if request("fldCode") <> "" then SQL = SQL & " and (prod_code like '%" & replace(request("fldCode"),"'","''") & "%')" if request("fldLabel") <> "" then SQL = SQL & " and prod_label = " & request("fldLabel") if request("fldCat") <> "" then SQL = SQL & " and prod_category = " & request("fldCat") if request("fldSubcat") <> "" then SQL = SQL & " and prod_subcategory = " & request("fldSubcat") if request("fldArchived") = "No" then SQL = SQL & " and prod_archived = 0" if request("instock") = "No" then SQL = SQL & " and prod_numleft > 0" end if SQL = SQL & " order by " & request("orderby") end if ```
In the second half of the query the you could possibly select from the tables products, labels, categories and subcategories. If any of these tables have a prod\_id the DBMS won't know which one you are referring to. A simple revision is to alias each table, e.g products p, labels l, etc. An even better refacotoring would be to alter the query to us joins: ``` SELECT p.prod_name, l.label_name FROM products p JOIN labels l ON l.label_id = p.label_id WHERE p.in_stock > 0 ``` One other tip when dealing with these problems is to response.write the SQL string and copy it in to Management Studio instead, this will help you see passed the string manipulation to the error. Finally, I would suggest looking at [Stored Procedures](https://stackoverflow.com/questions/972351/calling-stored-procedure-on-classic-asp-page) so you can remove the SQL from your application. *Edit* Following on from some chat in the comments, if Stored Procedures are out of the question then a [parameterized query](http://support.microsoft.com/kb/200190) would be a good step forward. This will bring a performance gain as the query plan will be cached and avoids the most basic forms of SQL Injection attack.
The problem is that the query will select the column `prod_id`, but more than one of the tables referenced has a column with that name. The query returns results from more than one table, but exactly *which* table depends on the values of the various parameters. So, that might explain why it works in one circumstance but not another. You can make the `prod_id` reference unambiguous by prefixing it with the table name, e.g. ``` myTable.prod_id ``` I presume it's fairly obvious (to you) which table is the right one (of course it has to be a table that's ALWAYS part of the query, not one that's only there under certain conditions).
SQL Server error '80040e14' Ambiguous column name
[ "", "sql", "sql-server", "asp-classic", "" ]
Like this: ``` public String text {get; set{ // here comes some setter checking / setter logic // finally assign the value to the var without using the setter <is_there_a_"without_setter"_keyword?> text = value; } } ```
No there is not a way to do that
No. The property is the *exposed interface* (not a C# `interface`) for controlling access to the private *backing field*. The special syntax introduced in C# 3 is what's called "syntactic sugar" - the compiler actually turns this into a private field that you never see with a get/set property to access it. Edit: Properties themselves don't store data. They simply control access to data stored elsewhere, where one common case is in a private field. Another Edit: This is the sugar syntax I'm referring to: ``` // When this is compiled, it actually creates a private // field for you, which the property accesses. public int MyProperty { get; set; } ```
C#, Is it possible to avoid defining private fields and still use set/get on public fields?
[ "", "c#", "" ]
Can I create an object of my class in stack regarding .net and C#? For example: ``` class abc { int i=1; } abc a1=new abc(); ``` Now, here the object is created in heap. So, is there any way to create the object in stack memory of ram if the size of object is not big?
.NET reference types always live on the GC heap. It's not possible to have them elsewhere. Even C++/CLI that supports things like ``` System::Random rnd; rnd.Next(); ``` that looks like stack variables, actually creates the `Random` class, on the GC heap (and calls its `Dispose` method at the end of the block if it implements `IDisposable`.) That said, as Eric Lippert says, [the stack is an implementation detail](http://blogs.msdn.com/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx) and you should primarily care about reference or value semantics of the types you create.
Use of the stack for objects (class instances) is not available. However, use of `struct` instead of `class`, creates a value-type that will be created on the stack. There's [lots of things to consider](http://msdn.microsoft.com/en-us/library/ms229017%28VS.80%29.aspx) about this. The book *Framework Design Guidelines* doesn't make a concrete suggestion, but indicates it's probably best to benchmark the differences and determine if it's really worth implementing a value-type. --- Side Note: Enabling objects to use the stack is under discussion. This is one of the several issues on github related to objects on the stack: <https://github.com/dotnet/coreclr/pull/6653>
object creation in stack
[ "", "c#", ".net", "memory-management", "object", "" ]
I'm looking for a parser generator that given an EBNF for a LL(k) language will give me a C# parser and generate classes the types defined in the EBNF.
[Gold](http://goldparser.org/) is OK as far a parser generators go.
[ANTLR](http://www.antlr.org/) (nothing else to say)
What is a good C# compiler-compiler/parser generator?
[ "", "c#", "parser-generator", "" ]
Is there an appender for log4j that only stores a list of the logging events (to be used in unit tests, to verify no error logs were written) ?
There is a [MemoryAppender](http://resources.openmrs.org/doc/org/openmrs/util/MemoryAppender.html), but it's not part of the standard log4j library. You could easily write your own, But if you are only using them for unit tests I would probably mock the Logger and assert no calls are made to it. Override the getLogger() method in the target class or set the mock Logger directly on the type. Using Jmock (example from memory, sorry for any errors): ``` public void testDoFoo() { Mockery mockery = new Mockery(); Logger mockLogger = mockery.mock(Logger.class); Foo foo = new Foo(); foo.setLogger(mockLogger); mockery.checking(new Expectations() { { never(mockLogger).debug(with(any(String.class)); } }; ... //do the actual test. //assert the mock type has never been called. mockery.assertIsSatisfied(); } ```
I don't believe there is. You can write your own easily, though. Here's a [suitable tutorial](http://www.javaworld.com/javaworld/jw-12-2004/jw-1220-toolbox.html).
In memory 'list appender' for log4j
[ "", "java", "log4j", "in-memory", "appender", "" ]
Is there a way to check if an enum value is 'greater/equal' to another value? I want to check if an error level is 'error or above'.
All Java enums implements Comparable: <http://java.sun.com/javase/6/docs/api/java/lang/Enum.html> You can also use the `ordinal` method to turn them into `int`s, then comparison is trivial. ``` if (ErrorLevel.ERROR.compareTo(someOtherLevel) <= 0) { ... } ```
A version which is much more expressive would be ``` myError.isErrorOrAbove(otherError) ``` or ``` myError.isWorseThan(otherError) ``` This way you can define the ordering inside the Enum and can change the implementation internally if you like. Now the clients of the Enum can compare values without knowing any details about it. A possible implementation whould be ``` public enum ErrorLevel { INFO(0), WARN(1), ERROR(2), FATAL(3); private Integer severity; ErrorLevel(int severity) { this.severity = severity; } public boolean isWorseThan(ErrorLevel other) { return this.severity > other.severity; } } ``` I also would not recommend using the ordinal() method for comparison, because when somebody changes the order the Enum values are defined you could get unexpected behaviour.
Compare Java enum values
[ "", "java", "enums", "" ]
I'm using this code to add an item to the code window right click menu: ``` public void OnConnection( object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { _applicationObject = (DTE2)application; _addInInstance = (AddIn)addInInst; object[] contextGUIDS = new object[] { }; Command codeWindowCommand = null; CommandBarControl codeWindowButton; CommandBar codeCommandBar; CommandBars commandBars; try { codeWindowCommand = _applicationObject.Commands.Item( _addInInstance.ProgID + "." + CODEWINDOW_COMMAND_NAME, 0); } catch { } if (codeWindowCommand == null) { codeWindowCommand = _applicationObject.Commands.AddNamedCommand( _addInInstance, CODEWINDOW_COMMAND_NAME, CODEWINDOW_COMMAND_NAME, "Pastebin selected code", true, 18, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled); } commandBars = (CommandBars)_applicationObject.CommandBars; codeCommandBar = commandBars["Code Window"]; codeWindowButton = (CommandBarControl)codeWindowCommand.AddControl( codeCommandBar, codeCommandBar.Controls.Count + 1); codeWindowButton.Caption = "Text for button"; codeWindowButton.TooltipText = "Tooltip for button"; } ``` and the addin is set to autostart. However each time the run VS2008 it adds another button to the menu until I totally delete the addin. Anyone know how I fix this? I would for example wrap the Command.AddControl() and later stuff in an if that only executes if the button doesn't already exist, but I can't seem to find a way to check this in the API?
I remember seeing this problem elsewhere, and the reason was that the OnConnection method can be called at multiple times for multiple reasons (with different values of connectMode), so there is some trickery (or peculiarities, depending on how you look at it and how much of this you know) involved. However, I am not an expert on this topic, so here are some links that *will* help you: [HOWTO: Use correctly the OnConnection method of a Visual Studio add-in](http://www.mztools.com/articles/2008/MZ2008004.aspx) [HOWTO: Adding buttons, commandbars and toolbars to Visual Studio .NET from an add-in](http://www.mztools.com/articles/2008/..%5C2005%5CMZ2005003.aspx) [HOWTO: Controlling the state of command in a Visual Studio add-in](http://www.mztools.com/articles/2007/MZ2007025.aspx) Those are somewhat too long to just summarize here (at least it seems like that to me), but they do have the information you need. Also, here is a list of articles on writing VS addins, which will probably be very helpful: <http://www.mztools.com/resources_vsnet_addins.aspx> HTH. --- EDIT: Money J's answer is a bit more to the point, I suppose, and is basically a *very short* summary of what you need to do, and if that's all you're after - great. However, I believe that the information contained on the pages I provided the links to is very useful, so you might want to read that as well.
I haven't written an addin for VS.NET 2008 before, but seeing what you have available on your method: Check for ext\_cm\_UISetup? ``` if(connectMode == ext_ConnectMode.ext_cm_UISetup) { ``` also, in your try block you should be able to use the resourcemanager... ``` ResourceManager resourceManager = new ResourceManager("MyAddin1.CommandBar", Assembly.GetExecutingAssembly()); CultureInfo cultureInfo = new System.Globalization.CultureInfo (_applicationObject.LocaleID); string resourceName = String.Concat(cultureInfo. TwoLetterISOLanguageName, "Tools"); toolsMenuName = resourceManager.GetString(resourceName); ``` And a handy diagram that might help in the future. <http://msdn.microsoft.com/en-us/library/za2b25t3.aspx>
VS2008 Addin add to menu
[ "", "c#", "visual-studio-2008", "add-in", "visual-studio-addins", "" ]
I’m debugging a Java application that runs several threads. After a while of watching the log it seems that one of those threads is not running anymore. My guess is that the thread is waiting for a lock that is never released (the last output is before calling a synchronized method). Can I configure a timeout to the thread; a sort of “wait for this lock but if it not available after 10 seconds don’t wait anymore!”
You can use a [java.util.concurrent.Lock](http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/Lock.html) instead of the intrinsic `Object` locks. [RentrantLock](http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/ReentrantLock.html) without fair ordering has the same basic behaviour and semantics as an intrinsic lock. There is a method [`tryLock`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/Lock.html#tryLock) that takes a timeout parameter: ``` Lock lock = ...; if (lock.tryLock(10L, TimeUnit.SECONDS)) { try { // manipulate protected state } finally { lock.unlock(); } } else { // perform alternative actions } ```
Rather than adding extra code for debugging, you could use a debugging tool or profiler. One option is to use something like JConsole (comes with the JDK) which includes a button called "Detect Deadlock" (at least it does in Java 6, I don't think it works in Java 5). Another option is to generate a thread dump to the console - on Unix you can type "kill -3 " while on Windows CTRL+BRK will work. Other profiling tools such as VisualVM (also in the JDK) can help. Finally there is [JCarder](http://www.jcarder.org/ "JCarder") which is "an open source tool for finding potential deadlocks in concurrent multi-threaded Java programs".
How to detect deadlock ? Timeout in synchronized block?
[ "", "java", "multithreading", "deadlock", "" ]
I have a label in a master page (sample.master) called lblHeading. I want to dynamically change the text of the label when I load the content page. I need to do this because I want to change the heading to something meaningful but only after I know about the content of the page. Is this possible?
Yes. You want to create a [strongly-type master page](http://msdn.microsoft.com/en-us/library/c8y19k6h.aspx) and you can then access it's properties from your content page during Page\_Load or wherever else.
yes, you can in this very simple way........ ``` ((Label)Master.FindControl("lblHeading")).Text = "your new text"; ```
Can I change the text of a label in a masterpage when loading a content page?
[ "", "c#", "asp.net", "vb.net", "" ]
What would you use for a brand new cross platform GUI app, CPython or IronPython ? What about - license / freedom - development - - doc - - editors - - tools - libraries - performances - portability What can you do best with one or the other ? - networking - database - GUI - system - multi threading / processing
Use CPython, with IronPython you are bound to .Net platform which do not have much cross platform support, mono is there on linux but still for a cross platform app, I wouldn't recommend .Net. So my suggestion is use CPython, for GUI use a framework like wxPython/PyQT and you would be happy.
if you like/need to use .net framework, use ironpython, else CPython it's your choice (or you can try PyPy :))
CPython or IronPython?
[ "", "python", "ironpython", "cpython", "" ]
``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { List list = new List(); list.Add(new A()); var list2 = from p in list select p as B; Console.WriteLine(list2.First().myString); Console.ReadLine(); } } class A { public string myString = "abc"; } class B : A { } } ``` How can I solve this? Thanks
You can't do that; the list contains an instance of A, you can't cast A to B. You can only cast "upwards" in the inheritance chain, not downwards. So if you change places on A and B in your code, it works: ``` class Program { static void Main(string[] args) { List<B> list = new List<B>(); list.Add(new B()); var list2 = from p in list select p as A; Console.WriteLine(list2.First().myString); Console.ReadLine(); } } class A { public string myString = "abc"; } class B : A { } ``` If you want to convert in the other direction, you need to write code for the conversion: ``` class Program { static void Main(string[] args) { List<A> list = new List<A>(); list.Add(new B()); var list2 = list.ConvertAll<B>(a => B.FromA(a)); Console.WriteLine(list2.First().myString); Console.ReadLine(); } } class A { public string myString = "abc"; } class B : A { public B() { } public static B FromA(A fromInstance) { B result = new B(); result.myString = fromInstance.myString; return result; } } ```
`list2.First().myString` will try to access `myString` on a `null` reference. The `as` operator returns `null` if you can't cast. And object-oriented design principles tell us that you can use a *subclass* in any place where you can also use its *superclass* but *not* the other way around. So you're filling your list with instances of `A` and try to cast them to `B`. But they simply aren't instances of `B` so that cast will always fail (and, since you're using `as`, return `null`).
Convert son class to father class
[ "", "c#", "" ]
I'm building an isapi filter that will grab any url requests with the prefix "<http://localhost/>" and redirect that url request to my message page "<http://localhost/default.html>." Here's the solution: if(urlString.Find("/") != -1) { urlString.Replace(urlString, "/default.html");
the answer is: if(urlString.Find("/") != -1) { urlString.Replace(urlString, "/default.html");
The boost string algorithm library has some effective replace [features](http://www.boost.org/doc/libs/1_39_0/doc/html/string_algo/usage.html#id3408550).
managed c++ find and replace syntax
[ "", "c++", "mfc", "isapi-redirect", "" ]
What is the easiest way to convert the result of `Throwable.getStackTrace()` to a string that depicts the stacktrace?
One can use the following method to convert an `Exception` stack trace to `String`. This class is available in *Apache commons-lang which is most common dependent library with many popular open sources* [`org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable)`](http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/exception/ExceptionUtils.html#getStackTrace(java.lang.Throwable))
Use [`Throwable.printStackTrace(PrintWriter pw)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#printStackTrace-java.io.PrintWriter-) to send the stack trace to an appropriate writer. ``` import java.io.StringWriter; import java.io.PrintWriter; // ... StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String sStackTrace = sw.toString(); // stack trace as a string System.out.println(sStackTrace); ```
How can I convert a stack trace to a string?
[ "", "java", "stack-trace", "tostring", "" ]
I have the following list of slide objects. Based on the value of object's 'type' var I want to upcast the Slide object in the list. Is it possible? ``` foreach(Slide slide in slidePack.slides) { if(slide.type == SlideType.SECTION_MARKER) { //upcast Slide to Section } } ``` `Section` extends `Slide` and adds one more parameter.
Here's the proper way to handle that cast. Edit: There are ways to design programs to not need the test/cast you are looking for, but if you run into a case where to need to attempt to cast a C# object to some type and handle it different ways depending on success, this is definitely the way to do it. ``` Section section = slide as Section; if (section != null) { // you know it's a section } else { // you know it's not } ```
Yes you can do that: ``` Section section = (Section)slide; ``` ...or: ``` Section section = slide as Section; ``` The difference between those is that the first one will throw an exception if `slide` cannot be cast to `Section`, while the second one will return `null` if the cast is not possible.
c# How to downcast an object
[ "", "c#", ".net", "" ]
What is the fastest way to import 15000000 records from Text File to SQL Server? Currently, I am importing data using Enterprise Manager, that takes 3-4 hours for importing into the SQL table. Thanks in advance!
Try [bcp utility or BULK INSERT statement](http://msdn.microsoft.com/en-us/library/aa196743(SQL.80).aspx). BULK INSERT statement should be [faster](http://msdn.microsoft.com/en-us/library/aa178096(SQL.80).aspx) though.
Using SSIS there is a published benchmark that [loads 2.36TB per hour](http://blogs.msdn.com/sqlperf/archive/2008/02/27/etl-world-record.aspx). There are tricks you can do, like split the file parsing and spread the load on separate NUMA listening ports. Also the articles quotes matching the column types properly in SSIS is a big factor.
Fastest Way to Import?
[ "", "sql", "sql-server", "" ]
I have a loop that reads plenty of data from an external source. The process takes about 20 seconds, and I want to show the progress to the user. I don't need any fancy progress bars, so I chose to plot my progress in a label that will say "Step 1/1000", then change to "Step 2/1000" etc. My code looks something like this: ``` // "count" is the number of steps in the loop, // I receive it in previous code String countLabel = "/"+count.ToString(); for (i = 0; i < count; i++) { ... do analysis ... labelProgress.Content = "Step "+i.ToString()+countLabel } ``` However, during that analysis the screen is "stuck" and the progress does not show as advancing. I understand this behavior from my past in C++, where I would probably have a separate thread showing a progress bar receiving notifications from the loop, or some form of repaint/refresh, or forcing the window/app to process its message queue. What's the right way to do it in C#? I'm not tied to the label, so if there's a simple progress-bar popup screen I could use instead of this label it would also be great... Thanks
Move the work to a [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) and use the [ReportProgress](http://msdn.microsoft.com/en-us/library/ka89zff4.aspx) method. ``` for (i = 0; i < count; i++) { ... do analysis ... worker.ReportProgress((100 * i) / count); } private void MyWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { taskProgressBar.Value = Math.Min(e.ProgressPercentage, 100); } ```
``` //Create a Delegate to update your status button delegate void StringParameterDelegate(string value); String countLabel = "/" + count.ToString(); //When your button is clicked to process the loops, start a thread for process the loops public void StartProcessingButtonClick(object sender, EventArgs e) { Thread queryRunningThread = new Thread(new ThreadStart(ProcessLoop)); queryRunningThread.Name = "ProcessLoop"; queryRunningThread.IsBackground = true; queryRunningThread.Start(); } private void ProcessLoop() { for (i = 0; i < count; i++) { ... do analysis ... UpdateProgressLabel("Step "+i.ToString()+countLabel); } } void UpdateProgressLabel(string value) { if (InvokeRequired) { // We're not in the UI thread, so we need to call BeginInvoke BeginInvoke(new StringParameterDelegate(UpdateProgressLabel), new object[] { value }); return; } // Must be on the UI thread if we've got this far labelProgress.Content = value; } ```
How do I display progress during a busy loop?
[ "", "c#", "wpf", "progress-bar", "" ]
I currently have multiple versions of Python installed on my Mac, the one that came with it, a version I downloaded recently from python.org, an older version used to run Zope locally and another version that Appengine is using. It's kind of a mess. Any recommendations of using one version of python to rule them all? How would I go about deleted older versions and linking all of my apps to a single install. Any Mac specific gotchas I should know about? Is this a dumb idea?
There's nothing inherently wrong with having multiple versions of Python around. Sometimes it's a necessity when using applications with version dependencies. Probably the biggest issue is dealing with site-package dependencies which may vary from app to app. Tools like [`virtualenv`](http://pypi.python.org/pypi/virtualenv) can help there. One thing you should **not** do is attempt to remove the Apple-supplied Python in /System/Library/Frameworks and linked to from /usr/bin/python. (Note the recent discussion of multiple versions [here](https://stackoverflow.com/questions/1213690/what-is-the-most-compatible-way-to-install-python-modules-on-a-mac/).)
Ian Bicking's [virtualenv](http://pypi.python.org/pypi/virtualenv) allows me to have isolated Pythons for each application I build, and lets me decide whether or not to include the global site-packages in the isolated Python environment. I haven't tried it with Zope, but I'm guessing that the following should work nicely: 1. Using your Zope's Python, make a new virtualenv, either with or without --no-site-packages 2. Drop your Zope into the virtualenv 3. Activate the environment with $VENV/bin/activate 4. Install any needed site-packages 5. Run your Zope using the Python now at $VENV/bin/python This has worked brilliantly for managing Django projects with various versions of Python, Django, and add-ons. [This article](http://grok.zope.org/documentation/how-to/using-virtualenv-for-a-clean-grok-installation) seems to go into more detail on the specifics of Grok and Virtualenv, but the generalities should apply to Zope as welll.
Multiple versions of Python on OS X Leopard
[ "", "python", "macos", "osx-leopard", "zope", "" ]
I have installed different versions of PHP and MySQL on wampserver for testing purposes. However, phpMyAdmin gives a warning that: "Your PHP MySQL library version 5.0.51a differs from your MySQL server version 5.1.36. This may cause unpredictable behavior." Is this going to cause problems?? If yes, what should be done? I am not able to set up a password for my root account. Normally, on changing the root account password, phpMyAdmin gives an error. Thereafter, setting the password in the config.inc.php file does the job. But, the problem with me is that I am not at all getting that error screen. Even when I change the password, it still gives the same warning that no password is set up for the root account.
No, it should not cause a problem. I have very little respect for phpMyAdmin as a system. I have never experienced a problem using different client/server versions with MySQL, and we have used them on a large scale in production. I don't believe a word of it. If phpmyadmin says it, does not necessarily mean it's true. MySQL client/server versions are very largely compatible, unless you're looking at very elderly versions of either of them (i.e. < 5.0)
If you are using this machine for development only *(seems you do : "for testing purposes")*, I don't think it should be much of a problem. I've seen that kind of message a few times, and never experimented any trouble that might be related. *(If it had been 4.0 and 4.1, maybe, as there were lots of important new stuff added... But between 5.0 and 5.1, I don't think so)* To correct that "problem", you'd have to install a new version of the libraries used by PHP... And I'm not sure the most recent version of PHP 5.2 (5.2.10) uses libmysql 5.1... And you probably don't want to recompile anything by yourself ^^ Other solution would be to downgrade to MySQL 5.0.x ; but I wouldn't care, for a testing machine, unless I run into strage behaviour.
Unpredictable behavior due to different MySQL versions
[ "", "php", "mysql", "wampserver", "" ]
I need something to get the position of a sub-sub element relative to the container. TransformToAncestor does that. However, the element and subelements move, resize change, their layout, etc. I need a way to keep the position up-to-date. Like an event if anything happend that would affect my TransformToAncestor operation. Or an "AbsolutePosition" dependency property I can bind to. Background: I'm doing sort of a work flow editor. There are 'modules' that have one or more ports and lines that connect the modules from port to port. The XAML stucture looks like this: ``` <Canvas> <Module Left="..." Top="..." Width="..." Height="..."> <Grid><otherelement><somemorelayouting> <Port Name="a" /> <Port Name="b" /> </somemorelayouting></otherelement></Grid> </Module> <Module Left="..." Top="..." Width="..." Height="..."> <differentsetoflayouts> <Port Name="c" /> <Port Name="d" /> </differentsetoflayouts> </Module> <Line startpoint="{binding source=a, path=abs_position}" endpoint="{binding source=c, path=abs_position}" /> </Canvas> ``` The line connects port a of the first module with port b of the second. The end points should be at the top left corner of the port-element (for the moment). This "abs\_position" property used in this example does unfurtunatly not exist (I'm using start/endpoint here instead of X1,X2,Y1,Y2 only to improve readability)
If you implement your container with attached dependency properties for location of children elements (like the [Canvas](http://msdn.microsoft.com/en-us/library/system.windows.controls.canvas.aspx) panel does, which seems to be the case according to provided code), then you can bind to changes of that dependency property using a [DependencyPropertyDescriptor](http://msdn.microsoft.com/en-us/library/system.componentmodel.dependencypropertydescriptor.aspx). ``` DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(Canvas.TopProperty, typeof(Canvas)); dpd.AddValueChanged(canvas1, new EventHandler(topChangedCallback)); ```
I propose to use kek444's solution with a custom layout if possible. However should this not be applicable, here is another approch I found while googling kek444's hints. The event [UIElement.LayoutUpdated](http://msdn.microsoft.com/en-us/library/system.windows.uielement.layoutupdated.aspx "UIElement.LayoutUpdated") is fired whenever something on the layout changes. It reacts to movement, resize, add/remove of elements, and about anything anything else. It does not only fire if the element is affected on which the event is registered, but also if any other element using the same dispatch thread is touched. As a result it is fired very often, so using it might have quite some performance impact. See also Dave Relyea's blog entry. Stackoverflow does not let me post two links, so just google for "Layout Events - SizeChanged and LayoutUpdated".
Bind to element's position relative to a parent in WPF
[ "", "c#", ".net", "wpf", "" ]
I am running a webapp inside Webpshere Application Server 6.1. This webapp has a rules kind of engine, where every rule obtains its very own connection from the websphere data source pool. So, I see that when an use case is run, for 100 records of input, about 400-800 connections are obtained from the pool and released back to the pool. I have a feeling that if this engine goes to production, it might take too much time to complete processing. Is it a bad practice to obtain connections from pool that frequently? What are the overhead costs involved in obtaining connections from pool? My guess is that costs involved should be minimal as pool is nothing but a resource cache. Please correct me if I am wrong.
Connection pooling keeps your connection alive in anticipation, if another user connects the ready connection to the db is handed over and the database does not have to open a connection all over again. This is actually a good idea because opening a connection is not just a one-go thing. There are many trips to the server (authentication, retrieval, status, etc) So if you've got a connection pool on your website, you're serving your customers faster. Unless your website is not visited by people you can't afford not to have a connection pool working for you.
The pool doesn't seem to be your problem. The real problem lies in the fact that your "rules engine" doesn't release connections back to the pool before completing the entire calculation. The engine doesn't scale well, so it seems. If the number of database connections somehow depends on the number of records being processed, something is almost always very wrong! If you manage to get your engine to release connections as soon as possible, it may be that you only need a few connections instead of a few hundred. Failing that, you could use a connection wrapper that re-uses the same connection every time the rules engine asks for one, that somewhat negates the benefits of having a connection pool though... Not to mention that it introduces many multithreading and transaction isolation issues, if the connections are read-only, it might be an option.
Connection Pooling - How much of an overhead is it?
[ "", "java", "jdbc", "jakarta-ee", "websphere", "connection-pooling", "" ]
I have lots of jquery functions in my script but a particular one is not working, this is my function ``` $('#delete').click(function() { var id = $(this).val(); $.ajax({ type: 'post', url: 'update.php', data: 'action=delete&id=' + id , success: function(response) { $('#response').fadeOut('500').empty().fadeIn('500').append(response); $(this).parent('tr').slideUp('500').empty(); } }); }); ``` a similar function like this is working ``` <!-- WORKING FUNCTION --> $('#UpdateAll').click(function() { $.ajax({ type: 'post', url: 'update.php', data: 'action=updateAll', success: function(response) { $('#response').fadeOut('500').empty().fadeIn('500').append(response); $('#table').slideUp('1000').load('data.php #table', function() { $(this).hide().appendTo('#divContainer').slideDown('1000'); }); } }); }); ``` I checked with firebug, the console doesnt show any errors, i checked html source the values are loading correct, i checked my php file 5times it is correct can't figure out the problem. Please Help.
Instead of **id=delete** i changed it to **class=delete** in html and in js **('.delete')** and it is working fine now but when again tried with id it doesnt work. Thank You all for Help, i dont have any problem whether it is id or class just the function works now.
I struggled with the EXACT SAME PROBLEM for 6hr straight! the solution was to use jquery 'live'. And that is it. ``` $('#submit').live('click',function(){ ...code... }); ```
.click function not working for me
[ "", "javascript", "jquery", "" ]
I have an object called ValueBox that I created like this: ``` function ValueBox(params) { ... $.extend(true, this, $('/* some HTML elements */')); ... var $inputBox = $('input[type=text]', this); ... this.val = function(newValue) { if(typeof newValue == "number") { $inputBox.val(newValue); $inputBox.change(); } else { return parseFloat($inputBox.val()); } } } ``` I have a change event on a particular ValueBox instance which fires whenever the `$inputBox` changes, but the change callback function is unable to use the val() method in my class. I assume that by using `$(this).val()` that I'm calling the jQuery val() method, which of course wouldn't work. Is it possible to access the val() method that I defined?
When you call `$inputBox.change()`, pass it the `ValueBox` object. Then call `val` on that. That way, you won't have to worry about scoping problems within jQuery controls.
``` $.fn.yourpluginscope.originalVal = $.fn.val; $.fn.extend({ val: function (value) { if (/* detect your plugin element */) { if (value == undefined) return /* getter */; return $.fn.yourpluginscope.originalVal.call(/* setter */, value); } return $.fn.yourpluginscope.originalVal.call(this, value); } }); ``` Proper way to extends "native" jQuery method
jQuery val() Method on a Custom Object
[ "", "javascript", "jquery", "inheritance", "oop", "user-defined", "" ]
what I want to do: call an unload-function to change ``` <span>some content</span> ``` into ``` <label>some content</label> ``` Is it possible to change a span-tag into a label-tag with javascript? If it is possible how can I do that? Thnx, ... doro
And if you're using jQuery you can use replaceWith() ``` jQuery.each($("span"), function() { $(this).replaceWith("<label>" + $(this).text() + "</label>"); }); ``` More information at: <http://docs.jquery.com/Manipulation/replaceWith>
First you need to gain a reference to the SPAN element, then you can go about replacing it with a new element: HTML: ``` <span id="something">Content</span> ``` JavaScript: ``` var span = document.getElementById('something'); var label = document.createElement('label'); label.innerHTML = span.innerHTML; span.parentNode.replaceChild( label, span ); ```
Change all span-tags into label-tags with Javascript?
[ "", "javascript", "" ]
I'm not familiar with Qt or with [Google Native Client](http://en.wikipedia.org/wiki/Google_Native_Client). Is it possible for a TRIVIAL Qt console application to be ported to Google Native Client? I understand that *some* work would be involved. But the question is, how much if it's even possible?
A Qt developer has managed to get some Qt examples running under Native Client: <http://blog.qt.io/blog/2009/12/17/take-it-with-a-grain-of-salt/>
Qt now has an official Native Client SDK: <http://qt-project.org/wiki/Qt_for_Google_Native_Client>
Does a Qt application work in Google Native Client?
[ "", "c++", "qt", "browser", "qt4", "google-nativeclient", "" ]
What does it mean? I am debugging C# code.
Grey lines are statements which are on the call stack, including other threads' call stacks. In other words, statements which started, but have not yet finished executing, are greyed. Try clicking on various functions listed in the call stack + switching to other threads and clicking.
Those are the lines comprising the call stack *other* than the line for the current frame. Here's a picture: [![Call Stack Highlighting](https://i.stack.imgur.com/kuAX1.png)](https://i.stack.imgur.com/kuAX1.png) (source: [280z28.org](http://www.280z28.org/images/CallStackHighlighting.png))
In visual studio, some lines of code have light grey background while debugging
[ "", "c#", "visual-studio", "" ]
I have methods returning private collections to the caller and I want to prevent the caller from modifying the returned collections. ``` private readonly Foo[] foos; public IEnumerable<Foo> GetFoos() { return this.foos; } ``` At the moment the private collection is a fixed array, but in the future the collection might become a list if the need for adding new items at run time arises. There are several solutions to prevent the caller from modifying the collection. Returning `IEnumerable<T>` is the simplest solution, but the caller can still up-cast the return value to `IList<T>` and modify the collection. ``` ((IList<Foo>)GetFoos())[0] = otherFoo; ``` Cloning the collections has the obvious disadvantage that there are two collections that can evolve independently. So far I have considered the following options. 1. Wrapping the collection in `ReadOnlyCollection<T>`. 2. Returning one of the LINQ iterators defined by the `Enumerable` class by performing a dummy projection like `list.Select(item => item)`. Actually I consider using `Where(item => true)` because the returned iterator seems more lightweight. 3. Writing a custom wrapper. What I don't like about using `ReadOnlyCollection<T>` is that it implements `IList<T>` and calling `Add()` or accessing the indexer will cause exceptions. While this is absolutly correct in theory, almost no real code checks `IList<T>.IsReadOnly` or `IList<T>.IsFixedSize`. Using the LINQ iterators - I wrapped the code in an extension method `MakeReadOnly()` - prevents this scenario, but it has the taste of a hack. Writing a custom wrapper? Reinventing the wheel? Any thoughts, considerations, or other solutions? --- While tagging this question, I discovered [this Stack Overflow question](https://stackoverflow.com/questions/491375/readonlycollection-or-ienumerable-for-exposing-member-collections) I didn't notice before. Jon Skeet suggest to use the "LINQ hack", too, but even more efficient using `Skip(0)`.
Unfortunately there is no way to achieve **exactly** what you are looking for in the current version of the framework. It simply has no concept of an indexable immutable / read-only collection on both the concrete type and interface style. As you pointed out, `ReadOnlyCollection<T>` works OK on the concrete type side. But there is no corresponding interface to implement which is also statically read-only. You're only real choice is to ... * Define your own collection class * Either only implement `IEnumerable<T>` or define a need read-only interface which your collection implements.
How about making a deep copy of the object being returned? [So there will be no effect on the original collection even if the caller decides to make changes to the copy returned]
How to prevent a method caller from modifying a returned collection?
[ "", "c#", "collections", "ienumerable", "readonly-collection", "" ]
I want to upload a file with AJAX in Wicket. It seems to me that Wicket does not support this feature. Is it possible?
Check out the source code from the Wicket Examples for upload: <http://www.wicketstuff.org/wicket13/upload/single>. It has examples for both standard and ajax versions.
As an update to an old question, it seems it is possible right now: <http://www.wicket-library.com/wicket-examples/ajax/upload>
Upload a file AJAX-ically using Wicket
[ "", "java", "ajax", "file-upload", "wicket", "" ]
I tried to ask this before, and messed up the question, so I'll try again. Is it possible to make an object return false by default when put in an if statement? What I want: ``` $dog = new DogObject(); if($dog) { return "This is bad;" } else { return "Excellent! $dog was false!" } ``` Is there a way this is possible? It's not completely necessary, but would save me some lines of code. thanks!
No, PHP has no support for operator overloading. Maybe they'll add it in a future version.
Use the instanceof keyword. For example ``` $result = Users->insertNewUser(); if($result instanceof MyErrorClass){ (CHECK WHAT WENT WRONG AND SAY WHY) } else { //Go on about our business because everything worked. } ``` [Info is here.](http://us.php.net/manual/en/language.operators.type.php)
Is it possible to make an object return false by default?
[ "", "php", "if-statement", "boolean-expression", "" ]
I'm Looking at using Amazon S3 and simpleDB in a desktop application. The main issue I have is that I either need to store my aws credentials in the application or use some other scheme. I'm guessing that storing them in the application is out of the question as they would be easily picked out. Another option is to create a web service that creates the aws authentication signature but this has its own issues. Does the signature require all the data from a file thats being uploaded? If so I would have to transfer all the data twice. There would then be a central failure point which was one of the main reasons for using aws. Any ideas? **UPDATE:** I needed to make it a bit clearer that I'm wanting to store my aws credentials in an application handed out to others. DPAPI or any other encryption would be only stop people simply using reflector to get the credentials. Using any encryption still needs the key that is easy to get. **UPDATE 2 - Sept 2011** Amazon have released some details on using the AWS Security Token Service, which allows for authentication without disclosing your secret key. More details are available on [this blog post](http://aws.typepad.com/aws/2011/09/updated-mobile-sdks-for-aws-improved-credential-management.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:%20AmazonWebServicesBlog%20%28Amazon%20Web%20Services%20Blog%29).
Tim, you're indeed hitting on the two key approaches: 1. NOT GOOD ENOUGH: store the secret key "secretly" in the app. There is indeed a grave risk of someone just picking it out of the app code. Some mitigations might be to (a) use the DPAPI to store the key outside the app binary, or (b) obtain the key over the wire from your web service each time you need it (over SSL), but never store it locally. No mitigation can really slow down a competent attacker with a debugger, as the cleartext key must end up in the app's RAM. 2. BETTER: Push the content that needs to be protected to your web service and sign it there. The good news is that only the request name and timestamp need to be signed -- not all the uploaded bits (I guess Amazon doesn't want to spend the cycles on verifying all those bits either!). Below are the relevant code lines from Amazon's own "[Introduction to AWS for C# Developers](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=875&categoryID=47)". Notice how `Aws_GetSignature` gets called only with "PutObject" and a timestamp? You could definitely implement the signature on your own web service without having to send the whole file and without compromising your key. In case you're wondering, `Aws_GetSignature` is a 9-line function that does a SHA1 hash on a concatenation of the constant string "AmazonS3", the operation name, and the RFC822 representation of the timestamp -- using your secret key. ``` DateTime timestamp = Aws_GetDatestamp(); string signature = Aws_GetSignature( "PutObject", timestamp ); byte[] data = UnicodeEncoding.ASCII.GetBytes( content ); service.PutObjectInline( "MainBucket", cAWSSecretKey, metadata, data, content.Length, null, StorageClass.STANDARD, true, cAWSAccessKeyId, timestamp, true, signature, null ); ``` EDIT: note that while you can keep the secret key portion of your Amazon identity hidden, the access key ID portion needs to be embedded in the request. Unless you send the file through your own web service, you'll have to embed it in the app.
You can encrypt the config file and/or use ProtectedData. [Here's my blog post on both](http://weblogs.asp.net/jgalloway/archive/2008/04/13/encrypting-passwords-in-a-net-app-config-file.aspx). UPDATE: You might be a be to encrypt your app.config as part of an install step. Sample here: <http://www.codeproject.com/KB/security/encryptstrings.aspx>. Not great, but the best I've found so far.
Storing My Amazon Credentials in C# Desktop App
[ "", "c#", ".net", "amazon-s3", "amazon-web-services", "" ]
I need a client networking thread to be able to respond both to new messages to be transmitted, and the receipt of new data on the network. I wish to avoid this thread performing a polling loop, but rather to process only as needed. The scenario is as follows: A client application needs to communicate to a server via a protocol that is largely, but not entirely, synchronous. Typically, the client sends a message to the server and blocks until a response is received. The server may process client requests asynchronously, in which case the response to client is not a result, but a notification that processing has begun. A result message is sent to to the client at some point in the future, when the server has finish processing the client request. The asynchronous result notifications can arrive at the client at any time. These notifications need processed when they are received i.e. it is not possible to process a backlog only when the client transmits again. The clients networking thread receives and processes notifications from the server, and to transmit outgoing messages from the client. To achieve this, I need to to make a thread wake to perform processing either when network data is received OR when a message to transmit is enqueued into an input queue. How can a thread wake to perform processing of an enqueued work item OR data from a socket? I am interested primarily in using the plain Win32 APIs. A minimal example or relevant tutorial would be very welcome!
An alternative to I/O Completion Ports for sockets is using [WSAEventSelect](http://msdn.microsoft.com/en-us/library/ms741576(VS.85).aspx) to associate an event with the socket. Then as others have said, you just need to use another event (or some sort of waitable handle) to signal when an item has been added to your input queue, and use WaitForMultipleObjects to wait for either kind of event.
You can set up an I/O Completion Port for the handles and have your thread wait on the completion port: * <http://technet.microsoft.com/en-us/sysinternals/bb963891.aspx> Actually, you can have multiple threads wait on the port (one thread per processor usually works well).
How to get a Win32 Thread to wait on a work queue and a socket?
[ "", "c++", "winapi", "winsock", "" ]
we have windows app. which expected to connect different soap web services. Service urls are added dynamically to database.I tried "Add Web Reference" feather but problem is it accepts only one url. Can any one suggest different approach?or link to source
The source of **qasanov**'s finding: <http://blogs.msdn.com/kaevans/archive/2006/04/27/585013.aspx>
Just set the Url property of the proxy. See [Ways to Customize your ASMX Client Proxy](http://johnwsaundersiii.spaces.live.com/blog/cns!600A2BE4A82EA0A6!435.entry).
.NET soap client call
[ "", "c#", "soap", "" ]
I've done a decent search, but can't seem to find a way to get Visual Studio 2008 to use a unix Makefile, or even to create some MSVC compatible equivalent from the Makefile. Does anyone have ideas or similar issues? Note: I already know the benefits/drawbacks of using Makefiles or not, and I don't want to hear your opinion. All I'm interested in right now is creating a Windows library from some originally unix code which only has a Makefile, and getting something functional out of it. TIA.
You can also use [cccl](http://cccl.sourceforge.net/) with [make for windows](http://gnuwin32.sourceforge.net/packages/make.htm). > cccl is a wrapper around Microsoft > Visual C++'s cl.exe and link.exe. It > converts Unix compiler parameters into > parameters understood by cl and link.
What you can do is create a project from existing code. Visual C++ does a pretty good job at compilation without makefiles. You could also install MinGW and that has `make` and the compilers. <http://www.mingw.org/>
Unix Makefile in Windows Visual Studio 2008
[ "", "c++", "visual-studio-2008", "makefile", "" ]