Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a sentence which is analyzed in different phases. First, I get some attributes (say, X, Y, Z): ``` public class AnalyzedSentence { private String X; private String Y; private String Z; public AnalyzedSentence(String sentence) { extractX(); extractY(); extractZ(); } // getters, setters } ``` Then, I use these attributes to further analyze the sentence to get another attribute, say, "XYZ", after which I create the following class: ``` public class FinalSentence { private AnalyzedSentence data; private String XYZ; public FinalSentence(String XYZ, AnalyzedSentence data) { this.data = data; this.XYZ = XYZ; } // getters, setters } ``` The workflow goes like this: ``` public class SentenceAnalyzer { /// ... public FinalSentence analyze(String sentence) { AnalyzedSentence as = new AnalyzedSentence(sentence); // every attribute of "as" can be calculated beforehand String XYZ = SpecialClass.extractXYZ(sentence, as); // extract XYZ (needs a special class), based on as return new FinalSentence(XYZ, as); } } ``` Alternatively, I could have just a single class holding all the information, filling the attributes as they were extracted, which could result in some null results. It'd be like so: ``` public class Sentence { private String X; private String Y; private String Z; private String XYZ; public Sentence(String sentence) { extractX(); extractY(); extractZ(); } public String getXYZ() { // with this design, this method can be called, even if XYZ was not extracted yet. // remember that XYZ cannot be extracted as X,Y,Z } public void setXYZ(...) {...} // getters, setters } ``` My question is: which design is preferred, and why ? If there's also a better way to accomplish what I'm trying to do here, I'd also like to hear it.
What you need to consider, is whether, in your problem domain, an AnalyzedSentence and FinalSentence are unique enough to be split or merged. It's clear they're working with similar data and cooperating closely in order to achieve the goal. To me, analysed and final are just states that a Sentence could be in, although that is based on my limited knowledge of the problem you're working on, so I would look to combine them in some way. **Edit** Based on the further information, I think I would design it something like this: The `Sentence` class encapsulates the original sentence, the tags, and the extracted category (or whatever it is you're extracting, I'm assuming it's a category based on your description), and the operations to set, get, and extract that information. The `Sentence` class stores a `TagList` that contains all the tags, the original string, and the extracted category. It also encapsulates the extraction of the data by creating an `Extractor` and passing it the `TagList` when the data needs extraction (I've put it in the constructor, but it could go in a method, where it gets called depends on when you need to extract the data). So in this way, everything required to manipulate the original sentence is in the `Sentence` class. Of course, you may know something that I don't that makes this approach unsuitable, but here's some code to illustrate what I mean: ``` public class Sentence { private TagList tags private String category; private String sentence public Sentence(String newSentence) { sentence = newSentence; Extractor<TagList> e = new Extractor<TagList>() tags = e.extractTags(sentence); category = new Category(tags); } public String getXYZ() { } public void setXYZ(...) {...} private extractTags(String s){ ...} // getters, setters } public class TagList{ private List<String> tags; .... //rest of class definition } ```
Personally I prefer the first design, the one with two classes. The distinction between analysis and results is appealing to me. I like to think of classes as collections of responsibilities more than collections of data, and using two distinct classes makes the responsibility of each more clear.
To split or not to split a class (in Java)
[ "", "java", "oop", "" ]
What is the cost of parsing a large XML file using PHP on every page request? I would like to implement custom tags in HTML. ``` <?xml version="1.0"?> <html> <head> <title>The Title</title> </head> <body> <textbox name="txtUsername" /> </body> </html> ``` After I load this XML file in PHP, I search for the custom tags using XPath and manipulate or replace them. Is this very costly or is it acceptable? What about applying this to a large scale web site? In the past I also used XSLT for large sites, and it didn't seem to slow things down. This is somehow similar to XSLT, but manual.
Parsing the xml should be fast, as long as you use builtin functions like [DOMXPath](http://php.net/manual/en/class.domxpath.php) and your xml files are not too large. However, I would rather replace the custom tags with function-calls and include the file in php, which should be a *lot* faster, since you're not doing any string manipulation in PHP then: ``` <?xml version="1.0"?> <html> <head> <title>The Title</title> </head> <body> <?php textbox('txtUsername') ?> </body> </html> ```
I would guess pretty costly, but the best way is to test it yourself and measure the peak memory usage and time required to run the script. You might be able to cache some intermediate state, so that the heavy XML parsing doesn't have to be done everytime - maybe you could replace the tags with actual PHP code like Smarty does and then include that generated/cached PHP file instead. The cached file could look like the code in Soulmerge's answer.
PHP and XML: The cost of parsing a large XML file every page request
[ "", "php", "xml", "model-view-controller", "dom", "parsing", "" ]
In other languages I can set up the method signature like ``` cookEgg(boolean hardBoiled = true) ``` This defaults the parameter `hardboiled` to `true`, if I don't receive a parameter in the method call. How would I achieve this in C#?
At present, you have to overload the method: ``` void cookEgg(bool hardBoiled) { ... } void cookEgg() { cookEgg(true); } ``` C# 4.0 will add optional arguments - you will be able to write code exactly as in your original sample, and it will work as you'd expect.
Default parameters are supported in C# 4 (Visual Studio 2010). <http://msdn.microsoft.com/en-us/library/dd264739(VS.100).aspx>
How to use default parameters in C#?
[ "", "c#", ".net", "parameters", "default-value", "optional-parameters", "" ]
To begin with, I would normally opt to use a pre-compiled binary of PHP, but am required to build from source for a specific business need. (I'm not the type that compiles open-source apps just for kicks.) I'm building on OS X 10.6 and am running into the following error when I try to `make` PHP 5.2.10 as an Apache module (`--with-apxs2`): ``` Undefined symbols: "_res_9_dn_expand", referenced from: _zif_dns_get_mx in dns.o "_res_9_search", referenced from: _zif_dns_get_mx in dns.o _zif_dns_check_record in dns.o "_res_9_dn_skipname", referenced from: _zif_dns_get_mx in dns.o _zif_dns_get_mx in dns.o ld: symbol(s) not found ``` These symbols are part of `libresolv`, which is included at `/usr/lib/libresolv.dylib` on OS X (and has been since *at least* 10.4). Note that `*.dylib` files are the Mac equivalent of `*.so` files on Linux, and I've successfully compiled in `libiconv.dylib` already by passing `--with-iconv=shared,/usr` to `./configure`, which eliminated similar linker errors for the `iconv` library. When I run `./configure`, it detects `/usr/include/resolv.h` and enables it in the makefile. However, I can't seem to figure out how to get the shared library to link in correctly. Any tips on getting that to work? I've never done anything like passing custom linker flags to `./configure`, and Google has been no help to me for this problem, unfortunately. --- **Edit:** I'm building from [this TAR download](http://www.php.net/distributions/php-5.2.10.tar.gz) if anyone wants to try to replicate the error on Snow Leopard.
Try adding -lresolv to your Makefile. Hope this helps. I got the suggestion from this [discussion](http://trac.macports.org/ticket/19997).
If you set the configure environment variable before running the configure script, you don't have to edit the makefile. For example: ``` LIBS=-lresolv ./configure --with-apxs2 --with-gd (etc.) ``` This solution worked for me.
Errors linking libresolv when building PHP 5.2.10 from source on OS X
[ "", "php", "compilation", "automake", "" ]
I've written a little function to take a url, and resize the image and store it on my local, however the script is taking about .85 seconds to run when it needs to create the folder, and .64 seconds on a resize. I currently have JPEG and PNG supported as seen below. I'm wondering if there is a quicker method or something I'm doing that is taking to long, as the current times i have are unacceptable for me, I would really like to get this to execute faster. Any thoughts / ideas are greatly appreciated. Thank you! ``` function getTime() { $timer = explode( ' ', microtime() ); $timer = $timer[1] + $timer[0]; return $timer; } function createThumb($thumb, $ids){ $start = getTime(); // File and new size $filename = $thumb; // Get new dimensions $img1 = getimagesize($filename); if ($img1[0] > $img1[1]) { $percentage = ('72' / $img1[0]); } else { $percentage = ('72' / $img1[1]); } $new_width = $img1[0] * $percentage; $new_height = $img1[1] * $percentage; // Resample $image_p = imagecreatetruecolor($new_width, $new_height); if($img1['mime']=='image/png'){ $image = imagecreatefrompng($filename); imagealphablending($image_p, false); imagesavealpha($image_p,true); $transparent = imagecolorallocatealpha($image_p, 255, 255, 255, 127); imagefilledrectangle($image_p, 0, 0, $new_width, $new_height, $transparent); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $img1[0], $img1[1]); } else { $image = imagecreatefromjpeg($filename); } imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $img1[0], $img1[1]); $imgPath = '/foo/bar/location/'.$ids; $imgName =''; //category, product, support if(!is_dir($imgPath)) { mkdir($imgPath, 0777); chmod($imgPath, 0777); } if(!is_file($imgPath."/index.html")){ $ourFileName = $imgPath."/index.html"; $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file"); fwrite($ourFileHandle,'<html><body>401</body></html>'); fclose($ourFileHandle); } // Output if($img1['mime']=='image/png'){ $name = rand(1, 156406571337); $imgName = date("y_m_d_h_m_s").$name.'.png'; imagepng($image_p, $imgPath.'/'.$imgName); } else { $name = rand(1, 156406571337); $imgName = date("y_m_d_h_m_s").$name.'.jpg'; imagejpeg($image_p, $imgPath.'/'.$imgName, 100); } $end = getTime(); echo '<strong>createImage</strong>: '.round($end - $start,4).' seconden<br />'; exit; return $imgName; } ```
Frederico, yea the GD library is just plain slow. :-\ I'd suggest using the PHP ImageMagick library. The syntax is super braindead simple: ``` $image = new Imagick('image.jpg'); $image->thumbnailImage(100,0); // 100px wide, 0 = preserve aspect ratio ``` I hope this is an option for you.
Ultimately, image manipulation is a CPU- and time-intensive action. 0.64 seconds isn't outrageous on a decently sized image by any means. ImageMagick, as suggested above, is likely to be a bit faster, but it's still going to take a lot longer than outputting a bunch of text.
PHP Image Resize / Relocate - Speeding it up
[ "", "php", "performance", "optimization", "" ]
A bit of background first: [GeoModel](http://code.google.com/p/geomodel) is a library I wrote that adds very basic geospatial indexing and querying functionality to App Engine apps. It is similar in approach to geohashing. The equivalent location hash in GeoModel is called a 'geocell.' Currently, the GeoModel library adds 13 properties (location\_geocell\_\_n\_, *n*=1..13) to each location-aware entity. For example, an entity can have property values such as: ``` location_geocell_1 = 'a' location_geocell_2 = 'a3' location_geocell_3 = 'a3f' ... ``` This is required in order to not use up an inequality filter during spatial queries. The problem with the 13-properties approach is that, for any geo query an app would like to run, 13 new indexes must be defined and built. This is definitely a maintenance hassle, as I've just painfully realized while rewriting the demo app for the project. This leads to my first question: ***QUESTION 1:*** Is there any significant storage overhead per index? i.e. if I have 13 indexes with n entities in each, versus 1 index with 13n entities in it, is the former much worse than the latter in terms of storage? It seems like the answer to (1) is no, per [this article](http://code.google.com/appengine/articles/index_building.html), but I'd just like to see if anyone has had a different experience. Now, I'm considering adjusting the GeoModel library so that instead of 13 string properties, there'd only be one StringListProperty called location\_geocells, i.e.: ``` location_geocells = ['a', 'a3', 'a3f'] ``` This results in a much cleaner `index.yaml`. But, I do question the performance implications: ***QUESTION 2:*** If I switch from 13 string properties to 1 StringListProperty, will query performance be adversely affected; my current filter looks like: ``` query.filter('location_geocell_%d =' % len(search_cell), search_cell) ``` *and the new filter would look like:* ``` query.filter('location_geocells =', search_cell) ``` *Note that the first query has a search space of \_n\_ entities, whereas the second query has a search space of \_13n\_ entities.* It seems like the answer to (2) is that both result in equal query performance, per tip #6 in [this blog post](http://googleappengine.blogspot.com/2009/06/10-things-you-probably-didnt-know-about.html), but again, I'd like to see if anyone has any differing real-world experiences with this. Lastly, if anyone has any other suggestions or tips that can help improve storage utilization, query performance and/or ease of use (specifically w.r.t. index.yaml), please do let me know! The source can be found here [geomodel](http://code.google.com/p/geomodel) & [geomodel.py](http://code.google.com/p/geomodel/source/browse/trunk/geo/geomodel.py)
You're correct that there's no significant overhead per-index - 13n entries in one index is more or less equivalent to n entries in 13 indexes. There's a total index count limit of 100, though, so this eats up a fair chunk of your available indexes. That said, using a ListProperty is definitely a far superior approach from usability and index consumption perspectives. There is, as you supposed, no performance difference between querying a small index and a much larger index, supposing both queries return the same number of rows. The only reason I can think of for using separate properties is if you knew you only needed to index on certain levels of detail - but that could be accomplished better at insert-time by specifying the levels of detail you want added to the list in the first place. Note that in either case you only need the indexes if you intend to query the geocell properties in conjunction with a sort order or inequality filter, though - in all other cases, the automatic indexing will suffice.
> > Lastly, if anyone has any other suggestions or tips that can help improve storage utilization, query performance and/or ease of use The StringListproperty is the way to go for the reasons mentioned above, but in actual usage one might want to add the geocells to ones own previously existing StringList so one could query against multiple properties. So, if you were to provide a lower level api it could work with full text search implementations like [bill katz's](http://www.billkatz.com/2009/6/Simple-Full-Text-Search-for-App-Engine) ``` def point2StringList(Point, stub="blah"): ..... return ["blah_1:a", "blah_2":"a3", "blah_3":"a3f" ....] def boundingbox2Wheresnippet(Box, stringlist="words", stub="blah"): ..... return "words='%s_3:a3f' AND words='%s_3:b4g' ..." %(stub) etc. ```
App Engine: 13 StringPropertys vs. 1 StringListProperty (w.r.t. indexing/storage and query performance)
[ "", "python", "google-app-engine", "google-cloud-datastore", "" ]
The following bits of code do not seem to be searching the entire routine definition. Code block 1: ``` select top 50 * from information_schema.routines where routine_definition like '%09/01/2008%' and specific_Name like '%NET' ``` Code Block 2: ``` SELECT ROUTINE_NAME, ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_DEFINITION LIKE '%EffectiveDate%' AND ROUTINE_TYPE='PROCEDURE' and ROUTINE_NAME like '%NET' ``` I know for a fact that these bits of SQL work under most circumstances. The problem is this: When I run this for "EffectiveDate" which is buried at line ~800 in a few stored procedures, these stored procedures never show up in the results. It's as if "like" only searches so deep. Any tips on fixing this? I want to search the ENTIRE stored procedure for the specified text. Thanks!
``` select * FROM INFORMATION_SCHEMA.ROUTINES WHERE OBJECTPROPERTY(OBJECT_ID(SPECIFIC_NAME),'IsMSShipped') =0 and OBJECT_DEFINITION(OBJECT_ID(SPECIFIC_NAME)) like '%EffectiveDate%' AND ROUTINE_TYPE='PROCEDURE' AND ROUTINE_NAME like '%NET' ``` Use the object definition instead.
Just to clarify why the [procedure text is truncated](http://msdn.microsoft.com/en-us/library/ms188757.aspx): > **ROUTINE\_DEFINITION nvarchar(4000)** > > Returns **the first 4000 characters** of > the definition text of the function or > stored procedure if the function or > stored procedure is not encrypted. > Otherwise, returns NULL. > > To ensure that you obtain the complete > definition, query the > `OBJECT_DEFINITION` function or the > definition column in the > `sys.sql_modules` catalog view.
SQL 2005 - Search stored procedures for text (Not all text is being searched)
[ "", "sql", "sql-server", "sql-server-2005", "sql-server-2008", "stored-procedures", "" ]
I want to use the following regular expression which is written within a C# .NET code, in a Java code, but I can't seem to convert it right, can you help me out? ``` Regex(@"\w+:\/\/(?<Domain>[\x21-\x22\x24-\x2E\x30-\x3A\x40-\x5A\x5F\x61-\x7A]+)(?<Relative>/?\S*)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline); ```
The most direct translation would be: ``` Pattern p = Pattern.compile( "\\w+://([\\x21-\\x22\\x24-\\x2E\\x30-\\x3A\\x40-\\x5A\\x5F\\x61-\\x7A]+)(/?\\S*)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); ``` Java has no equivalent for C#'s verbatim strings, so you always have to escape backslashes. And Java's regexes don't support named groups, so I converted those to simple capturing groups (named groups are due to be added in Java 7). But there are a few problems with the original regex: * The `RegexOptions.Compiled` modifier doesn't do what you probably think it does. Specifically, it's not related to Java's `compile()` method; that's just a factory method, roughly equivalent to C#'s `new Regex()` constructor. The `Compiled` modifier causes the regex to be compiled *to CIL bytecode*, which can make it match a lot faster, but at a considerable cost in upfront processing and memory use--and that memory never gets garbage-collected. If you don't use the regex a lot, the `Compiled` option is probably doing more harm than good, performance-wise. * The `IgnoreCase/CASE_INSENSITIVE` modifier is pointless since your regex always matches both upper- and lowercase variants wherever it matches letters. * The `Singleline/DOTALL` modifier is pointless since you never use the dot metacharacter. * In .NET regexes, the character-class shorthand `\w` is Unicode-aware, equivalent to `[\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}]`. In Java it's ASCII-only -- `[A-Za-z0-9_]`-- which seems to be more in line with the way you're using it (you could "dumb it down" in .NET by using the `RegexOptions.ECMAScript` modifier). So the actual translation would be more like this: ``` Pattern p = Pattern.compile("\\w+://([\\w!\"$.:@]+)(?:/(\\S*))?"); ```
Java does not have the @ string notation. So, make sure you escape all the '\' in your regexp. `(\w+ becomes> \\w+, \/ becomes> \\/, \x21 becomes> \\x21, etc. )`
How do I convert a regular expression in a valid .NET format to valid Java format?
[ "", "java", ".net", "regex", "" ]
I'm developing an application that needs to perform some processing on the user's Outlook contacts. I'm currently accessing the list of Outlook contacts by iterating over the result of `MAPIFolder.Items.Restrict(somefilter)`, which can be found in `Microsoft.Office.Interop.Outlook`. In my application, my user needs to choose several contacts to apply a certain operation on. I would like to add a feature that will allow the user to drag a contact from Outlook and drop it on a certain ListBox in the UI (I work in WPF but this is probably is more generic issue). I'm very new to C# and WPF - how can I: 1. Receive a dropped item on a ListBox 2. Verify it's a ContactItem (or something that wraps ContactItem) 3. Cast the dropped item to a ContactItem so I can process it Thanks
I tried this with a TextBox (no difference with a ListBox in practice). Summary : Searching in all outlook contacts for the one recieved dragged as text. The search here is based on the person's FullName. condition(s): When you drag a contact, it must show the FullName when selected in outlook. The only catch is when two persons have the same full names!! If it's the case you can try to find a unique identifier for a person by combining ContactItem properties and searching them in the dragged text. ``` private void textBox1_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetData("Text") != null) { ApplicationClass app; MAPIFolder mapif; string contactStr; contactStr = e.Data.GetData("Text").ToString(); app = new ApplicationClass(); mapif = app.GetNamespace("MAPI").GetDefaultFolder(OlDefaultFolders.olFolderContacts); foreach (ContactItem tci in mapif.Items) { if (contactStr.Contains(tci.FullName)) { draggedContact = tci; //draggedContact is a global variable for example or a property... break; } } mapif = null; app.Quit; app = null; GC.Collect(); } } ``` of course this code is to be organized-optimized, it's only to explain the method used. You can try using the Explorer.Selection property combined with GetData("Text") [to ensure it's coming from Outlook, or you can use GetData("Object Descriptor") in the DragOver Event, decode the memory stream, search for "outlook", if not found cancel the drag operation] And why not drag multiple contacts! ``` private void textBox1_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetData("Text") != null) { ApplicationClass app; Explorer exp; List<ContactItem> draggedContacts; string contactStr; contactStr = e.Data.GetData("Text").ToString(); draggedContacts = new List<ContactItem>(); app = new ApplicationClass(); exp = app.ActiveExplorer(); if (exp.CurrentFolder.DefaultItemType == OlItemType.olContactItem) { if (exp.Selection != null) { foreach (ContactItem ci in exp.Selection) { if (contactStr.Contains(ci.FullName)) { draggedContacts.Add(ci); } } } } app = null; GC.Collect(); } } ```
An Outlook contact, when dropped, supports the following formats: ``` (0): "RenPrivateSourceFolder" (1): "RenPrivateMessages" (2): "FileGroupDescriptor" (3): "FileGroupDescriptorW" (4): "FileContents" (5): "Object Descriptor" (6): "System.String" (7): "UnicodeText" (8): "Text" ``` The most interesting looking one on that list (for me) is Object Descriptor, which then led me to someone with a similar sounding problem: <http://bytes.com/topic/visual-basic-net/answers/527320-drag-drop-outlook-vb-net-richtextbox> Where it looks like in that case, they detect that it's an Outlook drop, and then use the Outlook object model to detect what's currently selected, with the implication that that must be the current drop source.
Receiving (dragged and) dropped Outlook contacts in C#?
[ "", "c#", "wpf", "outlook", "contactitem", "" ]
I am trying to build an app that uses a COM component in VisualStudio ´05 in native C++. The mix of native and managed desciptions of things in the MSDN totally wrecked my brain. (I think the MSDN is a total mess in that respect) I need a short and simple native C++ sample of code to load my Component and make it usable. I am ok with the compiler creating wrappers and the like. Please don't advise me to use the dialog based MFC example, because it does not work with this component and is in itself a huge pile of c... code. Can this be an issue native com vs managed com? I am totally lost, please give me some bearings... EDIT: Thanks for all the help. My problem is that all I have is a registered dll (actually the OCX, see below) . I (personally) know what the Interface should look like, but how do I tell my program? There are no headers that define IDs for Interfaces that I could use. But I read that the c++ compiler can extract and wrap it up for me. Anyone know how this is done? CLARIFICATION: I have only the OCX and a clue from the documentation of the component, what methods it should expose.
Fully working example (exactly what you need) from my blog article: [How to Call COM Object from Visual Studio C++?](https://helloacm.com/how-to-call-com-object-from-visual-studio-c/) ``` // https://helloacm.com/how-to-call-com-object-from-visual-studio-c/ #include <iostream> #include <objbase.h> #include <unknwn.h> #include <Propvarutil.h> #import "wshom.ocx" no_namespace, raw_interfaces_only using namespace std; int main() { HRESULT hr; CLSID clsid; CoInitializeEx(nullptr, COINIT_MULTITHREADED); CLSIDFromProgID(OLESTR("WScript.Shell"), &clsid); IWshShell *pApp = nullptr; hr = CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWshShell), reinterpret_cast<LPVOID *>(&pApp)); if (FAILED(hr) || pApp == nullptr) { throw "Cannot Create COM Object"; } int out; VARIANT s; InitVariantFromInt32(0, &s); VARIANT title; InitVariantFromString(PCWSTR(L"title"), &title); VARIANT type; InitVariantFromInt32(4096, &type); BSTR msg = ::SysAllocString(L"Hello from https://helloacm.com"); pApp->Popup(msg, &s, &title, &type, &out); CoUninitialize(); cout << "Out = " << out; return 0; } ```
I applaud your efforts to go with native C++ to deal with COM - you need to go through the pain to truly appreciate today's luxurious (managed) development environment :) Back when the world (and I) were younger, Kraig Brockshmidt's book "[Inside OLE](https://rads.stackoverflow.com/amzn/click/com/1556158432)" was **the** tome for making sense of COM (before COM even was COM). This book predates managed code, so no chance of managed confusion here. There's a second edition, too. Don Box's books "[Essential COM](https://rads.stackoverflow.com/amzn/click/com/0201634465)" and "[Effective COM](https://rads.stackoverflow.com/amzn/click/com/0201379686)" were later, but welcome additions to the store of (unmanaged) COM knowledge. However, if your wallet doesn't extend to acquiring these dusty old books, the Microsoft COM tutorial material [here](http://msdn.microsoft.com/en-us/library/aa263810(VS.60).aspx) could help set you on the right track. Happy hacking.
How can I easily use a COM component in Native Visual C++
[ "", "c++", "visual-c++", "com", "activex", "" ]
I'm currently working on a game engine written in pygame and I wanted to add OpenGL support. I wrote a test to see how to make pygame and OpenGL work together, and when it's running in windowed mode, it runs between 150 and 200 fps. When I run it full screen (all I did was add the FULLSCREEN flag when I set up the window), it drops down to 60 fps. I added a lot more drawing functions to see if it was just a huge performance drop, but it always ran at 60 fps. Is there something extra I need to do to tell OpenGL that it's running fullscreen or is this a limitation of OpenGL? (I am running in Windows XP)
As frou pointed out, this would be due to Pygame waiting for the vertical retrace when you update the screen by calling `display.flip()`. As the [Pygame `display` documentation](http://www.pygame.org/docs/ref/display.html#pygame.display.flip) notes, if you set the display mode using the `HWSURFACE` or the `DOUBLEBUF` flags, `display.flip()` will wait for the vertical retrace before swapping buffers. To be honest, I don't see any good reason (aside from benchmarking) to try to achieve a frame rate that's faster than the screen's refresh rate. You (and the people playing your game) won't be able to notice any difference in speed or performance, since the display can only draw 60 fps anyways. Plus, if you don't sync with the vertical retrace, there's a good chance that you'll get [screen tearing](http://en.wikipedia.org/wiki/Screen_tearing).
Is this a [V-Sync](http://en.wikipedia.org/wiki/V-sync) issue? Something about the config or your environment may be limiting maximum frame rate to your monitor's refresh rate.
PyOpenGL + Pygame capped to 60 FPS in Fullscreen
[ "", "python", "fullscreen", "pygame", "pyopengl", "" ]
I was just viewing stackoverflow page source and I have a few simple questions; **1)** What is the purpose of this? DO search engines see this or something else? ``` <link rel="search" type="application/opensearchdescription+xml" title="Stack Overflow" href="/opensearch.xml"> ``` **2)** ?v=3731 Why is this added to the end of some javascript and stylesheet files, is it to prevent the browser from caching these items? And if I am correct, then why would you not want this, I would think they wouldn't change often ``` <script type="text/javascript" src="/content/js/master.js?v=3731"></script> ``` **3)** What kind of file is this rel="canonical" ``` <link rel="canonical" href="http://stackoverflow.com/questions/1180651/php-array-and-foreach"> ``` **4)** What is this, my guess is maybe if you put in the page URL into something like google reader it would find this file maybe? ``` <link rel="alternate" type="application/atom+xml" title="Feed for question 'php array and `foreach?'" href="/feeds/question/1180651">` ```
1. This is to enable a site to be used as a built in search within a browser. Similar to the way wikipedia can be used from the top right search bar in firefox. More info can be found [here](http://www.opensearch.org/Documentation/Developer_how_to_guide) 2. This is to make use of browser caching, which is likely to be aggressively set with the content headers. By appending v=?, it ensures that the latest js file is used when a revision is made. 3. Canonical is used to specify the preferred version of a url, if that content is duplicated elsewhere. 4. Yes this is used to indicate that the url can serve an rss/atom feed that can be fed through a reader such as google reader.
number 4 is so that when you go to a page in FF or IE7+ the little RSS icon at the top of your browser lights up and you can add that feed to the browser's built-in feed reader
Please help me understand a few things found in the SO page source
[ "", "javascript", "html", "" ]
In hopes of trying to avoid future memory leaks in php programs (drupal modules, etc.) I've been messing around with simple php scripts that leak memory. Could a php expert help me find what about this script causes the memory usage to continually climb? Try running it yourself, changing various parameters. The results are interesting. Here it is: ``` <?php function memstat() { print "current memory usage: ". memory_get_usage() . "\n"; } function waste_lots_of_memory($iters) { $i = 0; $object = new StdClass; for (;$i < $iters; $i++) { $object->{"member_" . $i} = array("blah blah blha" => 12345); $object->{"membersonly_" . $i} = new StdClass; $object->{"onlymember"} = array("blah blah blha" => 12345); } unset($object); } function waste_a_little_less_memory($iters) { $i = 0; $object = new StdClass; for (;$i < $iters; $i++) { $object->{"member_" . $i} = array("blah blah blha" => 12345); $object->{"membersonly_" . $i} = new StdClass; $object->{"onlymember"} = array("blah blah blha" => 12345); unset($object->{"membersonly_". $i}); unset($object->{"member_" . $i}); unset($object->{"onlymember"}); } unset($object); } memstat(); waste_a_little_less_memory(1000000); memstat(); waste_lots_of_memory(10000); memstat(); ``` For me, the output is: ``` current memory usage: 73308 current memory usage: 74996 current memory usage: 506676 ``` [edited to unset more object members]
[`unset()`](http://www.php.net/manual/en/function.unset.php) doesn't free the memory used by a variable. The memory is freed when the "garbage collector" (in quotes since PHP didn't have a real garbage collector before version 5.3.0, just a memory free routine which worked mostly on primitives) sees fit. Also, technically, you shouldn't need to call [`unset()`](http://www.php.net/manual/en/function.unset.php) since the `$object` variable is limited to the scope of your function. Here is a script to demonstrate the difference. I modified your `memstat()` function to show the memory difference since the last call. ``` <?php function memdiff() { static $int = null; $current = memory_get_usage(); if ($int === null) { $int = $current; } else { print ($current - $int) . "\n"; $int = $current; } } function object_no_unset($iters) { $i = 0; $object = new StdClass; for (;$i < $iters; $i++) { $object->{"member_" . $i}= array("blah blah blha" => 12345); $object->{"membersonly_" . $i}= new StdClass; $object->{"onlymember"}= array("blah blah blha" => 12345); } } function object_parent_unset($iters) { $i = 0; $object = new StdClass; for (;$i < $iters; $i++) { $object->{"member_" . $i}= array("blah blah blha" => 12345); $object->{"membersonly_" . $i}= new StdClass; $object->{"onlymember"}= array("blah blah blha" => 12345); } unset ($object); } function object_item_unset($iters) { $i = 0; $object = new StdClass; for (;$i < $iters; $i++) { $object->{"member_" . $i}= array("blah blah blha" => 12345); $object->{"membersonly_" . $i}= new StdClass; $object->{"onlymember"}= array("blah blah blha" => 12345); unset ($object->{"membersonly_" . $i}); unset ($object->{"member_" . $i}); unset ($object->{"onlymember"}); } unset ($object); } function array_no_unset($iters) { $i = 0; $object = array(); for (;$i < $iters; $i++) { $object["member_" . $i] = array("blah blah blha" => 12345); $object["membersonly_" . $i] = new StdClass; $object["onlymember"] = array("blah blah blha" => 12345); } } function array_parent_unset($iters) { $i = 0; $object = array(); for (;$i < $iters; $i++) { $object["member_" . $i] = array("blah blah blha" => 12345); $object["membersonly_" . $i] = new StdClass; $object["onlymember"] = array("blah blah blha" => 12345); } unset ($object); } function array_item_unset($iters) { $i = 0; $object = array(); for (;$i < $iters; $i++) { $object["member_" . $i] = array("blah blah blha" => 12345); $object["membersonly_" . $i] = new StdClass; $object["onlymember"] = array("blah blah blha" => 12345); unset ($object["membersonly_" . $i]); unset ($object["member_" . $i]); unset ($object["onlymember"]); } unset ($object); } $iterations = 100000; memdiff(); // Get initial memory usage object_item_unset ($iterations); memdiff(); object_parent_unset ($iterations); memdiff(); object_no_unset ($iterations); memdiff(); array_item_unset ($iterations); memdiff(); array_parent_unset ($iterations); memdiff(); array_no_unset ($iterations); memdiff(); ?> ``` If you are using objects, make sure the classes implements [`__unset()`](http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members) in order to allow [`unset()`](http://www.php.net/manual/en/function.unset.php) to properly clear resources. Try to avoid as much as possible the use of variable structure classes such as `stdClass` or assigning values to members which are not located in your class template as memory assigned to those are usually not cleared properly. PHP 5.3.0 and up has a better garbage collector but it is disabled by default. To enable it, you must call [`gc_enable()`](http://www.php.net/manual/en/function.gc-enable.php) once.
`memory_get_usage()` "*Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.*" That's the amount of memory allocated to the process by the OS, *not* the amount of memory used by assigned variables. PHP does not always release memory back to the OS -- but that memory can still be re-used when new variables are allocated. Demonstrating this is simple. Change the end of your script to: ``` memstat(); waste_lots_of_memory(10000); memstat(); waste_lots_of_memory(10000); memstat(); ``` Now, if you're correct, and PHP is actually leaking memory, you should see memory useage grow twice. However, here's the actual result: ``` current memory usage: 88272 current memory usage: 955792 current memory usage: 955808 ``` This is because memory "freed" after the initial invocation of waste\_lots\_of\_memory() is re-used by the second invocation. In my 5 years with PHP, I've written scripts that have processed millions of objects and gigabytes of data over a period of hours, and scripts that have run for months at a time. PHP's memory management isn't great, but it's not nearly as bad as you're making it out to be.
Why does this simple php script leak memory?
[ "", "php", "memory", "" ]
I'm kind of wondering about this, if you create a texture in memory in DirectX with the CreateTexture function: ``` HRESULT CreateTexture( UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture9** ppTexture, HANDLE* pSharedHandle ); ``` ...and pass in `D3DFMT_UNKNOWN` format what is supposed to happen exactly? If I try to get the surface of the first or second level will it cause an error? Can it fail? Will the graphics device just choose a random format of its choosing? Could this cause problems between different graphics card models/brands?
I just tried it out and it does not fail, mostly When `Usage` is set to `D3DUSAGE_RENDERTARGET` or `D3DUSAGE_DYNAMIC`, it consistently came out as `D3DFMT_A8R8G8B8`, no matter what I did to the back buffer format or other settings. I don't know if that has to do with my graphics card or not. My guess is that specifying unknown means, "pick for me", and that the 32-bit format is easiest for my card. When the usage was `D3DUSAGE_DEPTHSTENCIL`, it failed consistently. So my best conclusion is that specifying `D3DFMT_UNKNOWN` as the format gives DirectX the choice of what it should be. Or perhaps it always just defaults to `D3DFMT_A8R8G8B`. Sadly, I can't confirm any of this in any documentation anywhere. :|
[MSDN](http://msdn.microsoft.com/en-us/library/bb174363%28VS.85%29.aspx) doesn't say. But I'm pretty sure you'd get "D3DERR\_INVALIDCALL" as a result. > If the method succeeds, the return > value is D3D\_OK. If the method fails, > the return value can be one of the > following: D3DERR\_INVALIDCALL, > D3DERR\_OUTOFVIDEOMEMORY, > E\_OUTOFMEMORY.
Passing D3DFMT_UNKNOWN into IDirect3DDevice9::CreateTexture()
[ "", "c++", "directx", "textures", "" ]
I've been using the YUI Test framework to do TDD with JavaScript but the default TestLogger shows all sorts of messages, not just the FAIL ones. This makes scanning the log for failures an exercise in tedium, or you have to play whack-a-mole on the filter checkboxes. Is there any way to make the toggle switches on the logger window stay the same between page refreshes? Or have the Logger only show the tests that have failed? You can see in [this example](http://developer.yahoo.com/yui/examples/yuitest/yt-advanced-test-options.html) that the PASS and INFO dominate when you have several tests and it is too easy to miss the FAIL messages. [YUI Test Logger screenshot http://img24.imageshack.us/img24/935/yuitest.png](http://img24.imageshack.us/img24/935/yuitest.png) I've looked at the [API for the TestLogger](http://developer.yahoo.com/yui/docs/YAHOO.tool.TestLogger.html), which hints at there being some options. Sadly the options are not described at all. I only use YUI for this feature so I'm not an expert in the API, so can anyone lend me a hand?
To filter a category in YUI 2.7 and prior, Logger must have received a message from that category before the request to hide. That means you can do ``` YAHOO.log('','pass','TestRunner'); var logger = new YAHOO.widget.LogReader(el,conf); logger.hideCategory('pass'); ``` FWIW, pre-filtering is available in YUI 3 with [Console + ConsoleFilters plugin](http://developer.yahoo.com/yui/3/console-filters/#config). I would recommend you add a feature request on yuilibrary.com at <http://yuilibrary.com/projects/yui2/newticket>
My solution for YUI3 <http://gist.github.com/309910>
Making the YUI TestLogger show only tests that fail?
[ "", "javascript", "unit-testing", "yui", "" ]
How can I execute some code when my process is going to exit? I've tried this: ``` public static void Main(string[] args) { StartUpMyServer(); AppDomain.CurrentDomain.ProcessExit += delegate(object sender, EventArgs e) { Console.WriteLine("process exiting!"); TellMyServerToStopAcceptingConnectionsAndWaitUntilItsFinishedWithAnyExistingOnes(); }; Thread.Sleep(Timeout.Infinite); } ``` "process exiting" is never printed and nothing else seems to happen. Whatever it is, it needs to be cross-platform (Mono/Linux/OS X/Windows). Thanks! **Clarification:** I could probably accomplish what I want to do by starting and stopping the server on a separate thread and polling a 'stop requested' flag (which would be set in the ProcessExit event hander) on the main thread every X ms. I'd like to avoid this solution if possible (extra thread, cpu cycles). I just want to main thread to suspend until such time as the process is exiting, when it should tell the server to stop. Possible?
I have encountered a similar problem. Where I work, we have a set of libraries that get used by every client-side application we write, which contains cleanup code that needs to be executed upon application exit. AppDomain.CurrentDomain.ProcessExit works great for us, and we have to use that method because we can't rely on the top-level application (running Program.Main) to explicitly call our cleanup method, nor do we have any control over that (since it's not our code, it belongs to the user using our libraries). However... in your situation, I don't think you need to worry about a ProcessExit event to fire your cleanup code. You're writing some sort of network server, hosted in a console application. How about: ``` public static void Main(string[] args) { StartUpMyServer(); Console.WriteLine("Press the ESCAPE key to shut down the server."); while (Console.ReadKey(true).Key != ConsoleKey.Escape); ShutDownMyServer(); } ``` Then when the user presses ESCAPE, your server will be shut down. The really elegant way to do this for a networked server would be to create a Windows service, which will give you handy OnStart() and OnStop() methods, where you just include your appropriate start-up and shut-down code, and the Windows service manager handles calling those for you. Ultimately, the real problem is ensuring that you're not sleeping forever... you need some way to signal your application to exit. There are many ways to do it, it all depends on how you're intending your app to run.
Your Thread.Sleep is blocking. You will have to think of a better idea. Without knowledge how your server runs, I cant help.
C# - Pause main thread and clean up before process exit
[ "", "c#", "mono", "" ]
I've been writing Java web (JSF, Struts, JSR168) apps for a number of years. With the recent departure of a colleague, it looks like I'm going to be building more client applications. I've used Eclipse since the beginning and I'm really comfortable with it. It feels as though SWT is waning (just an opinion based on literature I can find) and Swing is surging. My question: Is there value in learning Swing through writing apps by hand in Eclipse (as opposed to using Matisse in Netbeans)?
Yes, it is very valuable to learn coding Swing apps by hand. One reason for this is that no GUI-Designer I know always does the things you want them to do. The other - and in my opinion more important reason - is that most GUI builders (especially NetBeans') generate all and everything into one single class. This can be very annoying because the maintainability is reduced a lot (separation of concerns). Also many GUI builders have blocked regions, i.e. you cannot modify the generated code by hand. Or if you do the GUI builder will overwrite it the next time you use it. However that standard LayoutManagers coming with Swing are very complicated. This is why I suggest that you give [MigLayout](http://www.miglayout.com) or [JGoodies FormLayout](http://www.jgoodies.com) a try. On the JGoodies site you also find other libs for alternative Look&Feels, Binding and Validation, which can be very useful. I would also suggest that you have a look at the [Presentation Model pattern (Martin Fowler)](http://www.martinfowler.com/eaaDev/PresentationModel.html), which helps a lot if you want to unit-test your GUI-behaviour. If you then are motivated to improve the design and add some very cool effects to your application check out the book [Filthy Rich Clients](http://filthyrichclients.org/). Hope it helps.
Yes, definitely - even if you plan on using Matisse most of the time, you will benefit from having at least a reasonable understanding of the Swing code under the hood.
Java developer moving into Java Desktop development
[ "", "java", "swing", "swt", "desktop", "" ]
for our latest project we used Django, where one can specify a list of folders, that are searched for a template, say, with name `example.html`. Now, we switched back to [Smarty](http://smarty.net/) (PHP) and are wondering, if there is something similar. Smarty version: Can be cutting-edge. Behaviour: 1. Feed Smarty with an array of folders. 2. Call a template either with `$smarty->display()` or `{include}`. 3. Smarty searches through the folders and takes the first template matching the name. I looked at [Smarty resources](http://smarty.net/manual/en/template.resources.php), but they look like overkill for this task, and the docs are a bit sparse on this topic. Any ideas how this could be done? *An additional problem* is, that the list of folders may change depending on the requested URL. Any ideas how to tell Smarty, which compiled template to use? Cheers,
In Smarty.class.php, in the method `Smarty::_parse_resource_name()` : ``` foreach ((array)$params['resource_base_path'] as $_curr_path) { $_fullpath = $_curr_path . DIRECTORY_SEPARATOR . $params['resource_name']; if (file_exists($_fullpath) && is_file($_fullpath)) { $params['resource_name'] = $_fullpath; return true; } // didn't find the file, try include_path $_params = array('file_path' => $_fullpath); require_once(SMARTY_CORE_DIR . 'core.get_include_path.php'); if(smarty_core_get_include_path($_params, $this)) { $params['resource_name'] = $_params['new_file_path']; return true; } } ``` `$params['resource_base_path']` is defaulted to `$this->template_dir` in `Smarty::_fetch_resource_info()`. So it looks like you can set `$smarty->template_dir` to an array of directories to look in. Note that this won't be recursive. This must be an undocumented feature.
I know its been a while since this question was asked, but for the record I wanted to point out a feature of Smarty that I think does what the OP is asking. Below is a portion of the code from my app. Basically what it does is first look for the template in `/ext/templates`. If it does not find it there, it will use the one from `/base/templates`. My code only requires a single fallback, but more could easily be added. ``` class View extends Smarty { function __construct() { parent::Smarty(); $this->template_dir = LOCAL_APP_ROOT.'/ext/templates'; $this->compile_dir = LOCAL_APP_ROOT.'/cache/compile'; $this->default_template_handler_func = '__default_template_handler'; } } function __default_template_handler($resource_type, $resource_name, &$template_source, &$template_timestamp, &$smarty_obj) { if ($resource_type == 'file') { if (!is_readable($resource_name)) { $defaultPath = LOCAL_APP_ROOT."/base/templates/$resource_name"; if (file_exists($defaultPath)) { $template_source = file_get_contents($defaultPath); $template_timestamp = filemtime($defaultPath); return true; } } } return false; } ```
PHP, Smarty: Check for template in different folders
[ "", "php", "templates", "smarty", "" ]
The BackgroundWorker object allows us to pass a single argument into the DoWorkEventHandler. ``` // setup/init: BackgroundWorker endCallWorker = new BackgroundWorker(); endCallWorker.DoWork += new DoWorkEventHandler(EndCallWorker_DoWork); ... endCallWorker.RunWorkerAsync(userName); // the handler: private void EndCallWorker_DoWork(object sender, DoWorkEventArgs e) { string userName = e.Argument as string; ... } ``` To pass multiple arguments, I must wrap them in an object, like this poor string array: ``` // setup/init: BackgroundWorker startCallWorker = new BackgroundWorker(); startCallWorker.DoWork += new DoWorkEventHandler(StartCallWorker_DoWork); ... startCallWorker.RunWorkerAsync(new string[]{userName, targetNumber}); // the handler: private void StartCallWorker_DoWork(object sender, DoWorkEventArgs e) { string[] args = e.Argument as string[]; string userName = args[0]; string targetNumber = args[1]; } ``` Is there another object or pattern that allows us pass multiple arguments nicely, or ideally, write our own signature?
You could use a closure (Lambda): ``` backgroundWorker.DoWork += (s, e) => MyWorkMethod(userName, targetNumber); ``` Or with delegate (anonymous method) syntax: ``` backgroundWorker.DoWork += delegate(object sender, DoWorkEventArgs e) { MyWorkMethod(userName, targetNumber); }; ```
What's wrong with using a typed object? ``` internal class UserArgs { internal string UserName { get; set; } internal string TargetNumber { get; set; } } var args = new UserArgs() {UserName="Me", TargetNumber="123" }; startCallWorker.RunWorkerAsync(args); ```
Alternative to BackgroundWorker that accepts more than one argument?
[ "", "c#", ".net", "multithreading", "asynchronous", "backgroundworker", "" ]
I was implementing a on-demand script controller based on jquery's getscript, it looks like this: ``` function controller = function(){ var script = function(){ var scripts = {}; return { load: function(jsurl){ $.getScript(jsurl, null); }, run: function(js){ window[js].apply(this,null); } } }; return { script: script() }; } var ctlr = controller(); ``` then here is a remote script with a function to be loaded - remote.js ``` function remotefunc(){ alert( 'remotefunc invoked' ); } ``` and here is how the whole thing supposed to work, in the main script: ``` ctlr.script.load( 'remote.js' ); // remote script successfully loaded ctlr.script.run( 'remotefunc' ); // got an error, window['remotefunc'] undefined ``` but as you can see, 'remotefunc' is defined in the global 'window' scope, so the window object is supposed to be able to 'see' it. I thought the problem was probably the closure stuff in the 'controller' definition, so I did a direct $.getScirpt without using the 'controller': ``` $.getScript( 'http://path/to/remote.js', function(){ window['remotefunc'].apply( this, null ); // this worked } ); ``` strange. So it is about the 'controller' implementation(I kind need it)! Anybody can help me out with this? How to fix the 'controller' implementation so the ``` window[js].apply(this,null); ``` can actually work? Thanx.
When using something like `getSript`, it's important to remember that it is fetching **asynchronously**. Meaning, the browser fires off the request and while that's happening, code after that line executes without pause. jQuery provides a callback function parameter to get script that allows you to do something after the asynchronous fetch is finished. Try this: ``` var script = function(){ var scripts = {}; return { load: function(jsurl, callback){ $.getScript(jsurl, callback); }, run: function(js){ window[js].apply(this,null); } } }; ``` Then, when using it: ``` ctlr.load( 'remote.js', function(){ // remote script successfully loaded ctlr.run( 'remotefunc' ); }); ```
The reason it's telling you window['remotefunc'] is undefined is because you are not giving it time to actually download and execute the remote script before attempting to call a function defined in it. The remote script is loaded asynchronously, which means the script execution isn't paused while waiting for a response. You will need to either re-implement the getScript method to be synchronous or somehow work your class around the fact that the function will not be available in any determinate amount of time. EDIT: Just found another possible solution, try calling this before your request ``` $.ajaxSetup({async: false}); ``` This will make the getScript method synchronous
how to invoke a dynamically loaded javascript function
[ "", "javascript", "jquery", "scope", "closures", "" ]
I wish to embed a very light HTTP server in my Java Swing app which just accepts requests, performs some actions, and returns the results. Is there a very light Java class that I can use in my app which listens on a specified port for HTTP requests and lets me handle requests? Note, that I am not looking for a stand-alone HTTP server, just a small Java class which I can use in my app.
Since Java 6, the JDK contains a simple [HTTP server](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.httpserver/com/sun/net/httpserver/HttpServer.html) implementation. [Example usage:](http://www.java2s.com/Code/Java/JDK-6/LightweightHTTPServer.htm) ``` import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.Executors; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; public class HttpServerDemo { public static void main(String[] args) throws IOException { InetSocketAddress addr = new InetSocketAddress(8080); HttpServer server = HttpServer.create(addr, 0); server.createContext("/", new MyHandler()); server.setExecutor(Executors.newCachedThreadPool()); server.start(); System.out.println("Server is listening on port 8080" ); } } class MyHandler implements HttpHandler { public void handle(HttpExchange exchange) throws IOException { String requestMethod = exchange.getRequestMethod(); if (requestMethod.equalsIgnoreCase("GET")) { Headers responseHeaders = exchange.getResponseHeaders(); responseHeaders.set("Content-Type", "text/plain"); exchange.sendResponseHeaders(200, 0); OutputStream responseBody = exchange.getResponseBody(); Headers requestHeaders = exchange.getRequestHeaders(); Set<String> keySet = requestHeaders.keySet(); Iterator<String> iter = keySet.iterator(); while (iter.hasNext()) { String key = iter.next(); List values = requestHeaders.get(key); String s = key + " = " + values.toString() + "\n"; responseBody.write(s.getBytes()); } responseBody.close(); } } } ``` Or you can use [Jetty](https://www.eclipse.org/jetty/) for that purpose. It’s quite lightweight and perfectly fits this purpose.
You can use jetty as embedded server, its fairly light weight. Other option is check this out for a simple java class to handle http requests <http://java.sun.com/developer/technicalArticles/Networking/Webserver/>. Other way is in Java 6 you can use com.sun.net.httpserver.HttpServer
Java class for embedded HTTP server in Swing app
[ "", "java", "httpserver", "" ]
I am trying to increment a number by a given value each second and retain the formatting using JavaScript or JQuery I am struggling to do it. Say I have a number like so: > 1412015 the number which this can be incremented by each second is variable it could be anything beween 0.1 and 2. Is it possible, if the value which it has to be incremented by each second is 0.54 to incremenet the number and have the following output: > 1,412,016 > 1,412,017 > 1,412,018 Thanks Eef
I'm not quite sure I understand your incrementation case and what you want to show. However, I decided to chime in on a solution to format a number. I've got two versions of a number format routine, one which parses an array, and one which formats with a regular expression. I'll admit they aren't the easiest to read, but I had fun coming up with the approach. I've tried to describe the lines with comments in case you're curious **Array parsing version:** ``` function formatNum(num) { //Convert a formatted number to a normal number and split off any //decimal places if they exist var parts = String( num ).replace(/[^\d.]-/g,'').split('.'); //turn the string into a character array and reverse var arr = parts[0].split('').reverse(); //initialize the return value var str = ''; //As long as the array still has data to process (arr.length is //anything but 0) //Use a for loop so that it keeps count of the characters for me for( var i = 0; arr.length; i++ ) { //every 4th character that isn't a minus sign add a comma before //we add the character if( i && i%3 == 0 && arr[0] != '-' ) { str = ',' + str ; } //add the character to the result str = arr.shift() + str ; } //return the final result appending the previously split decimal place //if necessary return str + ( parts[1] ? '.'+parts[1] : '' ); } ``` **Regular Expression version:** ``` function formatNum(num) { //Turn a formatted number into a normal number and separate the //decimal places var parts = String( num ).replace(/[^\d.]-/g,'').split('.'); //reverse the string var str = parts[0].split('').reverse().join(''); //initialize the return value var retVal = ''; //This gets complicated. As long as the previous result of the regular //expression replace is NOT the same as the current replacement, //keep replacing and adding commas. while( retVal != (str = str.replace(/(\d{3})(\d{1,3})/,'$1,$2')) ) { retVal = str; } //If there were decimal points return them back with the reversed string if( parts[1] ) { return retVal.split('').reverse().join('') + '.' + parts[1]; } //return the reversed string return retVal.split('').reverse().join(''); } ``` Assuming you want to output a formatted number every second incremented by 0.54 you could use an interval to do your incrementation and outputting. **Super Short Firefox with Firebug only example:** ``` var num = 1412015; setInterval(function(){ //Your 0.54 value... why? I don't know... but I'll run with it. num += 0.54; console.log( formatNum( num ) ); },1000); ``` You can see it all in action here: <http://jsbin.com/opoze>
To increment a value on every second use this structure: ``` var number = 0; // put your initial value here function incrementNumber () { number += 1; // you can increment by anything you like here } // this will run incrementNumber() every second (interval is in ms) setInterval(incrementNumber, 1000); ``` This will format numbers for you: ``` function formatNumber(num) { num = String(num); if (num.length <= 3) { return num; } else { var last3nums = num.substring(num.length - 3, num.length); var remindingPart = num.substring(0, num.length - 3); return formatNumber(remindingPart) + ',' + last3nums; } } ```
JQuery/JavaScript increment number
[ "", "javascript", "jquery", "numbers", "increment", "" ]
Does anybody know how to use PHP to send product data to Amazon.com? I want to create a custom app that sends product data from an ecommerce website to Amazon (to list products on Amazon). I can't find any info on this.
Ok... I figured it out. To upload/modify your Amazon product listings (as they appear on Amazon.com), you can use the "Amazon Inventory Management" (AIM) API. [See info here: http://g-ec2.images-amazon.com/images/G/01/07102007\_AIM/Amazon\_AIMS.pdf](http://g-ec2.images-amazon.com/images/G/01/07102007_AIM/Amazon_AIMS.pdf)
From what I know (years old) it is done with csv file uploads This page on amazon still seems to imply that it is a file upload rather than a web service. <https://www.amazon.com/gp/seller-account/mm-product-page.html/ref=mm_soa_summ_learn?topic=200274780&ld=AZSOAMakeM> I think when you sign up as a merchant you will get information about it. From what I can remember there is a template xls or csv file they have for download.
How to send product data to Amazon.com?
[ "", "php", "amazon-web-services", "" ]
I have a JFrame that has a large number of changing child components. (Many layers) Is there any way to add a listener for all mouse events? Something like KeyEventDispatcher?
Use an AWTEventListener to filter out the MouseEvents: ``` long eventMask = AWTEvent.MOUSE_MOTION_EVENT_MASK + AWTEvent.MOUSE_EVENT_MASK; Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener() { public void eventDispatched(AWTEvent e) { System.out.println(e); } }, eventMask); ``` Check out [Global Event Listeners](http://tips4java.wordpress.com/2009/08/30/global-event-listeners/) for more information.
You could add a [GlassPane](http://java.sun.com/docs/books/tutorial/uiswing/components/rootpane.html) over your entire JFrame, add a [MouseInputAdapter](http://java.sun.com/javase/6/docs/api/javax/swing/event/MouseInputAdapter.html) to it to grab all possible mouse events, and then use [SwingUtilities.getDeepestComponentAt()][3] to get the actual component and [SwingUtilities.convertMouseEvent()][4] to delegate the mouse event from the glass pane to the actual component. However, I'm not sure of the performance impact of this - unlike KeyEventDispatcher, which just needs to fire an event whenever a key is pressed, multiple events are generated as the user moves the mouse - and unlike KeyEventDispatcher, you need to re-send the event to the lower component for it to handle it. (Sorry - stackoverflow isn't handling the links to the SwingUtilities methods correctly... links are showing below rather than in the text.) [3]: <http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/SwingUtilities.html#getDeepestComponentAt(java.awt.Component>, int, int) [4]: <http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/SwingUtilities.html#convertMouseEvent(java.awt.Component>, java.awt.event.MouseEvent, java.awt.Component)
How can I capture all mouse events in a JFrame/Swing?
[ "", "java", "swing", "" ]
I was browsing through one site called BSEINDIA.com (<http://www.bseindia.com/stockreach/stockreach.htm?scripcd=532667>), i Noticed that on click of Get Quote it seems to fire an Ajax request and get the price of selected equities. I tried to segregate this request and fire it separately, but it doesn't seem to work. I copied over the code from the HTML of same page (<http://www.bseindia.com/stockreach/stockreach.htm?scripcd=532667>) Any pointers why is this not working, is there some sort of Authentication going on , i am not even a member of this site?? following is what i am trying to do ``` <script type="text/javascript"> var oHTTP=getHTTPObject(); var seconds = Math.random().toString(16).substring(2); if(oHTTP) { oHTTP.open("GET","http://www.bseindia.com/DotNetStockReachs/DetailedStockReach.aspx?GUID="+seconds+"&scripcd=532667",true); oHTTP.onreadystatechange=AJAXRes; oHTTP.send(null); } function AJAXRes() { if(oHTTP.readyState==4)alert(oHTTP.responseText); } function getHTTPObject(){var obj; try{obj=new ActiveXObject("Msxml2.XMLHTTP");} catch(e){try{ obj=new ActiveXObject("Microsoft.XMLHTTP");} catch(e1){obj=null;}} if(!obj&& typeof XMLHttpRequest!='undefined'){ try{obj=new XMLHttpRequest();} catch(e){obj=false;}}return obj;} </script> ``` Found out my Answer here <http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.referer%28VS.71%29.aspx>
Actually, it is fairly easy. When you send an HTTP request, an header called [`Referrer`](http://en.wikipedia.org/wiki/HTTP_referrer) gets sent with the request. The [`Referrer`](http://en.wikipedia.org/wiki/HTTP_referrer) is basically the URL of the page which initiated the request. BSEINDIA checks the [`Referrer`](http://en.wikipedia.org/wiki/HTTP_referrer) value to make sure that the request is coming from their site. If it is, it sends the data. If not, it sends its 404 page. You can easily test that theory by disabling the [`Referrer`](http://en.wikipedia.org/wiki/HTTP_referrer) in your browser. In Firefox, you can do that by typing `about:config` and setting [`network.http.sendRefererHeader`](http://kb.mozillazine.org/Network.http.sendRefererHeader) to `0`. If you still want to get the data, you will need to write a script (in PHP or another language) which will make the request with the proper [`Referrer`](http://en.wikipedia.org/wiki/HTTP_referrer) and output the results.
There might be some form of IP restriction in place for accessing the files / data needed to save themselves from third party scripts accessing their data through their own scripts. Thats what I'd do.
How is this working?
[ "", "javascript", "ajax", "" ]
I'm trying to replace "\v" in the string "Lapensee\v" with "" ``` string a = "Lapensee\v"; string b = a.Replace("\\v", ""); Console.WriteLine(b); Output: Lapensee\v ``` Can anyone explain why this doesn't work?
``` string a = "Lapensee\v"; string b = a.Replace("\v", ""); // You don't want the double \\ Console.WriteLine(b); ``` Since you have \v in the string a, you should also replace it with \v.
I think you meant *either*: ``` string a = "Lapensee\\v"; ``` or ``` string b = a.Replace("\v", ""); ```
Replace /v in C# string
[ "", "c#", "string", "" ]
I tried to design a program which counts the vowels in a sentence. In my code, I used a `foreach` statement with the `if/else if` statement. I would like to convert these line of code using the `switch` statement but I'm not really sure where to go. Do I need to add a new method? I would appreciate your help. This is what I tried so far: I checked this one is very wrong. The `case 1` for example needs to have a constant. I'm not sure what constant shall I use here. ``` foreach (char v in yourSentence) { switch (v) { case 1: (v==ch1); counta++; j++; break; case 2: (v==ch2); counte++; j++; break; case 3: (v==ch3); counti++; j++; break; case 4: (v==ch4); counto++; j++; break; case 5: (v==ch3); counti++; j++; break; } } ``` Another question: I tried to change the color of the display text in the listBox. Is that possible to have different colors? What I also tried here is the first 5 (`listBox1.Items.Add`) are violet. And the sum of the (`listBox1.Items.Add`) is blue. But it seems that it didn't change. Did I miss something here? ``` private void btnCount_Click(object sender, EventArgs e) { string yourSentence; yourSentence = textBoxVowels.Text.ToLower().Trim(); char ch1 = 'a'; char ch2 = 'e'; char ch3 = 'i'; char ch4 = 'o'; char ch5 = 'u'; int counta = 0; int counte = 0; int counti = 0; int counto = 0; int countu = 0; int j = counta + counte + counti + counto + countu; foreach (char v in yourSentence) { if (v == ch1) { counta++; j++; } else if (v == ch2) { counte++; j++; } else if (v == ch3) { counti++; j++; } else if (v == ch4) { counto++; j++; } else if (v == ch5) { countu++; j++; } } listBox1.Items.Add("There are " + counta.ToString().Trim() + " a's in the sentence"); listBox1.Items.Add("There are " + counte.ToString().Trim() + " e's in the sentence"); listBox1.Items.Add("There are " + counti.ToString().Trim() + " i's in the sentence"); listBox1.Items.Add("There are " + counto.ToString().Trim() + " o's in the sentence"); listBox1.Items.Add("There are " + countu.ToString().Trim() + " u's in the sentence"); listBox1.Font = new Font("Arial", 12, FontStyle.Bold); listBox1.ForeColor = Color.Violet; listBox1.Items.Add("There are " + j.ToString().Trim() + " vowels in the sentence"); listBox1.ForeColor = Color.Blue; } private void btnClear_Click(object sender, EventArgs e) { textBoxVowels.Text = null; listBox1.Items.Clear(); } ```
I think you misunderstood how 'switch/case' works. Just change them to this: ``` case 'a': counta++; j++; break; ``` Case needs a constant value that should be compared to the current character.
Or just simplify the whole problem by using a bit of [LINQ](http://msdn.microsoft.com/en-us/netframework/aa904594.aspx). :) ``` public static int CountVowels(this string value) { const string vowels = "aeiou"; return value.Count(chr => vowels.Contains(char.ToLower(chr))); } ``` The [`Count`](http://msdn.microsoft.com/en-us/library/bb535181.aspx) extension method is particularly well suited to this task. Also, notice the use of a string of all vowels to check each character - much simpler than a switch statement. Note: It seems I missed the fact that you want to count each vowel individually. In this case, the LINQ becomes a bit more complicated (at least if you want to do it efficiently), but I shall leave that as an exercise for you. Regardless, a switch statement is probably a good way to learn the basics of C#. --- Since you're probably curious about the switch statement anyway, the following code uses the correct syntax: ``` foreach (var chr in sentence) { switch (chr) { case 'a': ... break; case 'e': ... break; case 'i': ... break; case 'o': ... case 'u': ... break; } } ```
Counting vowels using switch
[ "", "c#", "switch-statement", "" ]
How to make it so that the table user\_roles defines the two columns (userID, roleID) as a composite primary key. should be easy, just can't remember/find. In `user` entity: ``` @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "user_roles") public List<RoleDAO> getRoles() { return roles; } @Id @GeneratedValue(strategy = GenerationType.AUTO) public Integer getUserID() { return userID; } ``` In `roles` entity: ``` @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "user_roles") public List<UserDAO> getUsers() { return users; } @Id @GeneratedValue(strategy = GenerationType.AUTO) public Integer getRoleID() { return roleID; } ``` Thank you. \*\* MORE INFO So there is a third table `user_roles` (auto generated by above) that takes `userID` from `user` entity and `roleID` from `roles` entity. Now I need those two columns in the generated table (`user_roles`) to be a composite primary key.
You've already had a few good answers here on how to do exactly as you ask.. For reference let me just mention the recommended way to do this in Hibernate instead, which is to use a surrogate key as primary key, and to mark business keys as NaturalId's: > Although we recommend the use of > surrogate keys as primary keys, you > should try to identify natural keys > for all entities. A natural key is a > property or combination of properties > that is unique and non-null. It is > also immutable. Map the properties of > the natural key inside the > element. Hibernate will > generate the necessary unique key and > nullability constraints and, as a > result, your mapping will be more > self-documenting. > > It is recommended that you implement > equals() and hashCode() to compare the > natural key properties of the entity. In code, using annotations, this would look something like this: ``` @Entity public class UserRole { @Id @GeneratedValue private long id; @NaturalId private User user; @NaturalId private Role role; } ``` Using this will save you a lot of headaches down the road, as you'll find out when you frequently have to reference / map the composed primary key. I found this out the hard way, and in the end just gave up fighting against Hibernate and instead decided to go with the flow. I fully understand that this might not be possible in your case, as you might be dealing with legacy software or dependencies, but I just wanted to mention it for future reference. (*if you can't use it maybe someone else can*!)
In order to fulfill your requirement, you can map your @ManyToMany as a @OneToMany mapping. This way, USER\_ROLE will contain both USER\_ID and ROLE\_ID as compound primary key I will show you how to: ``` @Entity @Table(name="USER") public class User { @Id @GeneratedValue private Integer id; @OneToMany(cascade=CascadeType.ALL, mappedBy="joinedUserRoleId.user") private List<JoinedUserRole> joinedUserRoleList = new ArrayList<JoinedUserRole>(); // no-arg required constructor public User() {} public User(Integer id) { this.id = id; } // addRole sets up bidirectional relationship public void addRole(Role role) { // Notice a JoinedUserRole object JoinedUserRole joinedUserRole = new JoinedUserRole(new JoinedUserRole.JoinedUserRoleId(this, role)); joinedUserRole.setUser(this); joinedUserRole.setRole(role); joinedUserRoleList.add(joinedUserRole); } } @Entity @Table(name="USER_ROLE") public class JoinedUserRole { public JoinedUserRole() {} public JoinedUserRole(JoinedUserRoleId joinedUserRoleId) { this.joinedUserRoleId = joinedUserRoleId; } @ManyToOne @JoinColumn(name="USER_ID", insertable=false, updatable=false) private User user; @ManyToOne @JoinColumn(name="ROLE_ID", insertable=false, updatable=false) private Role role; @EmbeddedId // Implemented as static class - see bellow private JoinedUserRoleId joinedUserRoleId; // required because JoinedUserRole contains composite id @Embeddable public static class JoinedUserRoleId implements Serializable { @ManyToOne @JoinColumn(name="USER_ID") private User user; @ManyToOne @JoinColumn(name="ROLE_ID") private Role role; // required no arg constructor public JoinedUserRoleId() {} public JoinedUserRoleId(User user, Role role) { this.user = user; this.role = role; } public JoinedUserRoleId(Integer userId, Integer roleId) { this(new User(userId), new Role(roleId)); } @Override public boolean equals(Object instance) { if (instance == null) return false; if (!(instance instanceof JoinedUserRoleId)) return false; final JoinedUserRoleId other = (JoinedUserRoleId) instance; if (!(user.getId().equals(other.getUser().getId()))) return false; if (!(role.getId().equals(other.getRole().getId()))) return false; return true; } @Override public int hashCode() { int hash = 7; hash = 47 * hash + (this.user != null ? this.user.hashCode() : 0); hash = 47 * hash + (this.role != null ? this.role.hashCode() : 0); return hash; } } } ``` remember > If an object has an assigned > identifier, or a composite key, the > identifier SHOULD BE ASSIGNED to the > object instance BEFORE calling save(). So we have created a JoinedUserRoleId constructor like this one in order to take care of it ``` public JoinedUserRoleId(User user, Role role) { this.user = user; this.role = role; } ``` And finally Role class ``` @Entity @Table(name="ROLE") public class Role { @Id @GeneratedValue private Integer id; @OneToMany(cascade=CascadeType.ALL, mappedBy="JoinedUserRoleId.role") private List<JoinedUserRole> joinedUserRoleList = new ArrayList<JoinedUserRole>(); // no-arg required constructor public Role() {} public Role(Integer id) { this.id = id; } // addUser sets up bidirectional relationship public void addUser(User user) { // Notice a JoinedUserRole object JoinedUserRole joinedUserRole = new JoinedUserRole(new JoinedUserRole.JoinedUserRoleId(user, this)); joinedUserRole.setUser(user); joinedUserRole.setRole(this); joinedUserRoleList.add(joinedUserRole); } } ``` According to test it, let's write the following ``` User user = new User(); Role role = new Role(); // code in order to save a User and a Role Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Serializable userId = session.save(user); Serializable roleId = session.save(role); session.getTransaction().commit(); session.clear(); session.close(); // code in order to set up bidirectional relationship Session anotherSession = HibernateUtil.getSessionFactory().openSession(); anotherSession.beginTransaction(); User savedUser = (User) anotherSession.load(User.class, userId); Role savedRole = (Role) anotherSession.load(Role.class, roleId); // Automatic dirty checking // It will set up bidirectional relationship savedUser.addRole(savedRole); anotherSession.getTransaction().commit(); anotherSession.clear(); anotherSession.close(); ``` Notice according to code above NO REFERENCE to JoinedUserRole class. If you want to retrieve a JoinedUserRole, try the following ``` Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Integer userId; Integer roleId; // Lets say you have set up both userId and roleId JoinedUserRole joinedUserRole = (JoinedUserRole) session.get(JoinedUserRole.class, new JoinedUserRole.JoinedUserRoleId(userId, roleId)); // some operations session.getTransaction().commit(); session.clear(); session.close(); ``` regards,
how to make a composite primary key (java persistence annotation)
[ "", "java", "persistence", "annotations", "primary-key", "many-to-many", "" ]
I'm trying to extract the first user-right from semicolon separated string which matches a pattern. Users rights are stored in format: `LAA;LA_1;LA_2;LE_3;` String is empty if user does not have any rights. My best solution so far is to use the following regex in regex.replace statement: `.*?;(LA_[^;]*)?.*` (The question mark at the end of group is for the purpose of matching the whole line in case user has not the right and replace it with empty string to signal that she doesn't have it.) However, it doesn't work correctly in case the searched right is in the first position: `LA_1;LA_2;LE_3;` It is easy to fix it by just adding a semicolon at the beginning of line before regex replace but my question is, why doesn't the following regex match it? `.*?(?:(?:^|;)(LA_[^;]*))?.*` I have tried numerous other regular expressions to find the solution but so far without success.
I am not sure I get your question right, but in regards to the regular expressions you are using, you are overcomplicating them for no clear reason (at least not to me). You might want something like: ``` function getFirstRight(rights) { var m = rights.match(/(^|;)(LA_[^;]*)/) return m ? m[2] : ""; } ```
You could just split the string first: ``` function getFirstRight(rights) { return rights.split(";",1)[0] || ""; } ```
How to search csv string and return a match by using a Javascript regex
[ "", "javascript", "regex", "csv", "" ]
I am looking for a way to do the following: A Project : Defines an abstract class that is called when some events happen (event handler if you will) Defines the engine that will fire the events using the event handler above B Project: Defines the implementation for the abstract class Runs the engine. How can i register the implementation class and make sure that is the one being called when the engine runs. EDIT 1: By register i mean i must somehow define which is the implementation that should be called for that given abstract object Sorry if the question isn't too clear, let me know if you need some more details
At runtime, you can have the name of the implementation passed in your A project (with a properties file or a Java system property). Then you find this class in the classpath with `class.forName()` and instantiate it with `newInstance()`. But you'd prefer using a framework like [Guice](http://code.google.com/p/google-guice/) or Spring, that will allow you to glue stuff together in a clean way.
Something like this? ``` class A implements EventHandlerForB { ... } public class B { private EventHandlerForB eventHandler; public void registerEventHandler(EventHandlerForB eventHandler) { this.eventHandler = eventHandler; } ... } public interface EventHandlerForB { ... } ```
Define Implementation for abstract Object
[ "", "java", "class", "dependency-injection", "abstraction", "" ]
I have an app that starts 10 threads. Each thread does it's work and waits (using the producer consumer model). So when more work comes along, one of the threads is unblocked and it does the work. A colleague at work insists I should write some code that monitors the threads "just in case" they freeze/do not respond or die. So far in my testing, they work fine and close down correctly. My question is "should I put code in to do this"? If so, "how do I monitor a thread and check it's status"? Thanks. JD
It really depends on the situation. First of all, you should focus on correctness so that it doesn't freeze or die but if you need more reliability, you should first think about how you can gracefully recover from such a situation. You should think about why it might freeze or die and if it did, now what you can do. If you can't do anything good that reliably recovers from such a situation, you shouldn't even try. If can do it without making the situation worse, then you can go and try doing so. Obviously, if you made such a choice, you have to be careful not to mess things up and introduce some bugs that actually make the bad stuff happen yourself.
Ideally no, your threads should be able to finish properly. Monitoring them is not worth the complexity and processing time. If you do it correctly you won't need monitoring.
Should you code in case the threads die or freeze?
[ "", "c#", "" ]
I have a client that starts a long running process on the server. At regular intervals, I'd like to show the user what's happening in the background. The most simple approach is to poll the server but I'm wondering if there wasn't a way to implement the Observer pattern for this. Unfortunately, I'm using RMI to talk to the server and I fear that I have to turn my client into an RMI server for this. Is there another way that I'm missing?
<http://sites.google.com/site/jamespandavan/Home/java/sample-remote-observer-based-on-rmi>
RMI can in general support two way communication. (And yeah, RMI is a PITA to set up, and do anything else with.) However, the HTTP transport that works over a CGI script(!) does not support it.
How to implement the Observer pattern with Java RMI?
[ "", "java", "rmi", "observer-pattern", "" ]
``` <div id="message" style="display: none"> <!-- Here I want to place a message. It should be visible for 3 seconds.Then clear the div to get ready for the next message. --> </div> ``` How can I do the following using JQuery ? 1.Insert a message into div with id="message" and make div visible. 2.Make the message visible for 3 seconds. 3.Remove the content of div "message". 4.Hide the div and then if necessary start with step 1. Thank you in advance.
You can do something like this: ``` var $messageDiv = $('#message'); // get the reference of the div $messageDiv.show().html('message here'); // show and set the message setTimeout(function(){ $messageDiv.hide().html('');}, 3000); // 3 seconds later, hide // and clear the message ```
**Here's how I do it:** ``` $.msg = function(text, style) { style = style || 'notice'; //<== default style if it's not set //create message and show it $('<div>') .attr('class', style) .html(text) .fadeIn('fast') .insertBefore($('#page-content')) //<== wherever you want it to show .animate({opacity: 1.0}, 3000) //<== wait 3 sec before fading out .fadeOut('slow', function() { $(this).remove(); }); }; ``` --- **Examples:** ``` $.msg('hello world'); $.msg('it worked','success'); $.msg('there was a problem','error'); ``` --- **How it works** 1. creates a div element 2. sets the style (so you can change the look) 3. sets the html to show 4. starts fading in the message so it is visible 5. inserts the message where you want it 6. waits 3 seconds 7. fades out the message 8. removes the div from the DOM -- no mess! --- **Bonus Sample Message Styling:** ``` .notice, .success, .error {padding:0.8em;margin:0.77em 0.77em 0 0.77em;border-width:2px;border-style:solid;} .notice {background-color:#FFF6BF;color:#514721;border-color:#FFD324;} .success {background-color:#E6EFC2;color:#264409;border-color:#C6D880;} .error {background-color:#FBE3E4;color:#8a1f11;border-color:#FBC2C4;} .error a {color:#8a1f11;} .notice a {color:#514721;} .success a {color:#264409;} ``` ```
Using JQuery, how can I make a <div> appear, then add some html, then remove the html and then hide the div?
[ "", "javascript", "jquery", "timed", "" ]
Ok, got a tricky one here... If my data looks like this: Table1 ``` ID Date_Created 1 1/1/2009 2 1/3/2009 3 1/5/2009 4 1/10/2009 5 1/15/2009 6 1/16/2009 ``` How do I get the records that are 2 days apart from each other? My end result set should be rows 1-3, and 5-6. Thanks!
``` select distinct t1.* from Table1 t1 inner join Table1 t2 on abs(cast(t1.Date_Created - t2.Date_Created as float)) between 1 and 2 ```
``` SELECT l.* FROM Table1 l INNER JOIN Table1 r ON DATEDIFF(d, l.Date_Created, r.Date_Created) = 2 AND r.Date_Created = (SELECT TOP 1 * FROM Table1 WHERE Date_Created > l.Date_Created ORDER BY Date_Create) ```
SQL question: Getting records based on datediff from record to record
[ "", "sql", "datediff", "" ]
How would I change the wallpaper on a Linux desktop (using GNOME) within a C/C++ program? Is there a system API to do it?
Though the question was gnome-specific, there's also a way to deal with the wallpaper that is not depepndant on the higher layer toolkits. You should be able to deal with the root window (which the wallpaper is, in fact) by studying the source of [xsetroot.c](http://cgit.freedesktop.org/xorg/app/xsetroot/tree/xsetroot.c), the most interesting part of which I copypaste here: ``` static void SetBackgroundToBitmap(Pixmap bitmap, unsigned int width, unsigned int height) { Pixmap pix; GC gc; XGCValues gc_init; gc_init.foreground = NameToPixel(fore_color, BlackPixel(dpy, screen)); gc_init.background = NameToPixel(back_color, WhitePixel(dpy, screen)); if (reverse) { unsigned long temp=gc_init.foreground; gc_init.foreground=gc_init.background; gc_init.background=temp; } gc = XCreateGC(dpy, root, GCForeground|GCBackground, &gc_init); pix = XCreatePixmap(dpy, root, width, height, (unsigned int)DefaultDepth(dpy, screen)); XCopyPlane(dpy, bitmap, pix, gc, 0, 0, width, height, 0, 0, (unsigned long)1); XSetWindowBackgroundPixmap(dpy, root, pix); XFreeGC(dpy, gc); XFreePixmap(dpy, bitmap); if (save_colors) save_pixmap = pix; else XFreePixmap(dpy, pix); XClearWindow(dpy, root); unsave_past = 1; } ```
You could use [gconf](http://library.gnome.org/devel/gconf/stable/) library to do it. The following sample is a complete program to change background: ``` // bkgmanage.c #include <glib.h> #include <gconf/gconf-client.h> #include <stdio.h> typedef enum { WALLPAPER_ALIGN_TILED = 0, WALLPAPER_ALIGN_CENTERED = 1, WALLPAPER_ALIGN_STRETCHED = 2, WALLPAPER_ALIGN_SCALED = 3, WALLPAPER_NONE = 4 } WallpaperAlign; gboolean set_as_wallpaper( const gchar *image_path, WallpaperAlign align ) { GConfClient *client; char *options = "none"; client = gconf_client_get_default(); // TODO: check that image_path is a file if ( image_path == NULL ) options = "none"; else { gconf_client_set_string( client, "/desktop/gnome/background/picture_filename", image_path, NULL ); switch ( align ) { case WALLPAPER_ALIGN_TILED: options = "wallpaper"; break; case WALLPAPER_ALIGN_CENTERED: options = "centered"; break; case WALLPAPER_ALIGN_STRETCHED: options = "stretched"; break; case WALLPAPER_ALIGN_SCALED: options = "scaled"; break; case WALLPAPER_NONE: options = "none"; break; } } gboolean result = gconf_client_set_string( client, "/desktop/gnome/background/picture_options", options, NULL); g_object_unref( G_OBJECT(client) ); return result; } int main(int argc, const char* argv[]) { if ( argc > 1 ) { printf( "Setting %s as wallpaper... ", argv[1] ); if ( set_as_wallpaper( argv[1], WALLPAPER_ALIGN_STRETCHED ) ) printf( "Ok\n" ); else printf( "Failed\n" ); } else printf( "Usage: ./bkgmanage <filename>\n" ); return 0; } ``` The source above is based on [gthumb](http://gthumb.sourceforge.net/) project. It could be compiled with the following string: ``` gcc -Wall -g `pkg-config --libs --cflags glib-2.0 gconf-2.0` bkgmanage.c -o bkgmanage ```
Changing wallpaper on Linux programmatically
[ "", "c++", "linux", "gnome", "wallpaper", "desktop-wallpaper", "" ]
How can I select all elements that have a specific CSS property applied, using jQuery? For example: ``` .Title { color:red; rounded:true; } .Caption { color:black; rounded:true; } ``` How to select by property named "rounded"? CSS class name is very flexible. ``` $(".Title").corner(); $(".Caption").corner(); ``` How to replace this two operation to one operation. Maybe something like this: ``` $(".*->rounded").corner(); ``` Is there any better way to do this?
You cannot (using a CSS selector) select elements based on the CSS properties that have been applied to them. If you want to do this manually, you could select every element in the document, loop over them, and check the computed value of the property you are interested in (this would probably only work with real CSS properties though, not made up ones such as `rounded`). It would also would be slow. Update in response to edits — [group selectors](http://www.w3.org/TR/CSS21/selector.html#grouping): ``` $(".Title, .Caption").corner(); ```
This is a two year old thread, but it was still useful to me so it could be useful to others, perhaps. Here's what I ended up doing: ``` var x = $('.myselector').filter(function () { return this.style.some_prop == 'whatever' }); ``` not as succinct as I would like, but I have never needed something like this except now, and it's not very efficient for general use anyway, as I see it.
Select all elements that have a specific CSS, using jQuery
[ "", "javascript", "jquery", "css", "jquery-selectors", "" ]
OK..... I've done all the reading on related questions, and a few MSDN articles, and about a day's worth of googling. What's the current "state of the art" answer to this question: I'm using VS 2008, C++ unmanaged code. I have a solution file with quite a few DLLs and quite a few EXEs. As long as I completely control the build environment, such that all pieces and parts are built with the same flags, and use the same runtime libaries, and no one has a statically linked CRT library, am I ok to pass STL objects around? It seems like this should be OK, but depending on which article you read, there's lots of Fear, Uncertainty, and Doubt. I know there's all sorts of problems with templates that produce static data behind the scenes (every dll would get their own copy, leading to heartache), but what about regular old STL?
We successfully pass STL objects around in our application which is made up from dozens of DLLs. To ensure it works one of our automated tests that runs at every build is to verify the settings for all projects. If you add a new project and misconfigure it, or break the configuration of an existing project, the build fails. The settings we check are as follows. Note not all of these will cause issues, but we check them for consistency. #defines ``` _WIN32_WINNT STRICT _WIN32_IE NDEBUG _DEBUG _SECURE_SCL ``` Compiler options ``` DebugInformationFormat WholeProgramOptimization RuntimeLibrary ```
As long as they ALL use the exact same version of runtime DLLs, there should be no problem with STL. But once you happen to have several around, they will use for instance different heaps - leading to no end of troubles.
DLLs and STLs and static data (oh my!)
[ "", "c++", "windows", "visual-studio", "dll", "stl", "" ]
I want to find date by subtracting X number of days from a particular date in JavaScript. My JavaScript function accepts 2 parameters. One is the date value and the other is the number of days that needs to be subtracted. For example, I pass my argument date as 27 July 2009 and i pass my other argument as 3. So i want to calculate the date 3 days before 27 July 2009. So the resultant date that we should get is 24 July 2009. How is this possible in JavaScript. Thanks for any help.
Simply: ``` yourDate.setDate(yourDate.getDate() - daysToSubtract); ```
``` function date_by_subtracting_days(date, days) { return new Date( date.getFullYear(), date.getMonth(), date.getDate() - days, date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds() ); } ```
Finding date by subtracting X number of days from a particular date in Javascript
[ "", "javascript", "date", "" ]
I want to use a for loop to print every date between 2 dates. Actually going to merge this with a MySQL query to pass the date into the query itself and into the filename of the output. So, how can I change this: ``` sum = 0 for i in range(1,11): print sum sum += i ``` To this? ``` InputDate = '2009-01-01' for i in range('2009-01-01','2009-07-01'): print InputDate InputDate += i ``` I realize there is something in rrule that does this exact function: ``` a = date(2009, 1, 1) b = date(2009, 7, 1) for dt in rrule(DAILY, dtstart=a, until=b): print dt.strftime("%Y-%m-%d") ``` But, I am restricted to older version of python. This is the shell script version of what I am trying to do, if this helps clarify: ``` while [InputDate <= EndDate] do sql="SELECT Date,SUM(CostUsd) FROM DailyStats WHERE Date = '$InputDate' GROUP BY Date" name=$(mysql -h -sN -u -p -e "$sql" > DateLoop-$InputDate.txt db) echo "$name" InputDate=$(( InputDate + 1 )) done ``` So how can I do this in Python? Adding follow up question here for readability. Unfortunately I can not use standard MySQL library as we have a proprietary setup with numerous instances running in parallel. The only way to run this type of query is to connect to one instance at a time, on the command line. while day <= b: print "Running extract for :" day sql="SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date" os.system('mysql -h -sN -u -p -e " + sql + " > DateLoop-" + day + ".txt db') day += one\_day
This will work: ``` import datetime a = datetime.date(2009, 1, 1) b = datetime.date(2009, 7, 1) one_day = datetime.timedelta(1) day = a while day <= b: # do important stuff day += one_day ```
Try this: ``` import datetime dt1 = datetime.date(2009, 1, 1) dt2 = datetime.date(2009, 7, 1) dt = dt1 while dt <= dt2: print dt.strftime("%Y-%m-%d") dt += datetime.timedelta(days=1) ``` You say you are restricted to an older version of Python. If you don't have the datetime module (Python < 2.3), then you can also do: ``` import time dt1 = time.mktime(time.strptime('2009-01-01', '%Y-%m-%d')) dt2 = time.mktime(time.strptime('2009-07-01', '%Y-%m-%d')) ONE_DAY = 86400 dt = dt1 while dt <= dt2: print time.strftime('%Y-%m-%d', time.gmtime(dt)) dt += ONE_DAY ```
Creating Date Intervals in Python
[ "", "python", "mysql", "" ]
So I know this is a pretty dumb question, however (as the rather lengthily title says) I would like to know how do the following: I have a table like this: ``` ID Foo Bar Blagh ---------------- 1 10 20 30 2 10 5 1 3 20 50 40 4 20 75 12 ``` I want to group by Foo, then pull out rows with minimum Bar, i.e. I want the following: ``` ID Foo Bar Blagh ---------------- 2 10 5 1 3 20 50 40 ``` I can't for the life of me work out the correct SQL to retrieve this. I want something like: ``` SELECT ID, Foo, Bar, Blagh FROM Table GROUP BY Foo HAVING(MIN(Bar)) ``` However this clearly doesn't work as that is completely invalid HAVING syntax and ID, Foo, Bar and Blagh are not aggregated. What am I doing wrong?
[This](https://stackoverflow.com/questions/1211954/find-the-row-associated-with-a-min-max-without-inner-loop) is almost exactly the same question, but it has some answers! Here's me mocking up your table: ``` declare @Borg table ( ID int, Foo int, Bar int, Blagh int ) insert into @Borg values (1,10,20,30) insert into @Borg values (2,10,5,1) insert into @Borg values (3,20,50,70) insert into @Borg values (4,20,75,12) ``` Then you can do an anonymous inner join to get the data you want. ``` select B.* from @Borg B inner join ( select Foo, MIN(Bar) MinBar from @Borg group by Foo ) FO on FO.Foo = B.Foo and FO.MinBar = B.Bar ``` **EDIT** Adam Robinson has helpfully pointed out that "this solution has the potential to return multiple rows when the minimum value of Bar is duplicated, and eliminates any value of foo where bar is `null`" Depending upon your usecase, duplicate values where Bar is duplicated might be valid - if you wanted to find all values in Borg where Bar was minimal, then having both results seems the way to go. If you need to capture `NULLs` in the field across which you are aggregating (by MIN in this case), then you could `coalesce` the NULL with an acceptably high (or low) value (this is a hack): ``` ... MIN(coalesce(Bar,1000000)) MinBar -- A suitably high value if you want to exclude this row, make it suitably low to include ... ``` Or you could go for a UNION and attach all such values to the bottom of your resultset. ``` on FO.Foo = B.Foo and FO.MinBar = B.Bar union select * from @Borg where Bar is NULL ``` The latter will not group values in @Borg with the same `Foo` value because it doesn't know how to select between them.
``` select ID, Foo, Bar, Blagh from Table join ( select ID, (row_number() over (order by foo, bar) - rank() over (order by foo)) as rowNumber ) t on t.ID = Table.ID and t.rowNumber = 0 ``` This joins on the table again, but this time adds a relative row number for the value for `bar`, as if it were sorted ascending within each value of `foo`. By filtering on `rowNumber = 0`, it selects only the lowest values for `bar` for each value of `foo`. This also effectively eliminates the `group by` clause, since you're now only retrieving one row per `foo`.
How do you group by one column and retrieve a row with the minimum value of another column in T/SQL?
[ "", "sql", "sql-server", "t-sql", "" ]
I'm trying to move items in my list but when I compare against the last option I exit out before I move the items in my move linked list. Is there a way to do that before the node gets put at the end and can't loop through to move the items? ``` LinkedList<BD> list = new LinkedList<BD>(b[arg].Values); LinkedListNode<BD> node, terminator, next = null; List<LinkedListNode<BD>> move = new List<LinkedListNode<BD>>(); terminator = list.First; node = next = list.Last; while (next != null && next != terminator) { node = next; next = next.Previous; if (IDs.Contains(node.Value.Id)) { move.Add(node); list.Remove(node); } else { foreach (var item in move) { list.AddBefore(node, item); node = node.Previous; } move.Clear(); } } ```
Here is what worked for me. I tried different thing and thinks for the help but here is what worked for me more than just moving to the front but also just moving through the list: ``` while (next != null) { node = next; next = next.Previous; if (IDs.Contains(Id)) { move.Add(node); list.Remove(node); } else { foreach (var item in move) { list.AddBefore(node, item); node = node.Previous; } move.Clear(); } if (next == null) { foreach (var item in move) { list.AddFirst(item); } move.Clear(); } } ```
Your code is interleaving the two lists -- this doesn't look right to me. I think that instead of the repeated block ``` foreach (var item in move) { list.AddBefore(node, item); node = node.Previous; } move.Clear(); ``` you probably want something like ``` var before = node.Previous; var LinkedListNode<BD> current = null; foreach (var item in move) { list.AddBefore(node, item); current = node = item; } current.Previous = before; // assumes move was not empty move.Clear(); ``` to keep track of where you're inserting.
Moving items in linked list C#.NET
[ "", "c#", "linked-list", "" ]
I have a .txt file with product data, which I want to read in php. Each line contains one product, and the product details (number, name and price) are separated by tabs. As you can see below, it is not always true that the prices are nicely aligned vertically, because of the difference in length for the prodcut names. The data look like this: ``` ABC001 an item description $5.50 XYZ999 an other item $6 PPP000 yet another one $8.99 AKA010 one w a longer name $3.33 J_B007 a very long name, to show tabs $99 ``` (I didn't know how to show the tabs, so they are spaces in the example above, but in the real file, it are real tabs) What is the most efficient way to do this? (by the way, it is a remote file) I would love to have an array containing the product data per product: ``` $product['number'], $product['name'] and $product['price'] ``` Thanks very much!
1) Easiest way is using file() to load all the lines into an array (unless the file is really big, then i would consider another approach). 2) split each line by tab ("\t" character) 3) "format" the array columns as you wish. Sample snippet: ``` $productsArray = file($productsFileName, FILE_IGNORE_NEW_LINES); foreach ($productsArray as $key => &$product) { $arr = explode("\t", $product); $product = array('number' => $arr[0], 'name' => $arr[1], 'price' => $arr[2]); } var_dump($productsArray); ```
You could read the file line by line (using the function [`file`](http://php.net/manual/en/function.file.php), for instance, that will get you each line into one line of an array). And, then, use [`explode`](http://php.net/explode) on each of those lines, to separate the fields : ``` $data_of_line = explode("\t", $string_line); ``` Using "`\t`" (tabulation") as a separator. You'd then have `$data_of_line[0]` containing the number, `$data_of_line[1]` the name, and `$data_of_line[2]` the price.
php read product data txt file
[ "", "php", "file", "text-files", "" ]
In which languages are the Java *compiler* (`javac`), the virtual machine (JVM) and the `java` starter written?
The precise phrasing of the question is slightly misleading: it is not *"the JVM"* or *"the compiler"* as there are **multiple JVM vendors** (jrockit is one, IBM another) and **multiple compilers** out there. * The Sun JVM *is* written in `C`, although this need not be the case - the JVM as it runs on your machine is a *platform-dependent* executable and hence *could* have been originally written in any language. For example, the original IBM JVM was written in **Smalltalk** * The Java libraries (`java.lang`, `java.util` etc, often referred to as *the Java API*) are themselves written in Java, although methods marked as `native` will have been written in `C` or `C++`. * I believe that the Java compiler provided by Sun is also written in Java. (Although again, there are multiple compilers out there)
The very first Java compiler was developed by Sun Microsystems and was written in C using some libraries from C++. Today, the Java compiler is written in Java, while the JRE is written in C. We can imagine how the Java compiler was written in Java like this: The Java compiler is written as a Java program and then compiled with the Java compiler written in C(the first Java compiler). Thus we can use the newly compiled Java compiler(written in Java) to compile Java programs.
In which language are the Java compiler and JVM written?
[ "", "java", "jvm", "javac", "" ]
Hi i have a requirement where i have to use a tools API which is VB dll and i have to do some insert ,delete and update using that API. Can i use C#.net to implement these functionalities.If i use vb dll as reference and use thode API's will i face any issue ?
Absolutely not, you should be able to consume it without any problems.
If it is VB.NET DLL, and as long as it exposes only CLS-compliant types, then you will have no trouble at all. If these are VB 6 components, as opposed to VB.NET, then you will sometimes find strangeness when dealing with some types like variants. At least that was what I experienced when doing this.
can we use C#.NET to consume a VB dll (API)
[ "", "c#", ".net", "" ]
I need to write a download servlet in java to download a file from the web server. I am setting the response parameters as follows: ``` resp.setContentType( (mimetype != null) ? mimetype : "application/octet-stream"); resp.setContentLength( (int)f.length() ); resp.setHeader( "Content-Disposition", "attachment; filename=\"" + filename + "\"" ); ``` The code seems to work fine with firefox, chrome and IE7 but with IE6 its adding "`[1]`" in the middle of the filename. E.g. `test[1]_check.txt` (instead of `test_check.txt`). There are no duplicate copies of the file on client side and I'm unable to understand where I'm going wrong. Is there an issue with my response parameters? Thanks in advance
I think i understand the problem...In creating the filename of the file to be downloaded it is a concatenation of 2 strings such as : test.pdf\_check.txt. Firefox and Chrome download using the same name but IE6 inserts [1] just before the first extension it encounters (.pdf) so I get test[1].pdf\_check.txt. I removed the first extension and it seems to be working fine.
check the Temp folder: ``` C:\Documents and Settings\YourUserName\Local Settings\Temp ``` maybe there's a copy of the file from previous downloads
Download servlet issue with ie 6
[ "", "java", "servlets", "" ]
I have three JLabels and three JTextAreas. I have them in borderlayout, center, but I want each of them in a different line, that's not happening and the top ten search results in Google for line break java don't solve the problem. How can I do a simple line break?
If this is a Swing application, you should use a [layout manager](http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html) to position your fields in the container.
Line break won't help with placing Swing objects; you need to place a layout on a center JPanel. That is, the center of your border layout should be a single Swing object, a JPanel, and you should set that to a style which allows you to stack each widget. GridLayout(6,1) may do it.
<br>? \n? a line break in java
[ "", "java", "swing", "" ]
My friend read an article which mentioned that moving all JavaScript files to the end of the closing body tag (`</body>`), will improve the performance of a web page. I have moved all JS files to the end except the JQuery and the JS files which are attaching event to an element on page, like below; ``` $(document).ready(function(){ //submit data $("#create_video").click(function(){ //... }); }); ``` but he's saying to move the jQuery library file to the end of body tag. I don't think it is possible, because I am attaching many events to page elements on load using jQuery selectors, and to use jQuery selectors it is must to load jQuery library first. Is it possible to move JQuery library file to the end of page right before closing body tag (`</body>`) ?? Thanks
The `$(document).ready` function says not to run until the DOM has finished being instantiated - so moving it to after body is okay so long as the JQuery library is loaded first. Unconventional and some assumptions may not be correct anymore but okay.
It's standard practice to move all your js includes to the bottom of your page. This is because when a browser loads script, it does not spawn a new thread to do so, so basically the browser will wait until it has loaded the script before it proceeds to the next line. What this means for your users is that they will see a blank screen. Much better to have them see the full(ish) page as then it doesn't look like it has stalled.
Move jQuery to the end of body tag?
[ "", "javascript", "jquery", "xhtml", "" ]
I've got a problem with executing a python script in different environments with different versions of the interpreter, because the way text is formatted differ from one version to another. In python < 2.6, it's done like this: ``` n = 3 print "%s * %s = %s" % (n, n, n*n) ``` whereas in python >= 2.6 the [best way to do it](http://docs.python.org/library/stdtypes.html#str.format) is: ``` n = 3 print "{0} * {0} = {1}".format(n, n*n) ``` But how about when you want the script to be runned in any python version? What's better, to write python<2.6 code to assure instant compatibility or use the python>=2.6 code that is going to be the way it's used in the future? Is there any other option to write code for the actual python versions without loosing compatibility with olders? Thanks
str.format() was introduced in Python 2.6, but its only become the preferred method of string formatting in Python 3.0. In Python 2.6 both methods will still work, of course. It all depends on who the consumers of your code will be. If you expect the majority of your users will not be using Python 3.0, then stick with the old formatting. However, if there is some must-have feature in Python 3.0 that you require for your project, then its not unreasonable to require your users to use a specific version of the interpreter. Keep in mind though that Python 3.0 breaks some pre 3.0 code. So in summary, if you're targeting Python 3.0, use str.format(). If you're targeting Pyhon <3.0, use % formatting.
What about the good old tuple or string concatenation? ``` print n, "*", n, "=", n*n #or print str(n) + " * " + str(n) + " = " + str(n*n) ``` it's not as fancy, but should work in any version. if it's too verbose, maybe a custom function could help: ``` def format(fmt, values, sep="%%"): return "".join(str(j) for i in zip(fmt.split(sep), values) for j in i) #usage format("%% * %% = %%", [n, n, n*n]) ```
Text formatting in different versions of Python
[ "", "python", "formatting", "" ]
HI! How do i check if the users are trying to upload bigger than 2mb files? I would like to deny that and put an error message to the user who is trying to do that. I know it is something like this, but what shall i change the 50000 to to become 2mb? ``` if ($_FILES['imagefile']['size'] > 50000 ) { die ("ERROR: Large File Size"); } ```
2 MB is 2097152 bytes. Change the 50000 to 2097152 and you're set.
The 5,000 is the number of byes, so basically you just need to convert 2MB to bytes. 1 MB is 1024 kilobytes, and 1024 bytes is 1 kilobyte. Doing the maths, we get: 2 megabytes = 2 097 152 bytes Basically, you can calculate this in code form ``` $maxFileSize = $MB_limit * 1024 * 1024; ``` And check that the file size does not exceed $maxFileSize.
Don't allow > 2mb images
[ "", "php", "upload", "size", "limit", "" ]
Each user HAS MANY photos and HAS MANY comments. I would like to order users by ``` SUM(number_of_photos, number_of_comments) ``` Can you suggest me the SQL query?
GROUP BY with JOINs works more efficiently than dependent subqueries (in all relational DBs I know): ``` Select * From Users Left Join Photos On (Photos.user_id = Users.id) Left Join Comments On (Comments.user_id = Users.id) Group By UserId Order By (Count(Photos.id) + Count(Comments.id)) ``` with some assumptions on the tables (e.g. an `id` primary key in each of them).
``` Select * From Users U Order By (Select Count(*) From Photos Where userId = U.UserId) + (Select Count(*) From Comments Where userId = U.UserId) ``` EDIT: although every query using subqueries can also be done using Joins, which will be faster , 1. is not a simple question, 2. and is irrelevant unless the system is experiencing performance problems. 1) Both constructions must be translated by the query optimizer into a query plan which includes some type of correlated join, be it a nested loop join, hash-join, merge join, or whatever. And it's entirely possible, (even likely), that they will both result in the same query plan. NOTE: This is because the *entire* SQL Statement is translated into a single query plan. The subqueries do ***NOT*** get their own, individual query plans as though they were being executed in isolation. What query plan and what type of joins are used will depend on the data structure and the data in each specific situation. The only way to tell which is faster is to try both, in controlled environments, and measure the performance... but, 2) Unless the system is experiencing an issue with performance, (unacceptable poor performance). clarity is more important. And for problems like the one described above, (where none of the data attributes in the "other" tables are required in the output of the SQL Statement, a Subquery is much clearer in describing the function and purpose of the SQL that a join with Group Bys would be.
Select Users with more Items
[ "", "sql", "" ]
I'm trying to provide integration to my django application from subversion through the post commit hook. I have a django test case (a subclass of unittest.TestCase) that (a) inserts a couple of records into a table, (b) spawns an svn commit, (c) svn commit runs a hook that uses my django model to look up info. I'm using an sqlite3 db. The test is *not* using the :memory: db, it is using a real file. I have modified the django test code (for debugging this issue) to avoid deleting the test db when it is finished so I can inspect it. The test code dumps model.MyModel.objects.all() and the records are there between (a) and (b). When the hook fires at (c) it also dumps the model and there are no records. When I inspect the db manually after the test runs, there are no records. Is there something going on in the django test framework that isn't commiting the records to the db file? **To clarify**: (d) end the test case. Thus the svn commit hook is run before the test case terminates, and before any django db cleanup code *should* be run. **Extra info**: I added a 15 second delay between (b) and (b) so that I could examine the db file manually in the middle of the test. The records aren't in the file.
Are you using Django trunk? Recent changes ([Changeset 9756](http://code.djangoproject.com/changeset/9756)) run tests in a transaction which is then rolled back. Here's the check-in comment: > Fixed #8138 -- Changed > django.test.TestCase to rollback tests > (when the database supports it) > instead of flushing and reloading the > database. This can substantially > reduce the time it takes to run large > test suites.
The test framework is not saving the data to the database, the data is cleaned once the tests have finished.
can't see records inserted by django test case
[ "", "python", "django", "testing", "sqlite", "" ]
I have the following code that sends a message using the mail() function. Everything works fine except the line breaks at the end of each line don't seem to work. As you can see I am using " \r\n " hoping that this will give me a line break but it doesn't I have added `<br>` to get the break, but I would rather not use that in case someone doesn't have an HTML email client. ``` <?php $to = 'user@example.com'; // Was a valid e-Mail address, see comment below $name = $_REQUEST['name'] ; $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; $content = 'Name: '.$name."\r\n"; $content .= 'Email: '.$email."\r\n"; $content .= 'Subject: '.$subject."\r\n"; $content .= 'Message: '.$message."\r\n"; $headers = 'MIME-Version: 1.0' ."\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' ."\r\n"; // Additional headers $headers .= 'To: iVEC Help <help@ivec.com>'. "\r\n"; $headers .= 'From: '.$name.' <'.$email.'>' . "\r\n"; mail( $to, $subject, $content, $headers); ?> <p> You sent it ... good work buddy </p> <p> <?php '$name' ?> </p> ```
You're sending it as HTML - change the content type to `text/plain` and it should work.
The problem is that you say, in your headers, that the mail is an HTML email: ``` $headers .= 'Content-type: text/html; charset=iso-8859-1' ."\r\n"; ``` If you want to ensure compability with both HTML and text clients, consider using the Multipart content type. This can be achieved in many different ways, but one simple way is to use a library that can do this for you. For example, you can use [PEAR:Mail\_Mime](http://pear.php.net/package/Mail_Mime)
PHP line breaks don't seem to work
[ "", "php", "string", "line-breaks", "" ]
I am working with C#.net and also SQL Server 2008. I have the following error, when trying to run a test unit within my project. ``` System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.. ``` Database Table ``` Column Name: createddate Type: datetime Default Value: (getdate()) Allow Nulls: No. ``` I don't want to insert the createddate as part of my INSERT query. When I manually enter some data into the database table I get the following error: ``` The row was successfully committed to the database. However, a problem occurred when attempting to retrieve the data back after commit. Because of this the displayed data within the row is read-only. To fix this problem, please re-run the query. ``` I don’t understand why I am getting this error and cannot find anyone who has had this problem. Can anyone help?
Matt is most likely on the right track. You have defined a default value for your column - however, that will only take effect if you actually insert something in your table in the database. When you do a unit test, as you say, you most likely initialize the DateTime variable to something (or not - then it'll be DateTime.MinValue, which is 01/01/0001) and then you send that to the SQL Server and this value is outside the valid range for a DATETIME on SQL Server (as the error clearly states). So what you need to do is add a line to your .NET unit test to initialize the DateTime variable to "DateTime.Today": ``` DateTime myDateTime = DateTime.Today ``` and then insert that into SQL Server. OR: you can change your SQL INSERT statement so that it does not insert a value for that column - it looks like right now, it does do that (and attempts to insert that - for SQL Server - invalid date into the table). If you don't specify that column in your INSERT, then the column default of `getdate()` will kick in and insert today's date into the column. Marc
Are you using Linq to SQL to write your unit test? If you are, it might be bypassing the getdate() default value, and using some other value instead which falls outside the valid range.
System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow
[ "", "c#", ".net", "sql-server", "sql-server-2008", "" ]
I have created a console test application which creates, an object & calls 2 functions on 2 separate threads. One thread prints numbers form 1- 20 the other in the reverse order. The problem is while debugging the 1st worker thread does not get fired till I don't stop debugging the main thread (i.e. I press f5). Any answers? ``` class Program { static void Main(string[] args) { DisplayData dd = new DisplayData(); ThreadStart ts1 = new ThreadStart(dd.DisplayNumber); Thread t1 = new Thread(ts1); t1.Name = "Display Numbers"; ThreadStart ts2 = new ThreadStart(dd.ReverseNumbers); Thread t2 = new Thread(ts2); t2.Name = "Reverse Numbers"; t1.Start(); //Keep 1st break point at this location. Then press F10. t2.Start(); //Keep break point at this location permanently } public class DisplayData { public void DisplayNumber() { int length = 20; Console.WriteLine("\nNumbers in correct order.\n"); for (int i = 0; i < length; i++) { Console.WriteLine("DN: The value of i is: " + (i+1) + " " + Thread.CurrentThread.ManagedThreadId + " " + Thread.CurrentThread.Name); //Thread.Sleep(1000); } } public void ReverseNumbers() { int length = 20; Console.WriteLine("\nNumbers in reverse order.\n"); for (int i = 0; i < length; i++) { Console.WriteLine("RN: The value of i is: " + (length - i) + " " + Thread.CurrentThread.ManagedThreadId + " " + Thread.CurrentThread.Name); //Thread.Sleep(1000); } } ```
I'm not sure if this is a limitation in Visual Studio or the CLR but setting breakpoint on one thread will stop all threads. If you want to pause a thread you can do this through the Debug..Threads window, you can pause and resume threads there.
Work on another threat does not start until a context switch happens. It could easy get through all the work in your main routine before the CPU decides to start on something else. Use `t1.Join()` to wait for a worker thread to finish before continuing.
Why does a worker thread not execute when debugging the main thread?
[ "", "c#", "multithreading", "" ]
The page: **/index.php?page=6&test=1&test2=2** The code below strip's **page=6** off of this so I can add our new page to the url and add the $url\_without\_page\_var back to our link again: ``` $_SERVER['argv'][0] // Displays: page=6&test=1&test2=2 ``` And ``` $url_without_page_var=preg_replace('/page=(\d+)/i','',$_SERVER['argv'][0]); // Displays: &test=1&test2=2 ``` Ok so that code lets me take the **page=6** off of **page=6&test=1&test2=2** I can then change the page number and add this all back together. My problem is often the page in the URL will not always be in the same position, it may not be the 1st or last items And this is what will happen when, see how the URL is incorrect now; /page.php?**&\*\*test=1&test2=2 \*\*ERROR-HERE-ALSO** page=9 ## **Is it possible to fix this?**
The `$_GET` variable provides an array of all the variables set through the URL. `$_REQUEST` is an array of all the `GET` and `POST` variables set. Here's the fish: ``` $url_string = "index.php?"; foreach( $_GET as $k => $v ){ if( $k != "key_you_dont_want"){ // <-- the key you don't want, ie "page" if( $url_string != "index.php?" ) $url_string .= "&"; // Prepend ampersands nicely $url_string .= $k . "=" . $v; } } ``` Regex is a bit overkill for this problem. Hope it makes sense. I've been writing Python and Javascript for the past few weeks. PHP feels like a step backwards. EDIT: This code makes me happier. I actually tested it instead of blindly typing and crossing fingers. ``` unset( $_GET["page"] ); $c = count($_GET); $amp = ""; $url_string = "test.php"; if( $c > 0 ) { $url_string .= "?"; foreach( $_GET as $k => $v ){ $url_string .= $amp . $k . "=" . $v; $amp = "&"; } } ```
Why can't you just reconstruct the url? ``` $query = $_GET; unset($query['page']); $length = ($length = strpos($_SERVER['REQUEST_URI'], '?')) ? $length : strlen($_SERVER['REQUEST_URI']); $url = substr($_SERVER['REQUEST_URI'], 0, $length) . '?' . http_build_query($query); ``` http\_build\_query() does require PHP5 but you could easily rewrite that function. EDIT: Added the $length variable to fix the code.
Can regex fix this?
[ "", "php", "regex", "" ]
Until very recently I didn't know that there was a difference between a normal class and an inner class/sub class. What is the relationship between an instance of an inner class and an instance of its containing class. What is the purpose of inner classes and what makes them different?
Unlike Java, C# - contained classes are nested. There is no relation between containing class instance and instance of contained class. Contained classes are just used in C# to control accessibility of the contained class and avoid polluting namespaces. (Some companies have a coding standard that each class must go into it’s own file, contained classes is a way round that for small classes.) In Java an instance (object) of an inner class has a pointer back to the outer class. This was done in Java, as it uses lots of small classes to handle event etc. C# has delegates for that. (Contained classes were one of the experimental ideals in Java that everyone liked but did not truly prove the test of time. As C# come along a lot later, it could learn from Java what did not work well)
.NET does not have inner classes like Java does. It does have nested classes. The reason why you would use them, is to control the accessibility of the class.
Inner classes in C#
[ "", "c#", "inner-classes", "" ]
I get a "java.lang.NoClassDefFoundError: com/hp/hpl/jena/shared/BadURIException" when running a very simple servlet. The error points back to the initialisation of the "Tagger" class. The code is as follows ``` import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import my.package.Tagger; public class NormaliserServlet extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse response) throws IOException{ Tagger pot = new Tagger(""); response.setContentType("text"); PrintWriter out = response.getWriter(); out.println("hello"); out.println(pot.someMethod()); out.close(); this.log("Request for normaliser"); } } ``` The war file contains the jar file defining "Tagger" in WEB-INF/lib and a similar invocation works outside of a servlet. I can't seem to find what the problem would be. The web.xml is pretty standard too: ``` <servlet> <servlet-name>normalise</servlet-name> <servlet-class>NormaliserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>normalise</servlet-name> <url-pattern>/normalise</url-pattern> </servlet-mapping> ``` I'm using winstone as the servlet container, but i get the exact same error in tomcat. The stacktrace is: ``` java.lang.NoClassDefFoundError: com/hp/hpl/jena/shared/BadURIException at NormaliserServlet.doGet(NormaliserServlet.java:13) at javax.servlet.http.HttpServlet.service(HttpServlet.java:104) at javax.servlet.http.HttpServlet.service(HttpServlet.java:45) at winstone.ServletConfiguration.execute(ServletConfiguration.java:249) at winstone.RequestDispatcher.forward(RequestDispatcher.java:335) at winstone.RequestHandlerThread.processRequest(RequestHandlerThread.java:244) at winstone.RequestHandlerThread.run(RequestHandlerThread.java:150) at java.lang.Thread.run(Thread.java:619) ```
It looks like you're missing the jar for Jena(?) which defines the BadURIException class. Is that jar included in your WEB-INF/lib directory as well? Have you tried looking at the unpacked war file in Winstone and checking if the relevant jars are all there?
You are missing the jar files from the [Jena project](http://jena.sourceforge.net/). They should be in your WAR file. It could be an indirect dependency of some other library that you use. Take a look at the stacktrace to see what else sits between Jena and your code.
java.lang.NoClassDefFoundError: com/hp/hpl/jena/shared/BadURIException on running servlet
[ "", "java", "eclipse", "tomcat", "servlets", "" ]
I'm trying to add some help to my GUI developed in VC++ 2008. I want to compile a chm file, or a hlp file that can be accessed from my menu. Anyone can give me any idea about how to do this? Thanks a lot
Under **HKLM\Software\Microsoft\Windows\HTMLHelp** , create an entry named **help.chm** value **C:\path to\help file.chm** Then to open the chm at a particular topic call ``` HtmlHelp(m_hWnd, "Help.chm", HH_DISPLAY_TOPIC, NULL); ```
You could just ShellExecute the .chm file. That will open it. ``` ShellExecute( hWnd, _T( "open" ), _T( "help.chm" ), NULL, NULL, SW_NORMAL ); ```
How can I open a help file (chm or so) from my GUI developed in VC++ 2008?
[ "", "c++", "process", "chm", "winhelp", "" ]
I'm developing an asp.net application which has Windows Authentication enabled(anonymous access disabled). I've created a sub directory called 'Mobile' containing the pages that need to be accessible from a black berry mobile device. These pages contain read only text and a few buttons for performing some actions(no AJAX, no javascript). Most of the devices are running on version 4.2 or 4.5 of the Blackberry OS/browser I've also downloaded the [Mobile Device Browser File(MDBF)](http://mdbf.codeplex.com/) and included it as outlined in that link. Here are some questions I have: 1) Is there a way to have the BES(BlackBerry Enterprise Server) server authenticate the user/device(possibly an AD lookup)and pass on the NT credentials of the authenticated user to IIS? i.e perform integrated authentication 2) By using the MDBF does ASP.NET send back HTML formatted for rendering based on the capabilities of the incoming browser/device, if not in this case is there any value in using MDBF, I don't intend to write device/browser specific code by looking at the device capabilities exposed through Request.Browser. 3) I have a stlesheet that I would like to have applied when these pages are viewed on the black berry.If I view the pages on the desktop, I can see the styles being applied correctly, but the styles are not being applied when viewing these pages on the blackberry.Is there anything in particular that needs to be set in the markup/codebehind /config to enable support for CSS.
I was able to get around items 1 & 2 as indicated in the comments of the original question. For item 3 I decided to leverage the fact that MDS caches the user supplied credentials and uses that to re-authenticate the client on future visits to the same site, the cache expiration policy can be set in the BES to force expiration if desired, also if the user's NT password is changed, the cached credentials are invalidated and the user is presented with a challenge response to re-authenticate once again.
for this to work, you may need to turn off windows authentication for the mobile portion of the site then you would have to create an html form, displayable by the blackberry browser, and [authenticate using Active Directory](http://msdn.microsoft.com/en-us/library/ms998360.aspx). once authenticated they can browse as normal.
Integrated authentication in ASP.NET for a BlackBerry client
[ "", "c#", ".net", "asp.net", "blackberry", "mobile", "" ]
I have the following repeater below and I am trying to find lblA in code behind and it fails. Below the markup are the attempts I have made: ``` <asp:Repeater ID="rptDetails" runat="server"> <HeaderTemplate> <table> </HeaderTemplate> <ItemTemplate> <tr> <td><strong>A:</strong></td> <td><asp:Label ID="lblA" runat="server"></asp:Label> </td> </tr> </ItemTemplate> </asp:Repeater> </table> ``` First I tried, ``` Label lblA = (Label)rptDetails.FindControl("lblA"); ``` but lblA was null Then I tried, ``` Label lblA = (Label)rptDetails.Items[0].FindControl("lblA"); ``` but Items was 0 even though m repeater contains 1 itemtemplate
You need to set the attribute `OnItemDataBound="myFunction"` And then in your code do the following ``` void myFunction(object sender, RepeaterItemEventArgs e) { Label lblA = (Label)e.Item.FindControl("lblA"); } ``` Incidentally you can use this exact same approach for nested repeaters. IE: ``` <asp:Repeater ID="outerRepeater" runat="server" OnItemDataBound="outerFunction"> <ItemTemplate> <asp:Repeater ID="innerRepeater" runat="server" OnItemDataBound="innerFunction"> <ItemTemplate><asp:Label ID="myLabel" runat="server" /></ItemTemplate> </asp:Repeater> </ItemTemplate> </asp:Repeater> ``` And then in your code: ``` void outerFunction(object sender, RepeaterItemEventArgs e) { Repeater innerRepeater = (Repeater)e.Item.FindControl("innerRepeater"); innerRepeater.DataSource = ... // Some data source innerRepeater.DataBind(); } void innerFunction(object sender, RepeaterItemEventArgs e) { Label myLabel = (Label)e.Item.FindControl("myLabel"); } ``` All too often I see people manually binding items on an inner repeater and they don't realize how difficult they're making things for themselves.
I just had the same problem. We are missing the **item type** while looping in the items. The very first item in the repeater is the **header**, and header does not have the asp elements we are looking for. Try this: ``` if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {Label lblA = (Label)rptDetails.Items[0].FindControl("lblA");} ```
Can't find control within asp.net repeater?
[ "", "c#", "asp.net", "repeater", "" ]
I have just started a new project using a Linq to Sql model and I'm implementing our first many to many relationship. I have found this blog that gives great info on how implement this: <http://blogs.msdn.com/mitsu/archive/2008/03/19/how-to-implement-a-many-to-many-relationship-using-linq-to-sql-part-ii-add-remove-support.aspx> When I try to add some child objects in and then remove one before saving I get an error, > System.InvalidOperationException: > Cannot remove an entity that has not > been attached. Any ideas? Someone has already commented on this to the author of the blog, but there has been no response. Much appreciated!
You are calling DeleteOnSubmit, on an entity that has not been sucked into the DataContext. To check for this (in a rather hacky way), do the following: ``` var e = some_entity; var cs = dc.GetChangeSet(); if (cs.Inserts.Any( x => x == e)) { dc.SomeTable.DeleteOnSubmit(e); } dc.SubmitChanges(); ```
I suspect that's why the author mentions that this particular post is working 'in memory' and not with linq to sql. Another approach would be to modify the onAdd event to Insert the added object into the context, that should at least alleviate the error you are seeing.
Linq to Sql Many to Many relationships
[ "", "c#", ".net", "linq", "linq-to-sql", "" ]
I have a C++ class '`Expression`' with a method I'd like to use in my Objective-C class '`GraphVC`'. ``` class Expression { double evaluate(double); } ``` And my Objective-C class: ``` @implementation GraphVC : UIViewController { - (void)plot:(double(*)(double))f; @end ``` I thought that it would be easiest to pass around function pointers that take a double and return a double, as opposed to C++ objects, but I haven't had much success using `functional.h`. What's the best way to use my C++ method from Objective-C? EDIT: Thanks for your quick responses. Allow me to elaborate a bit... I have a backend written in C++ where I manipulate objects of type Expression. There's subclasses for rational, polynomial, monomial, etc. My initial idea was to use [mem\_fun](http://www.cplusplus.com/reference/std/functional/mem_fun/) from , but I wasn't able to get code compiling this way. I also had trouble using bind1st to bind the `this` pointer. * Writing an Objective-C wrapper is a possibility, but I'd rather use the already existing `evaluate()` function, and I don't want to break the clean separation between the backend and the iPhone GUI classes. * I can't have a global expression or use a static method (I need to plot arbitrary `Expression` instances. I should have more explicitly stated that I need to pass a C++ member function (not a static function or existing C function) to an Objective-C object. Has anyone had luck using C++'s `<functional>` to turn member functions into pointers I can use in an Objective-C object, or should I use an Objective-C wrapper?
If you want to make a pointer to a method in C++, you need to include the class name, like this: ``` class Foo { public: double bar(double d) { return d; } }; void call_using_obj_and_method(Foo *f, double (Foo::*m)(double d)) { (f->*m)(3.0); } int main() { Foo f; call_using_obj_and_method(&f, &Foo::bar); return 0; } ``` Note that you need an instance of the class as well. In my example this is another parameter, though you could let it be a global variable, or a singleton instance of class Foo. Though, like jkp said, you can also solve the problem by making the method static or turning it into a regular function. **EDIT:** I'm not sure if I understand your question correctly. I don't think you need to use functional. Here is how my example would look in Objective-C++: ``` #include <Cocoa/Cocoa.h> class Foo { public: double bar(double d) { return d; } }; typedef double (Foo::*fooMethodPtr)(double d); @interface Baz : NSObject { } - (void)callFooObj:(Foo *)f method:(fooMethodPtr)m; @end @implementation Baz - (void)callFooObj:(Foo *)f method:(fooMethodPtr)m { (f->*m)(3.0); } @end int main() { Foo f; Baz *b = [[Baz alloc] init]; [b callFooObj:&f method:&Foo::bar]; return 0; } ```
I would suggest wrapping the C++ class in an Objective-C class, and then also providing a ``` - (void) plotWithObject:(id)obj { double result = [obj evaluate: 1.5]; // ... etc ... } ``` in addition to the plot: method.
Passing a C++ method to an Objective-C method
[ "", "c++", "objective-c", "function-pointers", "objective-c++", "" ]
I am implementing Quartz Job Store on Oracle DB using Spring Framework. My ApplicationContext.xml is below ``` <bean id="driverJob" class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass" value="BatchFileCollector" /> </bean> <bean id="ranchTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail" ref="driverJob" /> <property name="startDelay" value="2000" /> <property name="repeatInterval" value="10000" /> </bean> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="ranchTrigger" /> </list> </property> <property name="dataSource"> <ref bean="dataSource.TEXAN"/> </property> <property name="applicationContextSchedulerContextKey"> <value>applicationContext</value> </property> <property name="autoStartup"> <value>true</value> </property> <property name="configLocation" value="classpath:quartz.properties"/> </bean> ``` This configuration gives me the below error. ``` Caused by: org.quartz.JobPersistenceException: Couldn't store trigger: The job (DEFAULT.driverJob) referenced by the trigger does not exist. [See nested exception: org.quartz.JobPersistenceException: The job (DEFAULT.driverJob) referenced by the trigger does not exist.] ``` I am using Spring Framework 2.5.6. Do I have to upgrade my Quartz version? I cannot find the problem. Thanks for your help.
Your SchedulerFactoryBean needs to have the "driverJob" registered, too. Along with your triggers, add a list of jobDetails. ``` <bean id="job.statistics.DailyQPSValidationJobTrigger" class="org.quartz.CronTrigger"> <property name="name" value="DailyQPSValidationTrigger" /> <property name="jobName" value="DailyQPSValidation" /> <property name="jobGroup" value="Statistics" /> <property name="volatility" value="false" /> <!-- Each day, 4 o'clock AM --> <property name="cronExpression" value="0 0 4 * * ?" /> </bean> <!-- Scheduler --> <bean id="job.SchedulerProperties" class="somecompany.someproduct.util.spring.PropertiesFactoryBean" scope="singleton"> <property name="source"> <props> <prop key="org.quartz.scheduler.instanceId">AUTO</prop> <prop key="org.quartz.scheduler.instanceName">JobCluster</prop> <prop key="org.quartz.jobStore.class">org.quartz.impl.jdbcjobstore.JobStoreTX</prop> <prop key="org.quartz.jobStore.driverDelegateClass">org.quartz.impl.jdbcjobstore.StdJDBCDelegate</prop> <prop key="org.quartz.jobStore.isClustered">true</prop> <prop key="org.quartz.jobStore.useProperties">false</prop> </props> </property> </bean> <bean id="job.Scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" scope="singleton" lazy-init="false"> <property name="startupDelay" value="30" /> <property name="waitForJobsToCompleteOnShutdown" value="true" /> <property name="dataSource" ref="jdbc.DataSource" /> <property name="quartzProperties" ref="job.SchedulerProperties" /> <property name="jobDetails"> <list> <ref bean="job.statistics.DailyQPSValidationJobDetail" /> </list> </property> <property name="triggers"> <list> <ref bean="job.statistics.DailyQPSValidationJobTrigger" /> </list> </property> <property name="schedulerListeners"> <list> <bean class="somecompany.someproduct.job.SchedulerErrorListener"> <property name="monitoringService" ref="monitoring.MonitoringService" /> </bean> </list> </property> <property name="globalJobListeners"> <list> <bean class="somecompany.someproduct.job.JobErrorListener"> <property name="name" value="JobErrorListener" /> <property name="monitoringService" ref="monitoring.MonitoringService" /> </bean> </list> </property> </bean> ```
I have the same problem with Quartz 1.5.2 and Spring 3.0.4. The problem is that the JobStoreSupport class tries to store a cron trigger with a foreign key to the job (tries to load the job from the db), which is not persisted yet. Same problem with quartz 1.6.1, 1.7.2 versions. ``` <bean id="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" depends-on="quartzDatabaseCreator"> <property name="autoStartup"> <value>true</value> </property> <property name="dataSource"> <ref bean="dataSource"/> </property> <property name="quartzProperties"> <props> <prop key="org.quartz.jobStore.selectWithLockSQL">SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = ? </prop> <prop key="org.quartz.jobStore.driverDelegateClass">org.quartz.impl.jdbcjobstore.${qrtz.delegateClass} </prop> </props> </property> <property name="triggers"> <list> <ref bean="cronTrigger"/> </list> </property> <property name="schedulerContextAsMap"> <map> <entry key="sygnoServerHelper"><ref bean="sygnoServerHelper"/></entry> <entry key="requestDAO"><ref bean="requestDAO"/></entry> <entry key="alairoCache"><ref bean="alairoCache"/></entry> </map> </property> </bean> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="checkGracePeriodJob" /> <!-- # s m h dom mon dow [y] --> <property name="cronExpression" value="0 0/5 * * * ?" /> </bean> <bean id="checkGracePeriodJob" class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass" value="com.synergon.sygnoserver.CheckGracePeriodJob"/> </bean> ```
Quartz JobStore with Spring Framework
[ "", "java", "spring", "quartz-scheduler", "" ]
Hey. I'm taking a course titled Principles of Programming Languages, and I need to decide on a project to do this summer. Here is a short version of what the project needs to accomplish: "The nature of the project is language processing. Writing a Scheme/Lisp processor is a project of this type. A compiler for a language like C or Pascal is also a potential project of this type. Some past students have done projects related to databases and processing SQL. Another possible project might relate to pattern matching and manipulating XML. Lisp, Pascal, and C usually result in the most straight forward projects." I am very interested in web technologies, and have some experience with PHP, MySql, JavaScript, etc. and I would like to do something web oriented, but I'm having trouble coming up with any ideas. I also want this to be a worthwhile project that could have some significance, instead of just doing the same thing as everyone else in class. Any ideas? Thanks! EDIT: I really like the idea of a Latex to XHTML/MathML translator, and I passed the idea to my instructor, in which he wrote back: "I think the idea is interesting, my question (and yours) is whether it is appropriate. I think of LateX as a low-level mark-up language. I'm wondering if converting this to XHTML or MathML is really a change in levels and complexity. I think you can make your point with a little more discussion and some examples. You might also think of some other mark-up constructs which made it easier to describe equations." Any ideas on how to convince him this may be appropriate, or any extensions of this idea that could work for the goals of my project? Thanks for all the responses so far!
I finished this course last semester :) IMHO the best way to go is to build an expression evaluator. build the simplest expression evaluator you can. Then add these features in order as many as you like: **1**- constant symbols, just place holders for variables. your evaluator should ask for their values after parsing the expression. **2**- imperative-style variables. Like variables in any imperative language, where the user can change the value of a symbol anywhere in code. **3**- simple control-statements. 'if-else' and pretest while loop are the simplest to consider. **4**- arrays. if you really want your expression evaluator to be really like a programming language. It would be interesting if you add variable dimension arrays to your 'language'. you have to build a [generic mapping function for your arrays](http://en.wikipedia.org/wiki/Row-major_order). Now you got a real programming language. To be a useful one, you might add subroutines. so the list continuous: **5**- subroutines. This is little harder than previous features, but it should not be impossible :) **6**- build a simple math library for your new language in your language it self! and that is the fun part in my opinion ;) [Sebest book](http://www.aw-bc.com/sebesta/) is a good book to overview famous imperative programming languages.
Hm, neat! Maybe: `1.` A web-based language interpreter. eg, a very simple assembly interpreter in javascript, or a PHP-based C interpreter (PHP script reads C code, and executes it in some sort of sandboxed kind of way. Obviously it would only be able to implement a small subset of the C language) `2.` Maybe some automated way to transform PHP data structures (like PHP arrays) into SQL queries, and vice versa. That kind of stuff has already been done, but you might be able to do something which (for example) takes an SQL query and creates the array datastructure that would be needed to "hold" the information returned by the SQL. It could support complex things like JOINS and GROUP BYs. `3.` Maybe a C-to-PHP compiler? (or a PHP-to-C compiler, to be able to run simple PHP code natively. Use this with any combination of languages) edit: `4.` Maybe a regex-to-C parser. That is, something that takes a regex, and generates C code to match that pattern. Or something which takes a regex, and converts it into an FSM which represents the "mathematical" translation of that expression. Or the opposite - something which takes an FSM for a CFL and generates the perl-syntax regex for it. `5.` Maybe an XML-to-PHP/MySQL parser. eg, an XML file might contain information about a database and fields, and then your program creates the SQL to create those tables, or the HTML/PHP code for the forms. Best of luck!
Looking for ideas on a computer science course project
[ "", "php", "xml", "parsing", "compiler-construction", "computer-science", "" ]
I want to modify a C program to make some of the files it creates hidden in Windows. What Windows or (even better) POSIX API will set the hidden file attribute?
You can do it by calling SetFileAttributes and setting the FILE\_ATTRIBUTE\_HIDDEN flag. See <http://msdn.microsoft.com/en-us/library/aa365535%28VS.85%29.aspx> This is not POSIX though. To create a 'hidden' file under a normal POSIX system like Linux, just start a filename with a dot (.).
Windows and UNIX-like systems have different views on what exactly is a hidden file. On UNIX-likes conventionally file names starting with a dot are considered "hidden". Windows file systems on the other hand have a "hidden" attribute for files. So for POSIX you should probably just create your files with a starting dot in the file name. On Windows you can use the [SetFileAttributes](http://msdn.microsoft.com/en-us/library/aa365535.aspx) function.
Hide a file or directory using the Windows API from C
[ "", "c++", "c", "windows", "file", "filesystems", "" ]
I'm looking for a good C++ library to give me functions to solve for large cubic splines (on the order of 1000 points) anyone know one?
Try the Cubic B-Spline library: * <https://github.com/NCAR/bspline> and ALGLIB: * <http://www.alglib.net/interpolation/spline3.php>
Write your own. Here is `spline()` function I wrote based on excellent [wiki algorithm](http://en.wikipedia.org/w/index.php?title=Spline_%28mathematics%29&oldid=288288033#Algorithm_for_computing_natural_cubic_splines): ``` #include<iostream> #include<vector> #include<algorithm> #include<cmath> using namespace std; using vec = vector<double>; struct SplineSet{ double a; double b; double c; double d; double x; }; vector<SplineSet> spline(vec &x, vec &y) { int n = x.size()-1; vec a; a.insert(a.begin(), y.begin(), y.end()); vec b(n); vec d(n); vec h; for(int i = 0; i < n; ++i) h.push_back(x[i+1]-x[i]); vec alpha; alpha.push_back(0); for(int i = 1; i < n; ++i) alpha.push_back( 3*(a[i+1]-a[i])/h[i] - 3*(a[i]-a[i-1])/h[i-1] ); vec c(n+1); vec l(n+1); vec mu(n+1); vec z(n+1); l[0] = 1; mu[0] = 0; z[0] = 0; for(int i = 1; i < n; ++i) { l[i] = 2 *(x[i+1]-x[i-1])-h[i-1]*mu[i-1]; mu[i] = h[i]/l[i]; z[i] = (alpha[i]-h[i-1]*z[i-1])/l[i]; } l[n] = 1; z[n] = 0; c[n] = 0; for(int j = n-1; j >= 0; --j) { c[j] = z [j] - mu[j] * c[j+1]; b[j] = (a[j+1]-a[j])/h[j]-h[j]*(c[j+1]+2*c[j])/3; d[j] = (c[j+1]-c[j])/3/h[j]; } vector<SplineSet> output_set(n); for(int i = 0; i < n; ++i) { output_set[i].a = a[i]; output_set[i].b = b[i]; output_set[i].c = c[i]; output_set[i].d = d[i]; output_set[i].x = x[i]; } return output_set; } int main() { vec x(11); vec y(11); for(int i = 0; i < x.size(); ++i) { x[i] = i; y[i] = sin(i); } vector<SplineSet> cs = spline(x, y); for(int i = 0; i < cs.size(); ++i) cout << cs[i].d << "\t" << cs[i].c << "\t" << cs[i].b << "\t" << cs[i].a << endl; } ```
Are there any good libraries for solving cubic splines in C++?
[ "", "c++", "spline", "" ]
Can anyone explain the actual use of **method hiding** in C# with a valid example ? If the method is defined using the `new` keyword in the derived class, then it cannot be overridden. Then it is the same as creating a fresh method (other than the one mentioned in the base class) with a different name. Is there any specific reason to use the `new` keyword?
C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus: ``` using System; namespace Polymorphism { class A { public void Foo() { Console.WriteLine("A::Foo()"); } } class B : A { public new void Foo() { Console.WriteLine("B::Foo()"); } } class Test { static void Main(string[] args) { A a; B b; a = new A(); b = new B(); a.Foo(); // output --> "A::Foo()" b.Foo(); // output --> "B::Foo()" a = new B(); a.Foo(); // output --> "A::Foo()" } } } ```
One use I sometimes have for the new keyword is for 'poor mans property covariance' in a parallell inheritance tree. Consider this example: ``` public interface IDependency { } public interface ConcreteDependency1 : IDependency { } public class Base { protected Base(IDependency dependency) { MyDependency = dependency; } protected IDependency MyDependency {get; private set;} } public class Derived1 : Base // Derived1 depends on ConcreteDependency1 { public Derived1(ConcreteDependency1 dependency) : base(dependency) {} // the new keyword allows to define a property in the derived class // that casts the base type to the correct concrete type private new ConcreteDependency1 MyDependency {get {return (ConcreteDependency1)base.MyDependency;}} } ``` The inheritance tree Derived1 : Base has a 'parallell dependency' on ConcreteDependency1 : IDependency'. In the derived class, I know that MyDependency is of type ConcreteDependency1, therefore I can hide the property getter from the base class using the new keyword. EDIT: see also [this blog post by Eric Lippert](http://blogs.msdn.com/ericlippert/archive/2008/05/21/method-hiding-apologia.aspx) for a good explanation of the new keyword.
method hiding in c# with a valid example. why is it implemented in the framework? what is the Real world advantage?
[ "", "c#", ".net", "oop", "inheritance", "polymorphism", "" ]
I'm new to Python and programming in general (a couple of weeks at most). Concerning Python and using modules, I realise that functions can imported using `from a import *`. So instead of typing ``` a.sayHi() a.sayBye() ``` I can say ``` sayHi() sayBye() ``` which I find simplifies things a great deal. Now, say I have a bunch of *variables* that I want to use across modules and I have them all defined in one python module. How can I, using a similar method as mentioned above or an equally simple one, import these variables. I don't want to use `import a` and then be required to prefix all my variables with `a.`. The following situation would by ideal: a.py ``` name = "Michael" age = 15 ``` b.py ``` some_function if name == "Michael": if age == 15: print("Simple!") ``` Output: ``` Simple! ```
You gave the solution yourself: `from a import *` will work just fine. Python does not differentiate between functions and variables in this respect. ``` >>> from a import * >>> if name == "Michael" and age == 15: ... print('Simple!') ... Simple! ```
Just for some context, most linters will flag `from module import *` with a warning, because it's prone to namespace collisions that will cause headaches down the road. Nobody has noted yet that, as an alternative, you can use the ``` from a import name, age ``` form and then use `name` and `age` directly (without the `a.` prefix). The `from [module] import [identifiers]` form is more future proof because you can easily see when one import will be overriding another. Also note that "variables" aren't different from functions in Python in terms of how they're addressed -- every identifier like `name` or `sayBye` is pointing at some kind of object. The identifier `name` is pointing at a string object, `sayBye` is pointing at a function object, and `age` is pointing at an integer object. When you tell Python: ``` from a import name, age ``` you're saying "take those objects pointed at by `name` and `age` within module `a` and point at them in the current scope with the same identifiers". Similarly, if you want to point at them with different identifiers on import, you can use the ``` from a import sayBye as bidFarewell ``` form. The same function object gets pointed at, except in the current scope the identifier pointing at it is `bidFarewell` whereas in module `a` the identifier pointing at it is `sayBye`.
Python: How can I import all variables?
[ "", "python", "variables", "import", "module", "" ]
If you try to pass the username/password to OpenVPN from a file via the --auth-user-pass switch, you get the following error: ``` "Sorry, 'Auth' password cannot be read from a file." ``` At least they're polite. So our workaround was to programmatically write to "standard in" when we get the Auth Username: and Auth Password: prompts (this is in C#). Something with the timing isn't 100% reliable, so I was looking for a way to pass the credentials to OpenVPN in a different way and came across this post: [OpenVPN Post](http://forum.mikrotik.com/viewtopic.php?f=2&t=26211) It says you can recompile the source with a --enable-password-save option. Has anyone been able to do this? My final question is: How can I pass an auth username/password to openvpn.exe on the client side? And does OpenVPNGUI somehow do this (maybe we can copy what they do)?
It turns out the problem wasn't with standard in. I was using some locking where if the process exited in the middle of writing to standard in, there could be a deadlock. There is no issue sending the password in this manner.
NOTE! param **auth-user-pass** not work if start by GUI "C:\Program Files\OpenVPN\config\name.ovpn" Made start file start\_openvpv.cmd (+ link to with "run as admin") with content: ``` cd C:\Users\Name\Documents\VPN "C:\Program Files\OpenVPN\bin\openvpn.exe" --config C:\Users\Name\Documents\VPN\myvpnconfig.ovpn --auth-user-pass "C:\Users\Name\Documents\VPN\pass.txt" ``` pass.txt: ``` yourusername yourpassword ``` OR put line to name.ovpn, as in upper messege: ``` auth-user-pass pass.txt ``` +start\_openvpv.cmd: ``` cd C:\Users\Name\Documents\VPN "C:\Program Files\OpenVPN\bin\openvpn.exe" --config C:\Users\Name\Documents\VPN\myvpnconfig.ovpn ```
OpenVPN --auth-user-pass FILE option on Windows
[ "", "c#", "windows", "credentials", "openvpn", "" ]
I'm using matplotlib to generate a (vertical) barchart. The problem is my labels are rather long. Is there any way to display them vertically, either in the bar or above it or below it?
Do you mean something like this: ``` >>> from matplotlib import * >>> plot(xrange(10)) >>> yticks(xrange(10), rotation='vertical') ``` ? In general, to show any text in matplotlib with a vertical orientation, you can add the keyword `rotation='vertical'`. For further options, you can look at help(matplotlib.pyplot.text) The yticks function plots the ticks on the y axis; I am not sure whether you originally meant this or the ylabel function, but the procedure is alwasy the same, you have to add rotation='vertical' Maybe you can also find useful the options 'verticalalignment' and 'horizontalalignment', which allows you to define how to align the text with respect to the ticks or the other elements.
In Jupyter Notebook you might use something like this ``` %matplotlib inline import matplotlib.pyplot as plt import numpy as np plt.xticks(rotation='vertical') plt.plot(np.random.randn(100).cumsum()) ``` or you can use: ``` plt.xticks(rotation=90) ```
Barchart with vertical ytick labels
[ "", "python", "matplotlib", "bar-chart", "yaxis", "" ]
I just moved from .net development to LINUX MONO development... and i don have much experience with linux dev earlier.. 1. I have a requirement to create a background service (like windows services) in mono c#.. is it possible.. 2. And is it possible to access the LINUX native APIs from mono c#. (like winAPI calls from win c#)..
1. Mono ships with a Windows Service compatible system called mono-service. * The Unix word for service is Daemon. Regular daemons can be found in /etc/init.d/ and are installed into the runlevel they are supposed to run in by being symlinked from /etc/rc.\* directories. 2. Just use p/invoke like you normally would. You can also check out the source code of some other simple mono-based projects like Banshee to see how they do p/invokes on Linux. Just search for banshee on google.com/codesearch.
I use scripts, so I can capture the exit code and use it to perform automated updates and things. It also restarts itself if it crashes, and e-mails you when it restarts with the last x lines of the log file. /etc/init.d/MyMonoApp ``` #!/bin/sh #/etc/init.d/MyMonoApp # APP_NAME="MyMonoApp" APP_PATH="/home/mono/MyMonoApp" APP_USER=mono case "$1" in start) echo "Starting $APP_NAME" start-stop-daemon --start \ --background \ --make-pidfile \ --pidfile /var/run/$APP_NAME.pid \ --chuid $APP_USER \ --exec "$APP_PATH/$APP_NAME" ;; stop) echo "Stopping $APP_NAME" start-stop-daemon -o --stop \ --pidfile /var/run/$APP_NAME.pid ;; *) echo "Usage: /etc/init.d/$APP_NAME {start|stop}" exit 1 ;; esac exit 0 ``` /home/mono/MyMonoApp ``` #!/bin/sh #!/home/mono/MyMonoApp APP_NAME=`basename $0` APP_DIR=`dirname $0` HOSTNAME=`hostname` cd $APP_DIR tail --lines=300 output.log | mail -s "MyMonoApp $HOSTNAME:$APP_NAME STARTED" "me@email.com" exitcode=0 until [ $exitcode -eq 9 ] do startdate="$(date +%s)" /usr/local/bin/mono MyMonoApp.exe $HOSTNAME:$APP_NAME > output.log exitcode=$? enddate="$(date +%s)" echo "EXIT CODE = $exitcode" >> output.log cp -f output.log output.log.1 elapsed_seconds="$(expr $enddate - $startdate)" echo "Elapsed seconds $elapsed_seconds" subject="EXIT CODE: $exitcode" echo "BASH: Exit Code = $exitcode" if [ $exitcode -eq 6 ] #Restart then subject="RESTART" elif [ $exitcode -eq 7 ] #Previous version then subject="PREVIOUS VERSION" cp -fv MyMonoApp.exe_previous MyMonoApp.exe elif [ $exitcode -eq 8 ] #Update then subject="SOFTWARE UPDATE" cp -fv MyMonoApp.exe MyMonoApp.exe_previous mv -fv MyMonoApp.exe_new MyMonoApp.exe elif [ $exitcode -eq 9 ] #Shutdown then subject="SHUTDOWN" fi if [ $elapsed_seconds -ge 10 ] #been running for longer than 10 seconds then tail --lines=300 output.log | mail -s "MyMonoApp $HOSTNAME:$APP_NAME $subject" "me@email.com" sleep 1 # tiny delay to let things settle else sleep 5 # delay to protect against eating the CPU resourses fi done ``` Note: if you close the app using the init.d script, it will kill the process, rather than signal it to cleanly close.
Windows like services development in LINUX using MONO?
[ "", "c#", "linux", "mono", "service", "" ]
I have a Windows Forms application that currently loads a database on startup. The flow is like this: Program.cs => Application.Run(new MainForm()); => MainForm Constructor => Open Database So basically MainForm holds all the bits and pieces that make the application run, while Program.cs is just a stub. Currently, the name of the database that is loaded is hardcoded, and I want to add functionality to specify the name of the database to load through the command line. At the same time, I want to add the ability to do some Unit Testing or even Dependency Injection later on, so I wonder which approach is recommended? * Change the constructor of MainForm to accept some parameters. Then change Program.cs to read the command line and change the call to `Application.Run(new MainForm());` accordingly * Leave Program.cs and the Signature of the constructor untouched and check the command line in the constructor of MainForm Method one seems to be cleaner as it would allow i.e. a Test runner to create MainForm with a test database, but as I'm usually not a WinForms developer I do not know if there could be side effects of not having a default constructor on the Main Form or if there is a better approach?
I think this comes down to a separation of concerns. The Program class should be concerned with application level details and the MainForm with form details. This then says to me that that Program should parse the command line and pass the names to the form. You could still leave the default constructor on the form and either mark it private or throw an error if you execute it. Or you could still have Program.cs use the default constructor to create the form and simply inject the database name with paramters (so it's either constructor injection or parameter injection), something like ``` form = new MainForm(); form.DbName = "foo"; Application.Run(form); ```
Currently, I configure a Dependency Injection Container within Program.cs and then say ``` Application.Run(container.GetInstance<Form>()); ``` The application we are currently developing has about 80 different application parts. Our MainForm currently clocks in at 95 lines of code and has dependencies to an *IApplicationModule* (an interface whose only property is to return a "TopControl"), a *MenuStripModule*, a *StatusBarModule* and a *Session* object.
Initialization code in a WinForms App - Program.cs or MainForm?
[ "", "c#", ".net", "winforms", "" ]
``` const std::string::size_type cols = greeting.size() + pad * 2 + 2; ``` Why `string::size_type`? `int` is supposed to work! it holds numbers!!!
A short holds numbers too. As does a signed char. But none of those types are guaranteed to be large enough to represent the sizes of *any* strings. `string::size_type` guarantees just that. It is a type that is big enough to represent the size of a string, no matter how big that string is. For a simple example of why this is necessary, consider 64-bit platforms. An int is typically still 32 bit on those, but you have far more than 2^32 bytes of memory. So if a (signed) int was used, you'd be unable to create strings larger than 2^31 characters. size\_type will be a 64-bit value on those platforms however, so it can represent larger strings without a problem.
The example that you've given, ``` const std::string::size_type cols = greeting.size() + pad * 2 + 2; ``` is from [Accelerated C++ by Koenig](https://rads.stackoverflow.com/amzn/click/com/020170353X). He also states the reason for his choice right after this, namely: > The std::string type defines size\_type to be the name of the > appropriate type for holding the number of characters in a string. Whenever we need a local > variable to contain the size of a string, we should use std::string::size\_type as the type of that variable. > > The reason that we have given cols a type of std::string::size\_type is > to ensure that cols is capable of containing the number of characters > in greeting, no matter how large that number might be. We could simply > have said that cols has type int, and indeed, doing so would probably > work. However, the value of cols depends on the size of the input to > our program, and we have no control over how long that input might be. > It is conceivable that someone might give our program a string so long > that an int is insufficient to contain its length.
string::size_type instead of int
[ "", "c++", "string", "int", "size-type", "" ]
I want to write a web version of an image processing application writen using winforms before. Which is prefered silverlight or xbab application? what is main differences of them?
* Silverlight applications will work on Mac and eventually on Linux. * Your users won't need to install full .NET framework runtime, instead they will need only smaller Silverlight plugin. * Silverlight is subset of WPF, so many features from WPF are simply not available for Silverlight. * Microsoft seems to be more dedicated to Silverlight. So I would definitely do it in Silverlight. The only good thing about WPF is that it has more features and is more mature. Your other options are JavaFX, Flash/Flex and Canvas tag in HTML5
I think Silverlight will eventually fade XBAP out, as said before it doesn't need the whole .net framework on client's box, and also works accross platform & browsers, recently it also introduced more languages like Iron Ruby & Iron Python, also it has better support for video streaming
Silverlight vs webbrowser application (.xbab)?
[ "", "c#", "web-applications", "" ]
Let's say there's an application which should create its own tables in main database if they are missing (for example application is run for a very first time). What way of doing this is more flexible, scalable and, let's say, more suitable for commercial product? If I code it all no additional files (scripts) are needed. User won't be able to make something stupid with them and then complain that application doesn't work. But when something will change in db structure I have to code patching part and user will have to install new binary (or just replace the old one). Scripting solution would be a few lines of code for just run all scripts from some directory and bunch of scripts. Binary could be the same, patching would be applied automatically. But new scripts also have to be deployed to user at some point. So, what would you recommend? Application will be coded in c#, database for now will be under SQLServer 2005 but it may change in the future. Of course, drawing application and database handling part can be separated into two binaries/assemblies but it doesn't solves my code vs. scripts dilemma.
Check [Wizardby](http://code.google.com/p/octalforty-wizardby/): it provides a special language (somewhat close to SQL DDL) to express changes to your database schema: ``` migration "Blog" revision => 1: type-aliases: type-alias N type => String, length => 200, nullable => false, default => "" defaults: default-primary-key ID type => Int32, nullable => false, identity => true version 20090226100407: add table Author: /* Primary Key is added automatically */ FirstName type => N /* “add” can be omitted */ LastName type => N EmailAddress type => N, unique => true /* "unique => true" will create UQ_EmailAddress index */ Login type => N, unique => true Password type => Binary, length => 64, nullable => true index UQ_LoginEmailAddress unique => true, columns => [[Login, asc], EmailAddress] add table Tag: Name type => N add table Blog: Name type => N Description type => String, nullable => false add table BlogPost: Title type => N Slug type => N BlogID references => Blog /* Column type is inferred automatically */ AuthorID: reference pk-table => Author ``` These `version` blocks are basically changes you want to be applied to your database schema. Wizardby can also be integrated into your build process, as well as into your application: on each startup in can attempt to upgrade database to the most recent version. Thus your application will always work with most up-to-date schema version. It can also be integrated into your setup process: Wizardby can generate SQL scripts to alter database schema, and these can be run as part of your setup process.
I would usually want to keep my installation code separate from my application code. You will definitely want your application performing some sort of version check against the database to ensure it has the proper structure it requires before running though. The basic setup I would follow is this: 1. Use scripts with each released version to make schema changes to the deployed database. 2. Have something in your database to track current version of the database, perhaps a simple version table that tracks which scripts have been run against it. It's simpler to look for the version script than to check the schema every time and search for all the tables and fields you need. 3. Have your application check the database version marker to ensure it meets the application's version. Log an error that will let the user know they have to update their database with the database scripts. That should keep your application code clean, but make sure database and app are in sync.
What approach for creating and editing database structure: code or scripts?
[ "", "c#", "sql-server", "database", "" ]
had a bit of confusion going around in work earlier. Thought id run it by yous to see if anyone knows wats going on. Were working on an internal administration system for our client, and its rite about to launch. Its comprised of TWO MySQL databases on the server [db\_1 and db\_2] and a PHP front end. [Both databases contain several tables]. There are maybe 90 different PHP files, some of which require a connection to our databases and ALL of these connections are made via a single PHP function which explicitly connects to the first database mentioned above [db\_1] and supplies the login and password. And this works fine. However, our second database, db\_2, does not seem to require its own login and password to access its contents. As soon as we connect to db\_1, we seem to have full access to db\_2, as long as we use the Full-Name for our tables [ie: db\_2.usersTable] -> ("SELECT \* FROM db\_2.usersTable WHERE..."). And this is what was causing much confusion. My question is this: Once you connect to a database on a server, do you have access to other databases on that server, or are we overlooking something??? Any feedback greatly appreciated lads...
You usually don't access a database server by a specific database, but by a user that has access to one or more databases. for example: ``` mysql_connect("localhost", "user", "password") or die(mysql_error()); ``` connects to the server and not a specific database. Once connected to the database server you have access to all databases for which that user has permission. You just need to specify the database name in your queries if there are multiple databases that aren't the default. ``` mysql_select_db("myTable") or die(mysql_error()); ``` sets myTable as the default, but you can still access other tables that the user has permission to.
I might be wrong, but doesn't PHP only connect and authenticate with the MySQL *server* with a user? And thus, based on that user's permissions, PHP can select any database that user has access to. I would check the permissions for the user you are connecting with...
php mysql connection confusion
[ "", "php", "mysql", "" ]
I have code written in .NET that only fails when installed as a Windows service. The failure doesn't allow the service to even start. I can't figure out how I can step into the OnStart method. *[How to: Debug Windows Service Applications](http://msdn.microsoft.com/en-us/library/7a50syb3%28VS.80%29.aspx)* gives a tantalizing clue: > Attaching to the service's process allows you to debug most but not all of the service's code; for example, because the service has already been started, you cannot debug the code in the service's OnStart method this way, or the code in the Main method that is used to load the service. **One way to work around this is to create a temporary second service in your service application that exists only to aid in debugging. You can install both services, and then start this "dummy" service to load the service process.** Once the temporary service has started the process, you can then use the Debug menu in Visual Studio to attach to the service process. However, I'm not clear how it is exactly that you are supposed to create the dummy service to load the service process.
One thing you could do as a temporary workaround is to launch the debugger as the first line of code in the OnStart ``` System.Diagnostics.Debugger.Launch() ``` This will prompt you for the debugger you'd like to use. Simply have the solution already open in Visual Studio and choose that instance from the list.
I tend to add a method like this: ``` [Conditional("DEBUG")] private void AttachDebugger() { Debugger.Break(); } ``` it will only get called on Debug builds of you project and it will pause execution and allow you to attach the debugger.
How to debug the .NET Windows Service OnStart method?
[ "", "c#", ".net", "debugging", "" ]
I have made a simple webcam based application that detects the "edges of motion" so draws a texture that shows where the pixels of the current frame are significantly different to the previous frame. This is my code: ``` // LastTexture is a Texture2D of the previous frame. // CurrentTexture is a Texture2D of the current frame. // DifferenceTexture is another Texture2D. // Variance is an int, default 100; Color[] differenceData = new Color[CurrentTexture.Width * CurrentTexture.Height]; Color[] currentData = new Color[CurrentTexture.Width * CurrentTexture.Height]; Color[] lastData = new Color[LastTexture.Width * LastTexture.Height]; CurrentTexture.GetData<Color>(currentData); LastTexture.GetData<Color>(lastData); for (int i = 0; i < currentData.Length; i++) { int sumCD = ColorSum(currentData[i]); // ColorSum is the same as c.R + c.B + c.G where c is a Color. int sumLD = ColorSum(lastData[i]); if ((sumCD > sumLD - Variance) && (sumCD < sumLD + Variance)) differenceData[i] = new Color(0, 0, 0, 0); // If the current pixel is within the range of +/- the Variance (default: 100) variable, it has not significantly changes so is drawn black. else differenceData[i] = new Color(0, (byte)Math.Abs(sumCD - sumLD), 0); // This has changed significantly so is drawn a shade of green. } DifferenceTexture = new Texture2D(game1.GraphicsDevice, CurrentTexture.Width, CurrentTexture.Height); DifferenceTexture.SetData<Color>(differenceData); LastTexture = new Texture2D(game1.GraphicsDevice,CurrentTexture.Width, CurrentTexture.Height); LastTexture.SetData<Color>(currentData); ``` Is there a way to offload this calculation to the GPU using shaders (it can go at about 25/26 fps using the above method, but this is a bit slow)? I have a basic understanding of how HLSL shaders work and don't expect a full solution, I just want to know if this would be possible and how to get the "difference" texture data from the shader and if this would actually be any faster. Thanks in advance.
Regarding your comment above about deciding to use a dual thread approach to your problem, check out the .Net Parallel Extensions CTP from Microsoft. [microsoft.com](http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3&displaylang=en) If you're not planning on deploying to an XBox360, this library works great with XNA, and I've seen massive speed improvements in certain loops and iterations. You would basically only have to change a couple lines of code, for example: ``` for (int i = 0; i < currentData.Length; i++) { // ... } ``` would change to: ``` Parallel.For(0, currentData.Length, delegate(int i) { // ... }); ``` to automatically make each core in your processor help out with the number crunching. It's fast and excellent. Good luck!
You could sample two textures inside the pixel shader, then write the difference out as the colour value. If you set up a [Render Target](http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series3/Render_to_texture.php), the colour information you ouput from the shader will be stored in this texture instead of the framebuffer. I don't know what sort of speed gain you'd expect to see, but that's how I'd do it. \*edit - Oh and I forgot to say, be aware of the sampling type you use, as it will affect the results. If you want your algorithm to directly translate to the GPU, use point sampling to start with.
Is it possible to use a shader to find the "difference" between two textures? (XNA/HLSL)
[ "", "c#", "xna", "webcam", "hlsl", "shader", "" ]
I read about **Compound property names** in the "[The Spring Framework (2.5) - Reference Documentation - chapter 3.3.2.7](http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-compound-property-names)" Can i use the same concept to set values of properties? Can i use a compound string as a value expression? ``` <bean id="service1" class="a.b.c.Service1Impl" scope="prototype"> <property name="service2" ref="service2"/> <property name="service2.user" value="this-service1-instance.user"/> </bean> <bean id="service2" class="a.b.c.Service2Impl" scope="prototype"> ... </bean> ``` User is a property of a.b.c.Service1Impl which is **not** in control of Spring. I want to forward this property to a.b.c.Service2Impl.
Rather than use a plain old factory bean, rather use a factory method to create the bean of the property and then inject that result... iow in your case, it would look something like [this](http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-factory-class)... ``` <!-- the bean to be created via the factory bean --> <bean id="exampleBean" factory-bean="serviceLocator" factory-method="createInstance"/> ``` So the bean of id is created by calling createInstance on bean serviceLocator. Now spring does not support nested properties out of the box, though you could look at creating a custom editors which might provide that support - possible but tricky. Possibly not worth the effort. One mechanism you could look at using is nesting using the factory-bean factory-method technique... Something like: ``` <bean id="c" class="C" /> <bean id="b" factory-bean="c" factory-method="getB"/> <bean id="a" factory-bean="b" factory-method="getA"/> ``` This will effectively expose: a.b.c where C has a method getB and A has a method getB
I had to do something similar, and I'm afraid it's not possible. I had to write a `[FactoryBean][1]` to expose the property. It would look something like this: ``` public class UserFactory implements BeanFactory { private Service2 service2; // ... setter and getter for service2 public Object getObject() { return getService2().getUser(); } public Class getObjectType() { return User.class; } public boolean isSingleton() { // Since it's a prototype in your case return false; } } ``` Come to think of it, in your case, you'd probably define the factory itself as a prototype, in which case your `isSingleton()` may return true, you'll need to play around with this a little bit.
Are there Compound property values in Spring
[ "", "java", "spring", "" ]
This seems like a simple question, but I haven't been able to find the answer online via many Google searches. I have a C# web service and, when I visit its ASMX page in the browser, for a particular method it always has the following: "The following is a sample SOAP 1.1 request and response. The placeholders shown need to be replaced with actual values." Likewise for SOAP 1.2 and HTTP POST. What I want to know is *how* I replace the placeholders shown, which are things like: ``` <myParameter>string</myParameter> ``` Where 'string' is the placeholder. And in the response: ``` <xsd:schema>schema</xsd:schema>xml ``` Where 'schema' and 'xml' are the placeholders. I've been using another web service that has these placeholders filled out with example values for the parameters and responses, and I would like to define such examples for my own web methods, too. I was able to describe the entire method with the following: ``` [WebMethod(Description="Does awesome things.")] ``` But I have not found such a thing for the individual parameters of a web method.
By default DefaultWsdlHelpGenerator.aspx is called to generate the "help" page. You can set another (or modified) template with the [wsdlHelpGenerator Element](http://msdn.microsoft.com/en-us/library/ycx1yf7k(VS.71).aspx) in your web.config file.
Why would you want to do that? That page you see in the browser when hitting your asmx is just giving sample requests and reponses. If you want to get data using those examples, replace the placholder values in the request with what you are querying from the service, and POST to it... Edit: I mean, if you really need to replace those placholder values, write code in your service to determine when someone does a GET (implying viewing from a browser), and play with the response, changing the placeholder values to whatever you require.
Describing ASMX web service WebMethod parameters
[ "", "c#", "web-services", "documentation", "asmx", "" ]
I am trying to come up with a linq query to convert an `IEnumerable<int>` to another `IEnumerable<int>`, where each int in the result is the sum of all the ints up to that position from the initial list: Given `int[] a` I need `int[] b` Where `b[0] = a[0], b[1] = a[0] + a[1], b[2] = a[0] + a[1] + a[2]` and so on Alternatively, the sums above can be written as `b[1] = b[0] + a[1], b[2] = b[1] + a[2]` and so on, but I don't see how that would help. I can, of course, do this with a `for` loop, but I obtain the a[] sequence from a query and I thought it would look nicer if I continue that query instead of suddenly adding a `for` there :)
Well, you can do it with side effects easily enough, although it's pretty icky... ``` int sum = 0; int[] b = a.Select(x => (sum += x)).ToArray(); ``` It would be nice if the framework provided a sort of "running aggregate" to encapsulate this, but it doesn't as far as I'm aware.
I wrote a function to do this a while ago. It's similar to Haskell's [scanl](http://www.zvon.org/other/haskell/Outputprelude/scanl_f.html) function. ``` public static IEnumerable<TResult> Scan<T, TResult>( this IEnumerable<T> source, Func<T, T, TResult> combine) { using (IEnumerator<T> data = source.GetEnumerator()) if (data.MoveNext()) { T first = data.Current; yield return first; while (data.MoveNext()) { first = combine(first, data.Current); yield return first; } } } int[] b = a .Scan((running, current) => running + current) .ToArray(); ```
How to compute a running sum of a series of ints in a Linq query?
[ "", "c#", "linq", "" ]
How can I show "√" (tick symbol) in label text?
This code will do it for you: ``` LblTick.Text = ((char)0x221A).ToString(); ``` Edit: or even easier: ``` lblTick.Text = "\u221A"; ``` Edit 2: And, as pointed out in a comment, that code (221A) is actually a square root symbol, not a tick. To use the true tick mark, you can use the following: ``` lblTick.Text = "\u2713"; ``` or for a heavy tick mark, you can use the following (but you may get font issues with this one): ``` lblTick.Text = "\u2714"; ``` (Credit to @Joey for that comment!)
You can also use ``` lblTick.Text="\u2714"; ```
Show tick symbol on label
[ "", "c#", "unicode", "" ]
Directions from my supervisor: "I want to avoid putting any logic in the `models.py`. From here on out, let's use that as only classes for accessing the database, and keep all logic in external classes that use the models classes, or wrap them." I feel like this is the wrong way to go. I feel that keeping logic out of the models just to keep the file small is a bad idea. If the logic is best in the model, that's where it really should go regardless of file size. So is there a simple way to just use includes? In PHP-speak, I'd like to propose to the supervisor that we just have `models.py` include() the model classes from other places. Conceptually, this would allow the models to have all the logic we want, yet keep file size down via increasing the number of files (which leads to less revision control problems like conflicts, etc.). So, is there a simple way to remove model classes from the models.py file, but still have the models work with all of the Django tools? Or, is there a completely different yet elegant solution to the general problem of a "large" models.py file? Any input would be appreciated.
Django is designed to let you build many small applications instead of one big application. Inside every large application are many small applications struggling to be free. If your `models.py` feels big, you're doing too much. Stop. Relax. Decompose. Find smaller, potentially reusable small application components, or pieces. You don't have to *actually* reuse them. Just think about them as potentially reusable. Consider your upgrade paths and decompose applications that you might want to replace some day. You don't have to *actually* replace them, but you can consider them as a stand-alone "module" of programming that might get replaced with something cooler in the future. We have about a dozen applications, each `model.py` is no more than about 400 lines of code. They're all pretty focused on less than about half-dozen discrete class definitions. (These aren't hard limits, they're observations about our code.) We decompose early and often.
It's natural for model classes to contain methods to operate on the model. If I have a Book model, with a method `book.get_noun_count()`, that's where it belongs--I don't want to have to write "`get_noun_count(book)`", unless the method actually intrinsically belongs with some other package. (It might--for example, if I have a package for accessing Amazon's API with "`get_amazon_product_id(book)`".) I cringed when Django's documentation suggested putting models in a single file, and I took a few minutes from the very beginning to figure out how to split it into a proper subpackage. ``` site/models/__init__.py site/models/book.py ``` `__init__.py` looks like: ``` from .book import Book ``` so I can still write "from site.models import Book". --- > The following is only required for versions prior to Django 1.7, see > <https://code.djangoproject.com/ticket/3591> The only trick is that you need to explicitly set each model's application, due to a bug in Django: it assumes that the application name is the third-to-last entry in the model path. "site.models.Book" results in "site", which is correct; "site.models.book.Book" makes it think the application name is "models". This is a pretty nasty hack on Django's part; it should probably search the list of installed applications for a prefix match. ``` class Book(models.Model): class Meta: app_label = "site" ``` You could probably use a base class or metaclass to generalize this, but I haven't bothered with that yet.
models.py getting huge, what is the best way to break it up?
[ "", "python", "django", "django-models", "models", "" ]
I've got a method that takes a bunch of optional parameters and I'm overloading the method to supply the different combinations of signatures. Intellisense pops up with a bunch of different signatures but I think it looks quite confusing now because there are different combinations I need to provide, not just building up parameters on the end of the method signature. Should I just not overload my method and stick to one signature so that the user of my method has to pass in nulls? It would make the signature clearer but makes the calling code look messier.
Are you restricted to using C# 1-3? C# 4 supports optional parameters and named arguments... Until then, you should probably *either* stick with overloading *or* create a separate class with mutable properties, e.g. ``` FooOptions options = new FooOptions { Name="Jon", Location="Reading" }; Foo foo = new Foo(options); ``` That can all be done in one statement if you want... and if some of the properties are mandatory, then create a single constructor in `FooOptions` which takes all of them. In C# 4 you'd be able to write: ``` Foo foo = new Foo(name: "Jon", location: "Reading"); ``` if the constructor was written as ``` public Foo(string name, int age = 0, string location = null, string profession = null) ``` Named arguments and optional parameters should make it a lot easier to construct immutable types with optional properties in C# 4 :)
Think about params argument of c# method. ``` void test(params object []arg) { .. } ```
Optional parameters
[ "", "c#", ".net", "optional-parameters", "" ]
I like to use the SQL Tools in VS but I would like to have some intellisense for SQL, with sql manager I can get the Redgate SQL prompt but I would like to stay in VS, any Ideas? Edit: is there anything other then Redgate SQL prompt? that dose error checking like the way R# or dev express?
Red-Gate SQL Prompt (at least more recent versions, I believe 3.x and up) also works inside Visual Studio. I don't think you need another extra tool, really. See the [Red-Gate SQL Prompt feature page](http://www.red-gate.com/products/SQL_Prompt/index.htm) It says clearly: > Integrates with SSMS, SSMS Express, Query Analyzer and **Visual Studio** Marc
With Red Gate SQL Prompt you also will stay in VS and this product supports now just VS 2008. [SQL Prompt web page](http://www.red-gate.com/products/SQL_Prompt/index.htm) If you don't like it I can propose you to try [SQL Assist](http://roundpolygons.com/) or [SQL Complete](http://www.devart.com/dbforge/sql/sqlcomplete/overview.html). I use this tool and as for me it's really reliable one.
is there a SQL Prompt like plugin for VS 2008
[ "", "sql", "visual-studio", "plugins", "intellisense", "" ]
I've got a function which returns an object of type `Foo`: ``` Foo getFoo(); ``` I know the following will compile and will work, but why would I ever do it? ``` const Foo& myFoo = getFoo(); ``` To me, the following is much more readable, and doesn't force me to remember that C++ allows me to assign an r-value to a const reference: ``` const Foo myFoo = getFoo(); ``` What are the differences between the two? Why would I use the first over the second? Why would I use the second over the first?
Contrary to popular opinion, there is no guarantee that assigning the result of a function returning an object by value to a const reference will result in fewer copies than assigning it to the object itself. When you assign an rvalue to a const reference, the compiler may bind the reference in one of two ways. It may create a new temporary by copying the rvalue and bind the reference to that, or it may bind the reference directly to the rvalue itself. If the compiler is not able to make the 'obvious' optimization to remove the temporary and elide the copy constructor for the return value of `getFoo`, then how likely is it to be able to do the more efficient form of binding an rvalue to a const reference without making a new temporary? One reason to use a const reference would be to make the function more robust against potential slicing. If the return type were actually a type derived from `Foo`, then assigning to a base class const reference would be guaranteed not to slice, even if the compiler did make a temporary object from the rvalue returned by the function. The compiler will also generate the correct call to the derived class destructor *whether or not the destructor in the base class is virtual or not*. This is because the type of the temporary object created is based on the type of the expression being assigned and not on the type of the reference which is being initialized. Note that the issue of how many copies of the return value are made is entirely separate from the *return value optimization* and the *named return value optimization*. These optimizations refer to eliminating the copy of either the rvalue result of evaluating a return expression or of a named local variable into the return value of a function in the body of the function itself. Obviously, in the best possible case, both a return value optimization can be made and the temporary for the return value can be eliminated resulting in no copies being performed on the returned object.
I think [GotW #88](http://herbsutter.wordpress.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/) answers this best
Assigning result of function which returns a Foo to a const Foo&
[ "", "c++", "" ]
I have 3 textboxes to do a check on the entered date. The code I originally had was for one textbox. Is there a way to pass an ID name to the onChange event ``` <asp:TextBox ID="txtDate" runat="server" Width="110px" onChange="checkEnteredDate('txtDate')"></asp:TextBox> function checkEnteredDate(var textBox = new String();) { var inputDate = document.getElementById(textBox); //if statement to check for valid date var formatDate = new Date(inputDate.value); if (formatDate > TodayDate) { alert("You cannot select a date later than today."); inputDate.value = TodayDate.format("MM/dd/yyyy"); } } ```
I actually figured it out. I did the following: ``` ...onChange="checkEnteredDate(this)"... function checkEnteredDate(inputDate) { //if statement to check for valid date var formatDate = new Date(inputDate.value); if (formatDate > TodayDate) { alert("You cannot select a date later than today."); inputDate.value = TodayDate.format("MM/dd/yyyy"); } } ``` getElement was messing me up. Thanks for the suggestions, they brought me in the right direction.
In order to pass the Id of the textbox you'll have to do this in your code behind's Page\_Load: ``` txtDate.Attributes["onchange"] = String.Format("checkEnteredDate('{0}');",txtDate.ClientID); ```
Can i pass the ID name in an onChange event for a textbox?
[ "", "asp.net", "javascript", "" ]
I'm fairly new to php and I am trying to figure how do I set an optional parameter after the first optional parameter? For example I have the following code: ``` function testParam($fruit, $veg='pota',$test='default test'){ echo '<br>$fruit = '.$fruit; echo '<br>$veg = '.$veg; echo '<br>Test = '.$test; } ``` If i make the following calls: ``` echo 'with all parama'; testParam('apple','carrot','some string'); //we get: //with all parama //$fruit = apple //$veg = carrot //Test = some string echo '<hr> missing veg'; testParam('apple','','something'); //we get: //missing veg //$fruit = apple //$veg = //Test = something echo '<hr> This wont work'; testParam('apple',,'i am set'); ``` I want to try make a call so that in the last example I show 'pota' as the default $veg parameter but pass into $test 'i am set'. I guess I can pass 0 into $veg then branch it in the code to say if $veg =0 then use 'pota' but just wondered if there's some other syntax as i cant find anything in php.net about it.
You can't do what you want with just default parameters. The defaults only apply to missing arguments, and only the last argument(s) can be missing. You can either add lines like ``` $vega = $vega ? $vega : 'carrot'; ``` and call the function as ``` testParam('apple',false,'something'); ``` or use the more general technique of passing the parameters in an array with the parameter names as keys. Something like ``` function testparam($parms=false) { $default_parms = array('fruit'=>'orange', 'vega'=>'peas', 'starch'=>'bread'); $parms = array_merge($default_parms, (array) $parms); echo '<br>fruit = $parms[fruit]'; echo '<br>vega = $parms[vega]'; echo '<br>starch = $parms[starch]'; } testparm('starch'=>'pancakes'); //we get: //fruit = orange //vega = peas //starch = pancakes ``` This is a little more verbose but it is also more flexible. You can add parameters and defaults without changing the existing callers.
Unfortunately, you cannot do that in PHP. You have to pass in 0, or `null`, or some other value and then if the value is 0 or `null`, change it to the default value. [Here](https://stackoverflow.com/questions/579331/is-it-possible-to-skip-parameters-that-have-default-values-in-a-php5-function-c) is another question that should give you more information.
How do i set an optional parameter in PHP after the first optional parameter
[ "", "php", "parameter-passing", "optional-parameters", "" ]
I'm using Visual Studio 2008 with C#. I have a .xsd file and it has a table adapter. I want to change the table adapter's command timeout. Thanks for your help.
I have investigated this issue a bit today and come up with the following solution based on a few sources. The idea is to create a base class for the table adapter too inherit which increases the timeout for all commands in the table adapter without having to rewrite too much existing code. It has to use reflection since the generated table adapters don't inherit anything useful. It exposes a public function to alter the timeout if you want to delete what i used in the constructor and use that. ``` using System; using System.Data.SqlClient; using System.Reflection; namespace CSP { public class TableAdapterBase : System.ComponentModel.Component { public TableAdapterBase() { SetCommandTimeout(GetConnection().ConnectionTimeout); } public void SetCommandTimeout(int Timeout) { foreach (var c in SelectCommand()) c.CommandTimeout = Timeout; } private System.Data.SqlClient.SqlConnection GetConnection() { return GetProperty("Connection") as System.Data.SqlClient.SqlConnection; } private SqlCommand[] SelectCommand() { return GetProperty("CommandCollection") as SqlCommand[]; } private Object GetProperty(String s) { return this.GetType().GetProperty(s, BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance).GetValue(this, null); } } } ```
With some small modifications csl's idea works great. ``` partial class FooTableAdapter { /** * <summary> * Set timeout in seconds for Select statements. * </summary> */ public int SelectCommandTimeout { set { for (int i = 0; i < this.CommandCollection.Length; i++) if (this.CommandCollection[i] != null) this.CommandCollection[i].CommandTimeout = value; } } } ``` To use it, just set this.FooTableAdapter.CommandTimeout = 60; somewhere before the this.FooTableAdapter.Fill(); --- If you need to change the timeout on a lot of table adapters, you could create a generic extension method and have it use reflection to change the timeout. ``` /// <summary> /// Set the Select command timeout for a Table Adapter /// </summary> public static void TableAdapterCommandTimeout<T>(this T TableAdapter, int CommandTimeout) where T : global::System.ComponentModel.Component { foreach (var c in typeof(T).GetProperty("CommandCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.Instance).GetValue(TableAdapter, null) as System.Data.SqlClient.SqlCommand[]) c.CommandTimeout = CommandTimeout; } ``` Usage: ``` this.FooTableAdapter.TableAdapterCommandTimeout(60); this.FooTableAdapter.Fill(...); ``` This is a little slower. And there is the possibility of an error if you use it on the wrong type of object. (As far as I know, there is no "TableAdapter" class that you could limit it to.)
How can I change the table adapter's command timeout
[ "", "c#", "dataset", "timeout", "command", "" ]
The following works, I'm just wondering if this is the correct approach to finding the latest value for each audit field. ``` USE tempdb CREATE Table Tbl( TblID Int, AuditFieldID Int, AuditValue Int, AuditDate Date ) GO INSERT INTO Tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(1,10,101,'1/1/2001') INSERT INTO Tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(2,10,102,'1/1/2002') INSERT INTO Tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(3,20,201,'1/1/2001') INSERT INTO Tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(4,20,202,'1/1/2009') SELECT AuditFieldID,AuditValue,AuditDate FROM Tbl A WHERE TblID= (SELECT TOP 1 TblID FROM Tbl WHERE AuditFieldID=A.AuditFieldID ORDER BY AuditDate DESC ) ```
Aggregate/ranking to get key and latest date, join back to get value. This assumes SQL Server 2005+ ``` DECLARE @tbl Table ( TblID Int, AuditFieldID Int, AuditValue Int, AuditDate Date ) INSERT INTO @tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(1,10,101,'1/1/2001') INSERT INTO @tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(2,10,102,'1/1/2002') INSERT INTO @tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(3,20,201,'1/1/2001') INSERT INTO @tbl(TblID,AuditFieldID,AuditValue,AuditDate) VALUES(4,20,202,'1/1/2009') ;WITH cLatest AS ( SELECT ROW_NUMBER() OVER (PARTITION BY AuditFieldID ORDER BY AuditDate DESC) AS Ranking, AuditFieldID, AuditDate FROM @tbl ) SELECT A.AuditFieldID, A.AuditValue, A.AuditDate FROM @tbl A JOIN cLatest C ON A.AuditFieldID = C.AuditFieldID AND A.AuditDate = C.AuditDate WHERE C.Ranking = 1 ```
Simpler: SELECT top 1 AuditFieldID,AuditValue,AuditDate FROM Tbl order by AuditDate DES
SQL Select Best practice
[ "", "sql", "" ]
Anyone care to comment on whether we should be using "I" or "II" and "&" or "&&" in our LINQ Where() extensions / queries? Any difference with LINQ to SQL? The resulting expression tree is more than I can get my brain around on a Friday afternoon Thanks, ``` static void Main(string[] args) { var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var q1 = numbers.Where(i => i == 1 | i == 2); var q2 = numbers.Where(i => i == 1 || i == 2); var q3 = numbers.Where(i => i == 1 & i < 3); var q4 = numbers.Where(i => i == 1 && i < 3); Write(q1); Write(q2); Write(q3); Write(q4); } static void Write<T>(IEnumerable<T> t) { foreach (var i in t) Console.Write("{0} ", i); Console.WriteLine(); } Results: 1 2 1 2 1 1 ```
You want `||` / `&&`. Well, the single-pipe (`|` / `&`) is generally used for bitwise arithmetic, and (among other problems) may make the code base harder to understand; it'll *work* in LINQ-to-Objects (since bitwise is still *defined* for `bool`), but without the usual short-circuiting. But if your data source is a database (i.e. there is an expression parser in the mix), you may find it explodes on you. --- OK; bitwise may have been misleading; but || and && remains the most logical and expected way of expressing your intent. My apologies for any confusion.
> Anyone care to comment on whether we should be using `|` or `||` and `&` or `&&` in our LINQ Where() extensions / queries? In lambda expressions (such as those frequently used in Linq), these operators act as they normally do in c#. `|` and `&` are logical operators while `||` and `&&` are short-circuiting logical operators. Short circuiting is good if you want efficient code. Short-circuiting is bad if you want to avoid **branching code** (perhaps to UnitTest with 100% coverage). Most people use short-circuiting all the time and the branching doesn't bother them because they avoid using expressions that have side effects, thus they suffer no ill consequences when some of the expressions are not evaluated. Here's an example of useful branching by short circuiting: ``` if (DatabaseIsAvailable() && QueryDataAndThereAreResults()) { //do something with Results } ``` When DatabaseIsAvailable() is false, QueryDataAndThereAreResults() will not be evaluated. > Any difference with LINQ to SQL? It doesn't matter which you use for Linq to Sql. The punctuation will be translated into T-Sql's `AND` and `OR` operators. After the query is sent to the database, the SqlServer Query Plan Optimizer will figure out whether or not to short circuit.
LINQ Where() Single or Double Pipes / Ampersands
[ "", "c#", "linq", "linq-to-sql", "" ]
I am working on a Reverse Engineering school project, which requires to translate manipulate AST of compiled C# project. I have seen the post on "Translate C# code into AST?" in this website, but it doesn't look like the one I am looking for. According to what I know, currently C# doesn't provide a library class that does something like that for Java: <http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.cdt.doc.isv/reference/api/org/eclipse/cdt/core/dom/ast/ASTVisitor.html>. If there is such library class in C#, everything here is solved. I have consulted with someone, and here are the possible solutions. But I have problems with working out on the solutions as well: 1. Find another compiler that provides a library which allows its AST to be expose for manipulation. But I can't find a compiler like that. 2. Use ANTLR Parser Generator to come out with my own compiler that does that (it will be a much more difficult and longer process). The download there provides sample grammars for different languages but not C# (it has grammars written in various languages including C# but not to produce C# grammar). Hence the problem is I can't find C# grammar. What is shortest and fastest way to approach this issue? If I really have to take one of the alternative above, how should I go about solving those problems I faced.
ANTLR is not a good choice. I am now trying out using Mono Cecil instead. Mono Cecil is good for analyzing any souce codes that can be compiled into Common Intermediate Language (CIL). The disadvantage is that it doesn't have properly documentation.
I know the answer for this one was accepted long ago. But I had a similar question and wasn't sure of the options out there. I did a little investigation of the NRefactory library that ships as part of SharpDevelop. It *does* generate an AST from C# code. Here's an image of the NRefactory demo application that is part of the SD source code. Type in some C# code and it generates and displays the AST in a treeview. ![alt text](https://i.stack.imgur.com/6uGi5.png)
How to manipulate C# AST?
[ "", "c#", "compiler-construction", "antlr", "abstract-syntax-tree", "" ]
``` if( count( $_POST ) < 1 ) { // determine if this was a secure request - we use a non standard HTTPS port so the SERVER_HTTPS_PORT define should always be used in place of 443 $protocol = $_SERVER['SERVER_PORT'] == SERVER_HTTPS_PORT ? 'https' : 'http'; header( "HTTP/1.0 301 Moved Permanently" ); header( "Status: 301" ); // this is for chrome compliance header( "Location: $protocol://".CLIENT_DOMAIN."{$_SERVER['REQUEST_URI']}" ); session_write_close(); exit; } ``` Can this functionality be rewritten with .htaccess rules? Logic: If not a POST request, redirect to equivalent page with whole query string by issuing 301 header and status, whilst maintaining protocol.
Try this: ``` RewriteCond %{REQUEST_METHOD} !=POST RewriteCond %{SERVER_PORT}s ^443(s)|.* RewriteRule ^foo/bar$ http%1://www.example.com%{REQUEST_URI} [L,R=301] ``` Not you just need to replace `443` by your `SERVER_HTTPS_PORT` value and `www.example.com` by your `CLIENT_DOMAIN` value.
This should work for you (replace `www.google.com` with your `CLIENT_DOMAIN`). ``` RewriteEngine on RewriteCond %{SERVER_PORT} ^80$ RewriteCond %{REQUEST_METHOD} !^POST$ [NC] RewriteRule ^(.*)$ http://www.google.com/$1 [L,QSA,R=301] RewriteCond %{SERVER_PORT} ^443$ RewriteCond %{REQUEST_METHOD} !^POST$ [NC] RewriteRule ^(.*)$ https://www.google.com/$1 [L,QSA,R=301] ```
php to htaccess rewrite - redirect if no $_POST data
[ "", "php", "apache", ".htaccess", "redirect", "http-status-code-301", "" ]
I would like to know how to I exit from Python without having an traceback dump on the output. I still want want to be able to return an error code but I do not want to display the traceback log. I want to be able to exit using `exit(number)` without trace but in case of an Exception (not an exit) I want the trace.
You are presumably encountering an exception and the program is exiting because of this (with a traceback). The first thing to do therefore is to catch that exception, before exiting cleanly (maybe with a message, example given). Try something like this in your `main` routine: ``` import sys, traceback def main(): try: do main program stuff here .... except KeyboardInterrupt: print "Shutdown requested...exiting" except Exception: traceback.print_exc(file=sys.stdout) sys.exit(0) if __name__ == "__main__": main() ```
Perhaps you're trying to catch all exceptions and this is catching the `SystemExit` exception raised by `sys.exit()`? ``` import sys try: sys.exit(1) # Or something that calls sys.exit() except SystemExit as e: sys.exit(e) except: # Cleanup and reraise. This will print a backtrace. # (Insert your cleanup code here.) raise ``` In general, using `except:` without naming an exception is a bad idea. You'll catch all kinds of stuff you don't want to catch -- like `SystemExit` -- and it can also mask your own programming errors. My example above is silly, unless you're doing something in terms of cleanup. You could replace it with: ``` import sys sys.exit(1) # Or something that calls sys.exit(). ``` If you need to exit without raising `SystemExit`: ``` import os os._exit(1) ``` I do this, in code that runs under unittest and calls `fork()`. Unittest gets when the forked process raises `SystemExit`. This is definitely a corner case!
How to exit from Python without traceback?
[ "", "python", "exit", "traceback", "" ]
I want to write a small (5-6 table) desktop app in Java. I want to use Firebird 2.1. database. But I googled and see HSQLDB. I want to make a decision between Firebird and hsqldb. So which database I have to use?
For a desktop application an embedded database should be enough. [hsqldb](http://hsqldb.org/) or [h2](http://www.h2database.com/) are very well suited for this. You just have to add the JAR file to you applications classpath. Firebird looks more complex. Actually, [H2 is more advanced than hsqldb](http://www.h2database.com/html/features.html#comparison).
Firebird runs in a process of its own and your java app needs to communicate with it. The advantage HSQLDB has that it is written in java, and can run in the same process, which simplifies your installation and runtime check ups (Is the db running, connection errors, etc.). It can persist the data to the disk as well. AN additional option is the [H2 database](http://www.h2database.com/) db, which also can run in process. I'd go with the HSQLDB or H2.
Choosing between Firebird and HSQLDB in Java
[ "", "java", "database", "comparison", "firebird", "hsqldb", "" ]
In the following italicized code, why don't we put "IntIndexer" in front of *myData = new string[size];* since *Customer cust = new Customer();* (assuming Customer is the name of the class): ``` *Customer cust = new Customer();* ``` using System; ``` /// <summary> /// A simple indexer example. /// </summary> class IntIndexer { private string[] myData; public IntIndexer(int size) { *myData = new string[size];* for (int i = 0; i < size; i++) { myData[i] = "empty"; } } ```
To break this down: ``` Customer cust = new Customer(); ``` This can be broken into two parts: ``` Customer cust; cust = new Customer(); ``` The first line says that the name `cust` will be able to refer to objects of type `Customer`. The second line creates a new `Customer` object and makes `cust` refer to it. The other example you give is already broken into those two parts: ``` private string[] myData; ``` and: ``` myData = new string[size]; ``` If the array of strings was to be of a constant length, we could collapse this onto one line as well, in `IntIndexer` (before the constructor). ``` private string[] myData = new string[100]; ``` But we need to use the `size` passed into the `IntIndexer` constructor, so we have to split the declaration and initialization into two steps.
The first line (`cust`) is declaring and initialising a field or variable. In the second example, the field (`myData`) is declared against the type, and intialised in the constructor (`IntIndexer(...)`). If (in the constructor) we placed a type before it, we would be declaring a local variable **with the same name**. This would be confusing (you'd then have to use `this.myData` and `myData` to refer to the field and variable respectively).
What's the difference between these two lines? (C#)
[ "", "c#", "" ]
In my project I have a few functions in derived classes that are the same except for one section that is different in each. I want to pull the method up to the base class. The functions look like this: ``` func(parameters) { //COMMON BITS if (someVar == "value1") { htmlFilename = line; } else if (someVar == "value2") { subVideoLink = line; } else if (someVar == "value3") { linksH2HeadingWritten = true; } //COMMON BITS } ``` where the center lines of the different functions all look like above but have different values for "someVar" and different variables in the "variable = line;" format. This is the generalized form: ``` if (someVar == "CommandName") { variable = line; } ``` The idea I had was to send the function a `Dictionary<string CommandName, ref string>`... however it seems I can't make a Dictionary with ref string in it... I would then remove the boolean cases of the 'variable' by replacing them with string versions with values of "true" or "false". Is there a better way to do this?
A better approach would be to define a `virtual` (or `abstract`) method in the base class that you call in `func`. Then in each of your subclasses you can override the method with the specific instructions and `func` will use the subclass's behavior. ``` public class MyBase { protected virtual void DoCommand() { throw new NotImplementedException(); } public void Func() { ... DoCommand(); ... } } public class MySubClass : MyBase { protected override void DoCommand() { ... } } ```
You should create an overridable method on the base class: ``` abstract func(parameters); ``` And implement it on the derived classes: ``` class CommandN { ... func(parameters) { htmlfilename = line; } } class CommandSubVideoLinkX { ... func(parameters) { subVideoLink = line; } } ``` And so on.
Refactoring Derived Classes' Methods to Common Base Class' Method? (C#)
[ "", "c#", "refactoring", "" ]
I built an application for a client that requires SQL Server 2005 Express. Everything worked fine on all the machines except for one. On this one they already had an application that uses SQL Server Express, so it was already installed on the machine, but nobody knows which application uses it or any usernames/passwords. Can I simply install another copy into a different folder? This just doesn't seem right to me, and I know this has to be a common scenario. Can someone point me in the right direction on how I should proceed? Thanks! Darvis
Yes you can just install into a different directory, as a new "named instance" of SQL Server Express. To install, follow Step 8 on [Microsoft's Install How-To](http://msdn.microsoft.com/en-us/library/ms143722%28SQL.90%29.aspx): > On the Instance Name page, select a Default instance or a Named instance for your installation. If you select Default instance, an existing default instance will be upgraded. If you select Named Instance, specify an instance name So what you need to do is specify the Named Instance and specify your own instance name, and connect to it using the URL format as above. As the Microsoft How-To mentions, the default installation is a named instance as well, with the name "SQLExpress", which is why if you want to stop or start the service with `net start` or `net stop' you need to write something like: ``` net start mssql$sqlexpress ``` and the hostname part of the connection string for a default SQL named instance is: ``` .\SQLEXPRESS (or localhost\SQLEXPRESS) ```
You should be able to log into it using Integrated Windows Authentication using an administrator type account on the PC, and use that to reset passwords on any SQL server type logins. Failing that, yes, you should be able install a "named instance". You connect to it by supplying "hostname\instancename" as the server name.
Installing SQL Server Express 2005 - but it already exists on the machine
[ "", "sql", "" ]
I have an application that interacts with external devices using serial communication. There are two versions of the device differing in their implementations. -->One is developed and tested by my team -->The other version by a different team. Since the other team has left, our team is looking after it's maintenance. The other day while testing the application I noticed that the application takes up 60 Mb memory at startup and to my horror it's memory usage starts increasing with 200Kb chunks, in 60 hrs it shoots up to 295 Mb though there is no slow down in the responsiveness and usage of application. I tested it again and again and the same memory usage pattern is repeated. **The application is made in C++,Qt 4.2.1 on RHEL4.** I used mtrace to check for any memory leaks and it shows no such leaks. I then used valgrind memcheck tool, but the messages it gives are cryptic and not very conclusive, it shows leaks in graphical elements of Qt, which on scrutiny can be straightaway rejected. I am in a fix as to what other tools/methodologies can be adopted to pinpoint the source of these memory leaks if any. -->Also, in a larger context, how can we detect and debug presence of memory leaks in a C++ Qt application? -->How can we check, how much memory a process uses in Linux? I had used gnome-system-monitor and top command to check for memory used by the application, but I have heard that results given by above mentioned tools are not absolute. **EDIT:** I used ccmalloc for detecting memory leaks and this is the error report I got after I closed the application. During application execution, there were no error messages. |ccmalloc report| ======================================================= | total # of| allocated | deallocated | garbage | +-----------+-------------+-------------+-------------+ | bytes| 387325257 | 386229435 | 1095822 | +-----------+-------------+-------------+-------------+ |allocations| 1232496 | 1201351 | 31145 | +-----------------------------------------------------+ | number of checks: 1 | | number of counts: 2434332 | | retrieving function names for addresses ... done. | | reading file info from gdb ... done. | | sorting by number of not reclaimed bytes ... done. | | number of call chains: 3 | | number of ignored call chains: 0 | | number of reported call chains: 3 | | number of internal call chains: 3 | | number of library call chains: 1 | ======================================================= | | 3.1% = 33.6 KB of garbage allocated in 47 allocations | | | | 0x???????? in | | | | 0x081ef2b6 in | | at src/wrapper.c:489 | | | | 0x081ef169 in <\_realloc> | | at src/wrapper.c:435 | | | `-----> 0x081ef05c in | at src/wrapper.c:318 | | 0.8% = 8722 Bytes of garbage allocated in 35 allocations | | | | 0x???????? in | | | | 0x081ef134 in | | at src/wrapper.c:422 | | | `-----> 0x081ef05c in | at src/wrapper.c:318 | | 0.1% = 1144 Bytes of garbage allocated in 5 allocations | | | | 0x???????? in | | | | 0x081ef1cb in | | at src/wrapper.c:455 | | | `-----> 0x081ef05c in | at src/wrapper.c:318 | `------------------------------------------------------ free(0x09cb650c) after reporting (This can happen with static destructors. When linking put `ccmalloc.o' at the end (for gcc) or in front of the list of object files.) free(0x09cb68f4) after reporting free(0x09cb68a4) after reporting free(0x09cb6834) after reporting free(0x09cb6814) after reporting free(0x09cb67a4) after reporting free(0x09cb6784) after reporting free(0x09cb66cc) after reporting free(0x09cb66ac) after reporting free(0x09cb65e4) after reporting free(0x09cb65c4) after reporting free(0x09cb653c) after reporting ccmalloc\_report() called in non valid state I have no clue, what this means, it doesn't seem to indicate any memory leaks to me? I may be wrong. Does anyone of you have come across such a scenario? link|edit|delete
Valgrind can be a bitch if you don't really read the manuals or whatever documentation is actually available (man page for starters) - but they are worth it. Basicly, you could start by running the valgrind on your application with --gen-suppressions=all and then create a suppressions for each block that is originating from QT itself and then use the suppression file to block those errors and you should be left with only with errors in your own code. Also, you could try to use valgrind thru a alleyoop frontend if that makes things easier for you. There are also bunch of other tools that can be used to detect memory leaks and Linux Journal has article about those here: <http://www.linuxjournal.com/article/6556> And last, in some cases, some static analysis tools can spot memory errors too..
I'd like to make the minor point that just because the meory used by a process is increasing, it does not follow that you have a memory leak. Take a word processor as an example - as you write text, the memory usage increases, but there is no leak. Most processes in fact increase their memoryy usage as they run, often until they reach some sort of near steady-state, where objects been created are balanced by old objects being destroyed.
Detecting memory leaks in C++ Qt combine?
[ "", "c++", "linux", "qt", "" ]
If I need a large buffer in my program written in C++, which one is better? 1. Allocate the buffer in heap, and keep a reference to that buffer in the class that use it. 2. Allocate a static buffer, and make it global.
How about: 3. Use a vector. [Edited to add: or boost::array is a good option if you're happy with the dependency]
The disadvantage with a static buffer is that you never exactly know when it will be deleted, if you want to use that buffer during destruction of some object, it could already be gone. So for more control, I would choose option 1.
How to manage large buffer in C++?
[ "", "c++", "memory", "" ]