Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am working on a module that takes a user-uploaded CSV file. Code looks like this: ``` function foo_form_submit($form_id, &$form_state) { $validators = array(); $dest = 'sites/phoenix.dev/files'; $uploaded_file = file_save_upload('upload', $validators, $dest); //some other stuff } ``` As you can see, I don't pass anything in to validate that the file in the 'upload' field is actually a .csv file. This would cause some nasty things to happen later on in the function. How do I use the validators to check that the extension is .csv, or even better, to check that it actually IS a .csv file? Edit: and Google search did not turn up anything too helpful.
[Drupal documentation on file\_validate\_extensions](http://api.drupal.org/api/function/file_validate_extensions/6) suggests you want to change this: ``` $validators = array(); ``` To this: ``` $validators = array( 'file_validate_extensions' => array( 'csv' ) ); ```
I don't see how you could check whether it's a valid CSV without actually trying to parse it and seeing if there are any errors.
How do I validate file type in Drupal 6 with file_save_upload?
[ "", "php", "file", "drupal-6", "" ]
Is it possible to make the default Eclipse "Generate hashCode() and equals()" use getters instead of field references? - ie. can I get at the template that it uses? I'm using Hibernate, and Proxied Objects are only LazyLoaded when getters are used and not from field references. It's an annoyance to be constantly changing it. The obvious workarounds are to create a template myself or write a plugin - which feels like overkill. EDIT: Looks like these aren't configurable. I'll pose this as a question for the JBoss Tools Group (They make some plugins for Hibernate).
It's not a solution, rather workaround - but you might try generate `equals()`, then use 'encapsulate field' refactoring to replace all field acceses to use getters/setters (it works inside class also).
Ohhhh, be carefull with proxing : <http://blog.xebia.com/2008/03/08/advanced-hibernate-proxy-pitfalls/> ;)
make Eclipse equals() / hashCode() use getters
[ "", "java", "eclipse", "hibernate", "" ]
I know this is normally rather stupid, but don't shoot me before reading the question. I promise I have a good reason for needing to do this :) It's possible to modify regular private fields in java using reflection, however Java throws a security exception when trying to do the same for `final` fields. I'd assume this is strictly enforced, but figured I'd ask anyway just in case someone had figured out a hack to do this. Let's just say I have an external library with a class "`SomeClass`" ``` public class SomeClass { private static final SomeClass INSTANCE = new SomeClass() public static SomeClass getInstance(){ return INSTANCE; } public Object doSomething(){ // Do some stuff here } } ``` I essentially want to Monkey-Patch SomeClass so that I can execute my own version of `doSomething()`. Since there isn't (to my knowledge) any way to really do that in java, my only solution here is to alter the value of `INSTANCE` so it returns my version of the class with the modified method. Essentially I just want to wrap the call with a security check and then call the original method. The external library always uses `getInstance()` to get an instance of this class (i.e. it's a singleton). EDIT: Just to clarify, `getInstance()` is called by the external library, not my code, so just subclassing won't solve the issue. If I can't do that the only other solution I can think of is to copy-paste entire class and modify the method. This isn't ideal as I'll have to keep my fork up to date with changes to the library. If someone has something a little more maintainable I'm open to suggestions.
It is possible. I've used this to monkeypatch naughty threadlocals that were preventing class unloading in webapps. You just need to use reflection to remove the `final` modifier, then you can modify the field. Something like this will do the trick: ``` private void killThreadLocal(String klazzName, String fieldName) { Field field = Class.forName(klazzName).getDeclaredField(fieldName); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); int modifiers = modifiersField.getInt(field); modifiers &= ~Modifier.FINAL; modifiersField.setInt(field, modifiers); field.set(null, null); } ``` There is some caching as well around `Field#set`, so if some code has run before it might not necessarily work....
Any AOP framework would fit your needs It would allow you to define a runtime override for the getInstance method allowing you to return whatever class suits your need. Jmockit uses the ASM framework internally to do the same thing.
Is there any way to modify the value of a `private static final` field in Java from outside the class?
[ "", "java", "monkeypatching", "" ]
Static inheritance works just like instance inheritance. Except you are not allowed to make static methods virtual or abstract. ``` class Program { static void Main(string[] args) { TestBase.TargetMethod(); TestChild.TargetMethod(); TestBase.Operation(); TestChild.Operation(); } } class TestBase { public static void TargetMethod() { Console.WriteLine("Base class"); } public static void Operation() { TargetMethod(); } } class TestChild : TestBase { public static new void TargetMethod() { Console.WriteLine("Child class"); } } ``` This will output: ``` Base class Child class Base class Base class ``` But I want: ``` Base class Child class Base class Child class ``` If it I could on static methods, I would make TargetMethod virtual and it would do the job. But is there a work around to get the same effect? Edit: Yes, I could put a copy of Operation in the child class, but this would require copy and pasting a large bit of code into every child, which in my case is about 35 classes, a maintenance nightmare.
No, you cannot override a static method. "static" also means that it is statically bound by the compiler, so the actual method to be called is not found at runtime, but bound at compile time. What you should do is make the class non-static. Make the method virtual and override it and make full benefit of real inheritance. Then, if you really need it, make a static entry point to a reference of your class. For instance a static factory, singleton (it's an anti-pattern in most of the cases but is as good as a static class) or just a static property.
You could store the TargetMethod as a delegate, which a subclass could change as needed: ``` class TestBase { protected static Action _targetMethod; static new() { _targetMethod = new Action(() => { Console.WriteLine("Base class"); }); } public static void TargetMethod() { _targetMethod(); } public static void Operation() { TargetMethod(); } } class TestChild : TestBase { static new() { _targetMethod = new Action(() => { Console.WriteLine("Child class"); }); } } ``` Since these are static instances, though - the `_targetMethod` is shared across all instances - changing it in `TestChild` changes it for `TestBase` as well. You may or may not care about that. If you do, generics or a `Dictionary<Type, Action>` might help. Overall, though, you'd have a much easier time if you didn't insist on statics, or perhaps used composition instead of inheritance.
C# virtual (or abstract) static methods
[ "", "c#", "inheritance", "" ]
OK when I save uploaded files with PHP via move\_uploaded\_file() I cannot use an absolute URL I have to use a relative one. My site has 2 root directories one for the http side and one for the https side: httpdocs and httpsdocs respectively. So if my script is on the https side how can I save the file to a location on the http side? Thanks! **UPDATE** OK so it seems like I am using the wrong absolute path convention I am doing it like this: ``` $dir = 'https://www.mydomain.com/masonic_images/'; move_uploaded_file($_FILES['blue_image']['tmp_name'], $dir.$new_name); ```
Are the httpdocs and httpsdocs directories both located in the same parent folder? If so, just use a relative path for the second parameter in move\_uploaded\_file to place the file in the other root directory. For example: ``` $uploaddir = '../httpdocs/'; $uploadfile = $uploaddir . basename($_FILES['myfile']['name']); ``` This code assumes that the uploading script is located in the httpsdocs root directory, and that you want to save the file into the httpdocs directory.
[`move_uploaded_file()`](http://php.net/move_uploaded_file) doesn't accept URLs for either parameter. The destination is an absolute path on your filesystem. ``` <?php $dir = '/var/www/httpsdocs/'; // Adjust to your configuration move_uploaded_file($_FILES['blue_image']['tmp_name'], $dir.$new_name); ``` As @[apphacker](https://stackoverflow.com/questions/748915/php-saving-files-with-php-to-different-root-directory/748936#748936) suggested. you can use [`realpath(__FILE__)`](http://php.net/realpath) to determine the absolute path to a file.
PHP: Saving files with PHP to different root directory?
[ "", "php", "php4", "" ]
I started working with C# recently and I noticed that the convention seems to be that the variables start with a capital letter along with the methods. Is this the only language that does this and why? For instance: ``` Page Page = new Page(); Page.Action(); ``` In other languages, you'd see instead: ``` Page page = new Page(); page.action(); ``` There are other examples of this that are confusing since I've worked a lot with UML, Ruby, C++ and Java. My question is, why does C# do it this way when other languages do not? ### Edit > Other Stack Overflow users are noting that C# does not follow this convention, this was just a mistake on my part.
Well actually, no: the convention in C# is for camelCased variable (and field) names, and PascalCase methods: ``` Page page = new Page(); page.Action(); ```
No, this is fairly non-standard C# code. The .Net Framework Design guidelines in section 2.6 recomend the use of camel casing for local variable names. * [http://blogs.msdn.com/brada/articles/361363.aspx](http://web.archive.org/web/20120801053215/http://blogs.msdn.com/b/brada/archive/2005/01/26/361363.aspx)
Why does C# use a different Naming convention?
[ "", "c#", "naming-conventions", "uml", "conventions", "" ]
I need to return two fields from a database concatenated as 'field1-field2'. The second field is an int, but needs to be returned as a fixed length of 5 with leading 0's. The method i'm using is: ``` SELECT Field1 + '-' + RIGHT('0000' + CAST(Field2 AS varchar),5) FROM ... ``` Is there a more efficient way to do this?
That is pretty much the way: [Adding Leading Zeros To Integer Values](http://wiki.lessthandot.com/index.php/Adding_Leading_Zeros_To_Integer_Values) So, to save following the link, the query looks like this, where `#Numbers` is the table and `Num` is the column: ``` SELECT RIGHT('000000000' + CONVERT(VARCHAR(8),Num), 8) FROM #Numbers ``` for negative or positive values ``` declare @v varchar(6) select @v = -5 SELECT case when @v < 0 then '-' else '' end + RIGHT('00000' + replace(@v,'-',''), 5) ```
Another way (without CAST or CONVERT): ``` SELECT RIGHT(REPLACE(STR(@NUM),' ','0'),5) ```
Most efficient method for adding leading 0's to an int in sql
[ "", "sql", "sql-server", "" ]
Does anyone know if there's a windows Python executable creator program available now that supports Python 3.0.1? It seems that py2exe and pyInstaller, along with all the rest I've found, still aren't anywhere close to supporting 3.0 or 3.0.1. Any help is greatly appreciated. Edit: I guess I could downgrade the program to an older version of Python to make it work with py2exe. The hardest part will probably be using an older version of Tkinter. Has anyone had luck with using py2exe or pyInstaller (or another windows-friendly program) to create an executable that uses Tkinter as well as subprocess. I'm actually not sure how to get the directory my program will be installed into so subprocess can find the executable program I'm using.
Not answering the original question but this: > I'm actually not sure how to get the directory my program will be installed into so subprocess can find the executable program I'm using. You can use something like ``` if hasattr(sys, 'frozen'): # this means we're installed using py2exe/pyinstaller INSTDIR = os.path.dirname(sys.executable) else: ... ```
How about [cx\_Freeze](http://cx-freeze.sourceforge.net/). Seems to support python 3.0 and 3.1?
Python 3.0.1 Executable Creator
[ "", "python", "executable", "py2exe", "pyinstaller", "" ]
I know [`document.write`](https://developer.mozilla.org/en-US/docs/DOM/document.write) is considered bad practice; and I'm hoping to compile a list of reasons to submit to a 3rd party vendor as to why they shouldn't use `document.write` in implementations of their analytics code. Please include your reason for claiming `document.write` as a bad practice below.
A few of the more serious problems: * document.write (henceforth DW) does not work in XHTML * DW does not directly modify the DOM, preventing further manipulation *(trying to find evidence of this, but it's at best situational)* * DW executed after the page has finished loading will overwrite the page, or write a new page, or not work * DW executes where encountered: it cannot inject at a given node point * DW is effectively writing serialised text which is not the way the DOM works conceptually, and is an easy way to create bugs (.innerHTML has the same problem) Far better to use the safe and DOM friendly [DOM manipulation methods](https://developer.mozilla.org/en-US/docs/Web/API/Document)
There's actually nothing wrong with `document.write`, per se. The problem is that it's really easy to misuse it. Grossly, even. In terms of vendors supplying analytics code (like Google Analytics) it's actually the easiest way for them to distribute such snippets 1. It keeps the scripts small 2. They don't have to worry about overriding already established onload events or including the necessary abstraction to add onload events safely 3. It's extremely compatible ***As long as you don't try to use it after the document has loaded***, `document.write` is not inherently evil, in my humble opinion.
Why is document.write considered a "bad practice"?
[ "", "javascript", "" ]
Trying to use 300dpi tif images for display on the web. At the moment, when the user uploads an image, I am dynamically creating a thumbnail. If a page is created referencing the high-res image with a width of 500x500px, can I use the same functionality to convert to a gif/jpg on the fly. What is the impending resolution of the jpg that would be created? **EDIT:** To further explain the usage, the user uploads 300dpi images which are approx 3000x3000 pixels. The user is using these images to create a catalog page which will be used for pdf printing. When they are creating the page, we only need 72dpi images to display to the screen, but for print, need the 300dpi images. Obviously they do not want to add a 3000x3000px image to the page, so it needs to be resized to the correct viewing area, e.g. 500x500px etc.
This boils down to a simple image resize. The discussion of DPIs is just ancillary data to calculate the scale factor. As @Guffa said, you should do this at the time of the upload so that you can just serve static images in your viewer. This will be a load on the server: 1. Load the full image. This will be about 27 MB of memory for your 3000x3000 images. 2. Resize. Lot's of math done lazily (still CPU intensive). 3. Compress. More CPU + Cost of writing to your drive. Since you are already taking the time to generate a thumbnail, you can amortize that cost and this cost by not having to repeat Step 1 above (see the code). After an image is uplaoded, I would recommend spinning off a thread to do this work. It's a load on the web server for sure, but you're only other option is to devote a second machine to performing the work. It will have to be done eventually. Here is some code to do the job. The important lines are these: ``` OutputAsJpeg(Resize(big, 300.0, 72.0), new FileStream("ScreenView.jpg")); OutputAsJpeg(Resize(big, bigSize, 64.0), new FileStream("Thumbnail.jpg")); ``` We can resize the `big` image however we need. In the first line we just scale it down by a fixed scale (72.0 / 300.0). On the second line, we force the image to have a final max dimension of 64 (scale factor = 64.0 / 3000.0). ``` using System.Windows.Media; using System.Windows.Media.Imaging; using System.IO; BitmapSource Resize(BitmapSource original, double originalScale, double newScale) { double s = newScale / originalScale; return new TransformedBitmap(original, new ScaleTransform(s, s)); } void OutputAsJpeg(BitmapSource src, Stream out) { var encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(src)); encoder.Save(out); } // Load up your bitmap from the file system or whatever, // then dump it out to a smaller version and a thumbnail. // Assumes thumbnails have a max dimension of 64 BitmapSource big = new BitmapImage(new Uri("BigPage0.png", UriKind. RelativeOrAbsolute)); double bigSize = Math.Max(big.PixelWidth, big.PixelHeight); OutputAsJpeg(Resize(big, 300.0, 72.0), new FileStream("ScreenView.jpg")); OutputAsJpeg(Resize(big, bigSize, 64.0), new FileStream("Thumbnail.jpg")); ```
If I understand what you want - you're trying to make a gif or jpg thumbnail of a very high resolution tif, for web display - if not, I apologize in advance.... --- If you want the thumbnail to be 500x500px, that is the resolution of the jpg/gif you'll want to create - 500x500, or at least 500x<500 or <500x500 (to fit in the box, unless you want distorted images). For display on the web, the DPI does not matter. Just use the pixel resolution you wish directly.
How to serve high-resolution imagery in a low-resolution form using C#
[ "", "c#", "image-processing", "image-manipulation", "tiff", "" ]
I want to use PostgreSQL's native UUID type with a Java UUID. I am using Hibernate as my JPA provider and ORM. If I try to save it directly, it is just saved as a bytea in Postgres. How can I do this?
Try use the latest development version of the JDBC driver (Currently 8.4dev-700), or wait for the next release version. (Edited to add: 8.4-701 has been released) The [release notes](http://jdbc.postgresql.org/changes.html#version_8.4dev-700) mention this change: > Map the database uuid type to java.util.UUID. This only works for relatively new server (8.3) and JDK (1.5) versions.
Here's a repost of my answer on [Postgresql UUID supported by Hibernate?](https://stackoverflow.com/questions/4495233/postgresql-uuid-supported-by-hibernate/7479035#7479035) ... I know this question is old, but if someone stumbles across it, this will help them out. This can be solved by adding the following annotation to the UUID: ``` import org.hibernate.annotations.Type; ... @Type(type="pg-uuid") private java.util.UUID itemUuid; ``` As to why Hibernate doesn't just make this the default setting, I couldn't tell you... **UPDATE**: There still seem to be issues using the `createNativeQuery` method to open objects that have UUID fields. Fortunately, the `createQuery` method so far has worked fine for me.
Postgres + Hibernate + Java UUID
[ "", "java", "hibernate", "postgresql", "jakarta-ee", "uuid", "" ]
I'm looking for a good publishing platform with a good media gallery. I'll need to show several sorts of video and images, so a good media gallery is a must. I've tried drupal, but I don't like the node organization structure. I'm searching for a simple URL scheme, because in the future I may want to migrate my static html site to this platform. So I prefer a platform where urls are like [www.mysite.com/parent/child/grandchild/page](http://www.mysite.com/parent/child/grandchild/page) kinda like the atlassian confluence urls (ex: confluence/display/TKB/Technical+Details). This way I'll be able to make a simple script to migrate my static page to the dynamic version. --- Edit: The CMS/publishing platform must run on PHP.
Are you looking for something opensource? you can try looking at Drupal or Joomla. Although, I recommend Drupal. But if you are looking for your enterprise, you should really look at Alfresco.
I would heartily get behind Wordpress. It is targeted at the blogging community, but a lot of "serious" sites use it with much success: * <http://politicalticker.blogs.cnn.com/> * <http://scobleizer.com/> * <http://www.zeldman.com> * <http://www.techcrunch.com/> It has many great media-handling plugins: <http://wordpress.org/extend/plugins/search.php?q=gallery> and also can be customized to produce whatever URLs you want: <http://codex.wordpress.org/Using_Permalinks> I've used it to develop 4 sites so far, and it's easy to customize, and has a great user-base. FTW.
Good CMS/Publishing platform with media plugin and nice urls
[ "", "php", "content-management-system", "media", "gallery", "" ]
Let's get straight to my question: I have a socket and all input coming via this socket / stream is parsed by my SAX parser. Now, upon a certain parsing event I'd like to close the socket / stream from within my SAX event handler. Also, I want to close the stream from outside in a certain case while the parser is still working. Unfortunately, I can't do the one thing or the other without having an exception thrown by the parser (unexpected document ending...). Ok, I could catch this exception, but do you know a solution how to securely close the stream?
I don't think you can easily do this. You're giving the SAX parser a resource (a stream) to read from, and then you're closing it and the SAX parser still expects to read from it - hence it's (not unreasonably!) throwing an 'unexpected document ending'. If you want to do this cleanly, I think your SAX parser [handler](http://java.sun.com/j2se/1.4.2/docs/api/org/xml/sax/helpers/DefaultHandler.html) that you've implemented should silently swallow events once you've decided to ignore further events. e.g. your implementations of `startElement()`, `endElement()` etc. should perform a check to see whether you're still interested in these events before processing. That way the SAX parser can run cleanly to the end of the document without you processing any more events. Alternatively, why not record the fact that you've closed the input stream, and then when you get an 'unexpected document ending' event, see if it in fact *was* expected. And only log an error if it really was unexpected.
This may be obvious, but for use case like this, a [Stax parser](http://woodstox.codehaus.org) might be a better fit. Since application controls reading via iteration it can close the parser and the underlying stream at any given point. With SAX you will have to throw an exception, which is not particularly elegant or efficient. Plus you can only do that from within handler. For extra points, [StaxMate](http://staxmate.codehaus.org/Tutorial) can make use of Stax more pleasant; without it Stax has similar low level of abstraction as SAX. Finally: if your problem is that of blocking due to sockets, it may be hard to solve with traditional blocking-IO based xml parsers. There is one open source xml parser that can do non-blocking (async) parsing, but that's rather little known so I'll leave that discovery to interested readers. :-)
Best way to close a stream an SAX parser is reading during the parsing process?
[ "", "java", "sockets", "stream", "sax", "jaxp", "" ]
I'm trying to make a website in which a user inputs details on one screen, and they are posted onto the following script. This script is meant to store these details in a database along with a unique integer ID (which it does), and then generate two links containing the unique ID of the record just created. Since the database creates the ID rather than the page before, I've tried to query the database for the most recent record (i.e. the one with the highest unique ID value) and use that number in the link, however with the current script the ID doesn't seem to show up in the page. Is it a variable type thing? Is there a simpler way to get the ID of the page just created? Here's the code: ``` $css = $_POST['css']; $shopName = strip_tags($_POST['title']); $email = $_POST['email']; $con = mysql_connect("***","***","***"); if (!$con) { die('Could not connect to database: '. mysql_error()); } mysql_select_db("***", $con); $sql = "INSERT INTO wps_Shops (shopName, shopEmail, shopStyle) VALUES ('$shopName', '$email', '$css')"; $quer = mysql_query($sql); $result = mysql_query("SELECT * FROM wps_Shops ORDER BY shopId DESC LIMIT 1"); $lastShop = mysql_fetch_array($result); $id = strval($lastShop['id']); echo ("Id: ".$id); if ($quer) { echo("<h1>Shop created</h1>"); echo("<p><a href=\"shop.php?id=$id\">Go to shop</a></p>"); echo("<p><a href=\"addproducts.php?id=$id\">Add products</a></p>"); } mysql_close($con); ```
Right after you do the `mysql_query()` for the insert, you can use [mysql\_insert\_id()](https://www.php.net/mysql-insert-id) to get the ID of the inserted row. ``` mysql_query("INSERT INTO........"); $id=mysql_insert_id(); ``` ---
You need [`mysql_insert_id`](http://www.php.net/manual/en/function.mysql-insert-id.php).
Echoing an integer from a mySQL database
[ "", "php", "mysql", "integer", "echo", "" ]
I have written a converter that takes openstreetmap xml files and converts them to a binary runtime rendering format that is typically about 10% of the original size. Input file sizes are typically 3gb and larger. The input files are not loaded into memory all at once, but streamed as points and polys are collected, then a bsp is run on them and the file is output. Recently on larger files it runs out of memory and dies (the one in question has 14million points and 1million polygons). Typically my program is using about 1gb to 1.2 gb of ram when this happens. I've tried increasing virtual memory from 2 to 8gb (on XP) but this change made no effect. Also, since this code is open-source I would like to have it work regardless of the available ram (albeit slower), it runs on Windows, Linux and Mac. What techniques can I use to avoid having it run out of memory? Processing the data in smaller sub-sets and then merging the final results? Using my own virtual memory type of handler? Any other ideas?
First, on a 32-bit system, you will always be limited to 4 GB of memory, no matter pagefile settings. (And of those, only 2GB will be available to your process on Windows. On Linux, you'll typically have around 3GB available) So the first obvious solution is to switch to a 64-bit OS, and compile your application for 64-bit. That gives you a huge virtual memory space to use, and the OS will swap data in and out of the pagefile as necessary to keep things working. Second, allocating smaller chunks of memory at a time may help. It's often easier to find 4 256MB chunks of free memory than one 1GB chunk. Third, split up the problem. Don't process the entire dataset at once, but try to load and process only a small section at a time.
It sounds like you're already doing a [SAX](http://en.wikipedia.org/wiki/Simple_API_for_XML) based approach to the XML processing (loading the XML as you go instead of all at once). The solution is almost always to change the algorithm so that it cuts the problem into smaller parts. Physically don't allocate as much memory at one time, read in only what you need, process it, then write it out. You can sometimes extend memory via using the hard drive instead when needed in your algorithm. If you can't split up your algorithm, you probably want something like [memory mapped files](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2044.html). In the worst case you can try to use something like [VirtualAlloc](http://msdn.microsoft.com/en-us/library/aa366887(VS.85).aspx) if you are on a windows system. If you are on a 32-bit system you can try to use something like [Physical Address Extension (PAE)](http://msdn.microsoft.com/en-us/library/aa366796(VS.85).aspx). You could also consider putting input limitations for your program, and having a different one for 32-bit and 64-bit systems.
How to avoid running out of memory in high memory usage application? C / C++
[ "", "c++", "c", "memory", "virtual-memory", "" ]
Why is this? I would find it *really* nice to be able to have some extension methods locked down to be used only within one of my classes. Don't really want to have certain extension methods available everywhere... and they look so much nicer than regular static methods :P --- For clarification: The reason I want these extension methods is because I am extending a Form, which has a DataGridView on it. And I am getting very tired of lines like these: ``` foreach(var row in grid.Rows.OfType<DataGridViewRow>().Where(r => (bool) r.Cells[checkBoxColumn.Index].Value)) foreach(var row in grid.SelectedRows.OfType<DataGridViewRow>().Where(r => (bool) r.Cells[checkBoxColumn.Index].Value)) ``` Would like an extension method so that I could just do ``` foreach(var row in grid.Rows.CheckedRows()) foreach(var row in grid.SelectedRows.CheckedRows()) ``` So in other words, this extension method would not be useful at all outside this class. But it would make the code a lot cleaner. Can of course make regular methods too, and that is what I ended up doing, since this wasn't possible. Aaanyways, I was just curious to know if anyone had some good arguments to why they had chosen to put a restriction like this upon where extension methods can created used. *Must be in a static class* makes total sense. *Can't be in a nested static class* doesn't... to me at least...
Would using an extension method really make your code *a lot cleaner* than using a standard helper method on your class? ``` // extension method foreach (var row in grid.Rows.CheckedRows()) foreach (var row in grid.SelectedRows.CheckedRows()) // standard helper method foreach (var row in CheckedRows(grid.Rows)) foreach (var row in CheckedRows(grid.SelectedRows)) ```
If you own the source code of the type, why are you using extension methods? Why don't you just make those extension methods members of the type itself? Extension methods are best used to extend types that you did not create. While they are useful tools they are a layer of indirection that should be a last resort rather than a first. While you can use them to extend your own types it makes more sense to reserve their use for types that you did not create.
Extension methods not allowed in nested static classes?
[ "", "c#", "extension-methods", "nested-class", "" ]
The following code plots to two [PostScript](http://en.wikipedia.org/wiki/PostScript) (.ps) files, but the second one contains both lines. ``` import matplotlib import matplotlib.pyplot as plt import matplotlib.mlab as mlab plt.subplot(111) x = [1,10] y = [30, 1000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("first.ps") plt.subplot(111) x = [10,100] y = [10, 10000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("second.ps") ``` How can I tell matplotlib to start afresh for the second plot?
You can use `figure` to create a new plot, for example, or use `close` after the first plot.
There is a clear figure command, and it should do it for you: ``` plt.clf() ``` If you have multiple subplots in the same figure ``` plt.cla() ``` clears the current axes.
How do I tell matplotlib that I am done with a plot?
[ "", "python", "matplotlib", "plot", "" ]
I would like a particular set of Python subprocesses to be as low-impact as possible. I'm already using [nice](http://www.manpagez.com/man/1/nice/) to help limit CPU consumption. But ideally I/O would be limited as well. (If skeptical, please humor me and assume there is value in doing this; it doesn't matter how long they take to run, there can be a lot of them, and there is higher-priority stuff (usually) going on on the same machine, etc.) One possibility appears to be `ionice`. Are there any existing Python packages for invoking `ionice` (Google didn't turn up anything)? It wouldn't be difficult to write code to simply run the `ionice` command; but I'd prefer to avoid writing code that someone else has written/tested; sometimes there are subtle edge cases, etc. And, is there just a better way to limit I/O consumption? The [man page for ionice](http://linux.die.net/man/1/ionice) suggests that the `ionice` value can be affected by the `nice` value, but running this Python 2.6 script appears to disprove that, even for child processes where the `nice` value is inherited: ``` #!/usr/bin/env python import os import multiprocessing def print_ionice(name): print '*** ', name, ' ***' os.system("echo -n 'nice: '; nice") os.system("echo -n 'ionice: '; ionice -p%d" % os.getpid()) for niced in (None, 19): if niced: os.nice(niced) print '**** niced to: ', niced, ' ****' print_ionice('parent') subproc = multiprocessing.Process(target=print_ionice, args=['child']) subproc.start() subproc.join() ``` Which has the following output: ``` $ uname -as Linux x.fake.org 2.6.27-11-server #1 SMP Thu Jan 29 20:13:12 UTC 2009 x86_64 GNU/Linux $ ./foo.py **** niced to: None **** *** parent *** nice: 0 ionice: none: prio 4 *** child *** nice: 0 ionice: none: prio 4 **** niced to: 19 **** *** parent *** nice: 19 ionice: none: prio 4 *** child *** nice: 19 ionice: none: prio 4 ```
[psutil](http://code.google.com/p/psutil/) exposes this functionality (python 2.4 -> 3.2): ``` import psutil, os p = psutil.Process(os.getpid()) p.ionice(psutil.IOPRIO_CLASS_IDLE) ``` Also, starting from Python 3.3 this will be available in python stdlib as well: <http://bugs.python.org/issue10784>
Hm. As a start pointer, you should find what `syscall` number are the `ioprio_set` and `ioprio_get` system calls in your kernel. I'd suggest you check in `/usr/include/asm/unistd_32.h` or `/usr/include/asm/unistd_64.h`, depending on your kernel arch; if not there, start with the suggestion of the `syscall(2)` man page, which should be `/usr/include/sys/syscall.h` and work your way down includes. Given that, you should use `ctypes`, à la: ``` def ioprio_set(which, who, ioprio): rc= ctypes.CDLL('libc.so.6').syscall(289, which, who, ioprio) # some error checking goes here, and possibly exception throwing ``` That's it, more or less. Have fun :)
How to limit I/O consumption of Python processes (possibly using ionice)?
[ "", "python", "linux", "performance", "unix", "" ]
I have an object with a method named `StartDownload()`, that starts three threads. How do I get a notification when each thread has finished executing? Is there a way to know if one (or all) of the thread is finished or is still executing?
There are a number of ways you can do this: 1. Use [Thread.join()](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#join()) in your main thread to wait in a blocking fashion for each Thread to complete, or 2. Check [Thread.isAlive()](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#isAlive()) in a polling fashion -- generally discouraged -- to wait until each Thread has completed, or 3. Unorthodox, for each Thread in question, call [setUncaughtExceptionHandler](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)) to call a method in your object, and program each Thread to throw an uncaught Exception when it completes, or 4. Use locks or synchronizers or mechanisms from [java.util.concurrent](http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html), or 5. More orthodox, create a listener in your main Thread, and then program each of your Threads to tell the listener that they have completed. How to implement Idea #5? Well, one way is to first create an interface: ``` public interface ThreadCompleteListener { void notifyOfThreadComplete(final Thread thread); } ``` then create the following class: ``` public abstract class NotifyingThread extends Thread { private final Set<ThreadCompleteListener> listeners = new CopyOnWriteArraySet<ThreadCompleteListener>(); public final void addListener(final ThreadCompleteListener listener) { listeners.add(listener); } public final void removeListener(final ThreadCompleteListener listener) { listeners.remove(listener); } private final void notifyListeners() { for (ThreadCompleteListener listener : listeners) { listener.notifyOfThreadComplete(this); } } @Override public final void run() { try { doRun(); } finally { notifyListeners(); } } public abstract void doRun(); } ``` and then each of your Threads will extend `NotifyingThread` and instead of implementing `run()` it will implement `doRun()`. Thus when they complete, they will automatically notify anyone waiting for notification. Finally, in your main class -- the one that starts all the Threads (or at least the object waiting for notification) -- modify that class to `implement ThreadCompleteListener` and immediately after creating each Thread add itself to the list of listeners: ``` NotifyingThread thread1 = new OneOfYourThreads(); thread1.addListener(this); // add ourselves as a listener thread1.start(); // Start the Thread ``` then, as each Thread exits, your `notifyOfThreadComplete` method will be invoked with the Thread instance that just completed (or crashed). Note that better would be to `implements Runnable` rather than `extends Thread` for `NotifyingThread` as extending Thread is usually discouraged in new code. But I'm coding to your question. If you change the `NotifyingThread` class to implement `Runnable` then you have to change some of your code that manages Threads, which is pretty straightforward to do.
**Solution using [CyclicBarrier](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CyclicBarrier.html)** ``` public class Downloader { private CyclicBarrier barrier; private final static int NUMBER_OF_DOWNLOADING_THREADS; private DownloadingThread extends Thread { private final String url; public DownloadingThread(String url) { super(); this.url = url; } @Override public void run() { barrier.await(); // label1 download(url); barrier.await(); // label2 } } public void startDownload() { // plus one for the main thread of execution barrier = new CyclicBarrier(NUMBER_OF_DOWNLOADING_THREADS + 1); // label0 for (int i = 0; i < NUMBER_OF_DOWNLOADING_THREADS; i++) { new DownloadingThread("http://www.flickr.com/someUser/pic" + i + ".jpg").start(); } barrier.await(); // label3 displayMessage("Please wait..."); barrier.await(); // label4 displayMessage("Finished"); } } ``` **label0** - cyclic barrier is created with number of parties equal to the number of executing threads plus one for the main thread of execution (in which startDownload() is being executed) **label 1** - n-th DownloadingThread enters the waiting room **label 3** - NUMBER\_OF\_DOWNLOADING\_THREADS have entered the waiting room. Main thread of execution releases them to start doing their downloading jobs in more or less the same time **label 4** - main thread of execution enters the waiting room. This is the 'trickiest' part of the code to understand. It doesn't matter which thread will enter the waiting room for the second time. It is important that whatever thread enters the room last ensures that all the other downloading threads have finished their downloading jobs. **label 2** - n-th DownloadingThread has finished its downloading job and enters the waiting room. If it is the last one i.e. already NUMBER\_OF\_DOWNLOADING\_THREADS have entered it, including the main thread of execution, main thread will continue its execution only when all the other threads have finished downloading.
How to know if other threads have finished?
[ "", "java", "multithreading", "" ]
I would like to take a string ``` var a = "http://example.com/aa/bb/" ``` and process it into an object such that ``` a.hostname == "example.com" ``` and ``` a.pathname == "/aa/bb" ```
``` var getLocation = function(href) { var l = document.createElement("a"); l.href = href; return l; }; var l = getLocation("http://example.com/path"); console.debug(l.hostname) >> "example.com" console.debug(l.pathname) >> "/path" ```
The modern way: ``` new URL("http://example.com/aa/bb/") ``` Returns an object with properties `hostname` and `pathname`, along with [a few others](https://developer.mozilla.org/en-US/docs/Web/API/URL#instance_properties), most notably, `port` and `searchParams` (prepared instance of [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)). Note that `host` contains both `hostname`+`port`, but `hostname` only contains the domain (and **not the port**). The first argument is a relative or absolute URL; if it's relative, then you need to specify the second argument (the base URL). For example, for a URL relative to the current page: ``` new URL("/aa/bb/", location) ``` In addition to browsers, [this API is also available in Node.js](https://nodejs.org/api/url.html#url_the_whatwg_url_api) since v7, through `require('url').URL`.
How do I parse a URL into hostname and path in javascript?
[ "", "javascript", "url", "" ]
i want to get the data of five table having a common id from one query can we do this , for example tbl\_student,tbl\_batch,tbl\_section,tbl\_level,tbl\_faculty all have a common id college\_id how can i get all the tables value with one query if anybody can help me i would be greatful
If I understand you correctly that sounds like a [join](http://en.wikipedia.org/wiki/Join_(SQL)). ``` select * from tbl_student st join tbl_batch ba on ba.college_id=st.college_id join tbl_section se on se.college_id=st.college_id join tbl_level le on le.college_id=st.college_id join tbl_faculty fa on fa.college_id=st.college_id ``` This is most probably not exactly the way you want to get the data because the data model would not make much sense. Hopefully you get the idea though.
``` SELECT fields FROM table1 LEFT JOIN table2 ON table1.id = table2.id LEFT JOIN table3 ON table1.id = table3.id LEFT JOIN table4 ON table1.id = table4.id ```
can we get the data from five tables having a common id with one query?
[ "", "sql", "mysql", "join", "" ]
I'm trying to convert an ArrayList containing Integer objects to primitive int[] with the following piece of code, but it is throwing compile time error. Is it possible to convert in Java? ``` List<Integer> x = new ArrayList<Integer>(); int[] n = (int[])x.toArray(int[x.size()]); ```
You can convert, but I don't think there's anything built in to do it automatically: ``` public static int[] convertIntegers(List<Integer> integers) { int[] ret = new int[integers.size()]; for (int i=0; i < ret.length; i++) { ret[i] = integers.get(i).intValue(); } return ret; } ``` (Note that this will throw a NullPointerException if either `integers` or any element within it is `null`.) EDIT: As per comments, you may want to use the list iterator to avoid nasty costs with lists such as `LinkedList`: ``` public static int[] convertIntegers(List<Integer> integers) { int[] ret = new int[integers.size()]; Iterator<Integer> iterator = integers.iterator(); for (int i = 0; i < ret.length; i++) { ret[i] = iterator.next().intValue(); } return ret; } ```
If you are using [java-8](/questions/tagged/java-8 "show questions tagged 'java-8'") there's also another way to do this. ``` int[] arr = list.stream().mapToInt(i -> i).toArray(); ``` What it does is: * getting a `Stream<Integer>` from the list * obtaining an `IntStream` by mapping each element to itself (identity function), unboxing the `int` value hold by each `Integer` object (done automatically since Java 5) * getting the array of `int` by calling `toArray` You could also explicitly call `intValue` via a method reference, i.e: ``` int[] arr = list.stream().mapToInt(Integer::intValue).toArray(); ``` It's also worth mentioning that you could get a `NullPointerException` if you have any `null` reference in the list. This could be easily avoided by adding a filtering condition to the stream pipeline like this: ``` //.filter(Objects::nonNull) also works int[] arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray(); ``` Example: ``` List<Integer> list = Arrays.asList(1, 2, 3, 4); int[] arr = list.stream().mapToInt(i -> i).toArray(); //[1, 2, 3, 4] list.set(1, null); //[1, null, 3, 4] arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray(); //[1, 3, 4] ```
How to convert an ArrayList containing Integers to primitive int array?
[ "", "java", "arrays", "arraylist", "primitive-types", "" ]
What variables do I have to set/pass as arguments to the JVM to get Log4j to run properly? And by properly I mean not complain and print to the console. Can I see a typical example? Note: I need to avoid creating a `log4j.properties` file in the application.
Do you have a log4j configuration file ? Just reference it using ``` -Dlog4j.configuration={path to file} ``` where {path to file} should be prefixed with `file:` **Edit:** If you are working with log4j2, you need to use ``` -Dlog4j.configurationFile={path to file} ``` Taken from answer <https://stackoverflow.com/a/34001970/552525>
The solution is using of the following JVM argument: ``` -Dlog4j.configuration={path to file} ``` If the file is NOT in the classpath (in `WEB-INF/classes` in case of Tomcat) but somewhere on you disk, use `file:`, like ``` -Dlog4j.configuration=file:C:\Users\me\log4j.xml ``` More information and examples here: <http://logging.apache.org/log4j/1.2/manual.html>
Log4j configuration via JVM argument(s)?
[ "", "java", "logging", "log4j", "" ]
When you overload the - unary operators, for an immutable type, you can write it like: ``` public static Point3 operator - (Point3 p) { return new Point3 (-p.X, -p.Y, -p.Z); } ``` But for the + unary operator, how should you implement it? Like this: ``` public static Point3 operator + (Point3 p) { return p; } ``` or like this: ``` public static Point3 operator + (Point3 p) { return new Point3 (p); } ```
Either way is fine. You are not mutating the original object in either of the two methods. If you call `string.substring(0, string.length())`, there is no reason why the original string cannot be returned. The only contract you sign with immutability is that once an object is created, it doesn't change.
In my opinion it depends on implementation of Point3.Equals(). Consider the following code: ``` Dictionary<Point3, string> cache; Point3 pointA = new Point3(1, 2, 3); Point3 pointB = new Point3(1, 2, 3); cached[pointA] = "Value Aaa"; cached[pointB] = "Value Bbb"; Console.WriteLine(cached[pointA]); Console.WriteLine(cached[pointB]); ``` If Point3 has reference semantics (pointA.Equals(pointB) when they are the same object), this will output: ``` Value Aaa Value Bbb ``` If Point3 has value semantics (pointA.Equals(pointB) when their x, y and z values are equal), this will output: ``` Value Bbb Value Bbb ``` With value semantics it would not really matter if you create a new object or not. You could probably just return the same to avoid creating garbage. If your type has reference semantics, you probably want the unary plus to create a new object, so that it behaves the same way as the other operators.
Overloading +/- unary operators
[ "", "c#", ".net", "operators", "" ]
I myself am one of these types of coders, who never learned coding in a formal setting, but am instead, self-taught by the use of copy and paste scripts, and pre-authored works available through GPL projects and premium software's(which is often the way commerical script companies show you how to change, or update code in their script ie. "Copy & paste this on line 234, etc..")... this are my beginnings. I don't understand how what I do works, but I am getting good at what I do with code, though I feel because of my informal learning methods, that I lack in knowledge, some of the really simple, but necessary principles of web coding in general(the ins and outs of servers, browsers, etc). I feel as though I have started from the inside of understanding code, the practical side.. and lack the basic fundamentals, and theorized understanding of what I am doing. I also know quite a few others who are the same, who started learning in the same communities as I, and are pretty much at the same point as me... Feeling as though something big is missing from the picture. I see the lacking in my discipline when I attempt to use PHP authoring tools, which I find very challenging to understand... and this is becoming a downfall on the time frames in which I complete my projects(having to hand code everything). I also find it difficult to ask for help at times, for lack of the specific language that comes with programming, and being able to use the right words to explain the intricacy of my problem. I was a hairdresser by trade, I worked as a bartender, and hotel manager, I'm a business consultant by profession. I've been learning web development slowly now for 3 years, and I have taken on quite a few commercial projects over the past 2 years, but I'm obviously feeling some lacking in my skills & overall knowledge. Basically, Id like to ask any experienced coders who've had similar beginnings to give me an idea on how I can adapt my coding disciplines to be more effective and productive. What would someone with such an informal understanding of programming want to seek to learn, and understand. What are the things I must know as a programmer... and what is a basic overview of the whole picture???? Feel free to direct me to articles Any help is always appreciated. Lea **Edit:** Just to give a round up of my actual capabilities. I am a programmer, I do author my own code from scratch.. and sell my work. I can write PHP functions, and classes, use mysql, have a good working understanding of html & css, and am very good in the design aspects(web graphics), and am learning javascript/ajax/jquery, as I am using jquery in most of my projects. Thanks for all of the answers so far!
We all learn differently, so don't feel handicapped because of the way you've entered the field. I guess the simplest, easiest thing I can suggest would be to get yourself a PHP book (seeing as that's what you're familiar with right now) and start from there to build up confidence. In your spare time, just create some very small basic apps to practice without any pressure. Then take on a language like Python, Java or .NET.. depending on what takes your fancy. With a language or two under your belt, then you can take on books like Code Complete, which will cover some of the more esoteric areas of software development. Good luck, this is a profession where you really never stop learning.
* Realise that "copy and paste programming" is not actually programming, despite the name. The act of "programming" is figuring out how something should work, and what code is needed to make that work. Therefore, when you copy and paste some code, it is someone else who did the programming. This isn't a bad thing necessarily, as you shouldn't always need to write code yourself. But to call yourself a programmer, you do need to have written the code yourself. * You will want to start humble. Don't try to write a large complex application as your first step into programming. There is a good reason why most people who are taught programming are first taught how to print "Hello, world". This is because there is a lot more that you will need to know than just what code to use - you need to know where code execution starts and how it flows, and that sort of thing. You need to be able to look at the code and step through it mentally, knowing where program execution will go next, so you understand how it will work. * Take a tutorial or course in programming. There is so much free stuff online. Do not trust any tutorial that just gives you large chunks of code, make sure it forces you to actually come up with some code yourself. Do exercises such as sorting strings, calculating fibonacci sequences, and the like, and "echo" or "print" the results. Learn about conditional statements (like "if") and the "for" loop and play with these to do various things. * GUI or forms programming is more complicated; make sure you know the fundamentals of the language before you go looking through any API or framework documentation to see what the language can do. You'll need to know how execution flows, how to write functions, what types of variables you can use etc before you can effectively use an API or framework anyway. It is boring not being able to do cool graphics or forms and sticking to basic text or number processing, but you have to walk before running. Make sure you are doing, not just reading. When you learn about something new like the Array type, the "while" statement, try it out. By actually doing it, you'll "get it" a lot faster than just reading a book or website and you may be more likely to remember it. * Read books about programming. Some people say you should learn C before you learn anything else. I don't necessarily agree, but if you do learn C then the book to read is "The C Programming Language" by Kernighan and Ritchie. Many programming books are very interesting but either not suitable for beginners, or aren't going to teach you how to actually begin programming. This one is an exception. * Use a decent text editor with syntax highlighting and line numbering. That's all you should need. A big IDE that also does code completion and the like is not necessarily helpful at the learning stage. Don't spend too long choosing one or setting it up. If you don't already have one, just get Notepad++ (if you're on Windows) and be done with it. If you don't like it you can change it once you get more proficient. Or if you've already paid for Microsoft Visual Studio then use that, but don't go out and get it just for the sake of learning a language. Avoid falling into the trap of spending all your time sharpening your tools and no time using them.
Help For The Copy & Paste Generation Of Coders
[ "", "php", "" ]
I've tried following the PHP.net instructions for doing `SELECT` queries but I am not sure the best way to go about doing this. I would like to use a parameterized `SELECT` query, if possible, to return the `ID` in a table where the `name` field matches the parameter. This should return one `ID` because it will be unique. I would then like to use that `ID` for an `INSERT` into another table, so I will need to determine if it was successful or not. I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this: ``` $db = new PDO("..."); $statement = $db->prepare("select id from some_table where name = :name"); $statement->execute(array(':name' => "Jimbo")); $row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator ``` You insert in the same way: ``` $statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)"); $statement->execute(array(':some_id' => $row['id'])); ``` I recommend that you configure PDO to throw exceptions upon error. You would then get a `PDOException` if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the `$db` object: ``` $db = new PDO("..."); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); ```
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well. ``` $nametosearch = "Tobias"; $conn = new PDO("server", "username", "password"); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name"); $sth->bindParam(':name', $nametosearch); // Or sth->bindParam(':name', $_POST['namefromform']); depending on application $sth->execute(); ```
How can I properly use a PDO object for a parameterized SELECT query
[ "", "php", "mysql", "select", "pdo", "" ]
I am trying to create a simple user control that is a slider. When I add a AjaxToolkit SliderExtender to the user control I get this (\*&$#()@# error: ``` Server Error in '/' Application. The Controls collection cannot be modified because the control contains code blocks (i.e. `<% ... %>`). Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. `<% ... %>`). Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [HttpException (0x80004005): The Controls collection cannot be modified because the control contains code blocks (i.e. `<% ... %>`).] System.Web.UI.ControlCollection.Add(Control child) +8677431 AjaxControlToolkit.ScriptObjectBuilder.RegisterCssReferences(Control control) in d:\E\AjaxTk-AjaxControlToolkit\Release\AjaxControlToolkit\ExtenderBase\ScriptObjectBuilder.cs:293 AjaxControlToolkit.ExtenderControlBase.OnLoad(EventArgs e) in d:\E\AjaxTk-AjaxControlToolkit\Release\AjaxControlToolkit\ExtenderBase\ExtenderControlBase.cs:306 System.Web.UI.Control.LoadRecursive() +50 System.Web.UI.Control.LoadRecursive() +141 System.Web.UI.Control.LoadRecursive() +141 System.Web.UI.Control.LoadRecursive() +141 System.Web.UI.Control.LoadRecursive() +141 System.Web.UI.Control.LoadRecursive() +141 System.Web.UI.Control.LoadRecursive() +141 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627 Version Information: Microsoft .NET Framework Version:2.0.50727.3074; ASP.NET Version:2.0.50727.3074 ``` I have tried putting a placeholder in the user control and adding the textbox and slider extender to the placeholder programmatically and I still get the error. Here is the simple code: ``` <table cellpadding="0" cellspacing="0" style="width:100%"> <tbody> <tr> <td></td> <td> <asp:Label ID="lblMaxValue" runat="server" Text="Maximum" CssClass="float_right" /> <asp:Label ID="lblMinValue" runat="server" Text="Minimum" /> </td> </tr> <tr> <td style="width:60%;"> <asp:CheckBox ID="chkOn" runat="server" /> <asp:Label ID="lblPrefix" runat="server" />:&nbsp; <asp:Label ID="lblSliderValue" runat="server" />&nbsp; <asp:Label ID="lblSuffix" runat="server" /> </td> <td style="text-align:right;width:40%;"> <asp:TextBox ID="txtSlider" runat="server" Text="50" style="display:none;" /> <ajaxToolkit:SliderExtender ID="seSlider" runat="server" BehaviorID="seSlider" TargetControlID="txtSlider" BoundControlID="lblSliderValue" Orientation="Horizontal" EnableHandleAnimation="true" Length="200" Minimum="0" Maximum="100" Steps="1" /> </td> </tr> </tbody> </table> ``` What is the problem?
First, start the code block with <%# instead of <%= : ``` <head id="head1" runat="server"> <title>My Page</title> <link href="css/common.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="<%# ResolveUrl("~/javascript/leesUtils.js") %>"></script> </head> ``` This changes the code block from a Response.Write code block to a databinding expression. Since `<%# ... %>` databinding expressions aren't code blocks, the CLR won't complain. Then in the code for the master page, you'd add the following: ``` protected void Page_Load(object sender, EventArgs e) { Page.Header.DataBind(); } ```
I just ran into this problem as well but found another solution. I found that wrapping the code blocks with a asp:PlaceHolder-tag solves the problem. ``` <asp:PlaceHolder runat="server"> <meta name="ROBOTS" content="<%= this.ViewData["RobotsMeta"] %>" /> </asp:PlaceHolder> ``` (The CMS I'm using is inserting into the head-section from some code behind which restricted me from adding custom control blocks with various information like meta-tags etc so this is the only way it works for me.)
"The Controls collection cannot be modified because the control contains code blocks"
[ "", "c#", "asp.net", "user-controls", "" ]
I am a **Mac user** who wants to run a few **.exe files** from my Java process using Process and Runtime classes. I know that it is **not possible** to execute .exe files in general in **Mac OS X**. Is there a Mac application which can wrap these .exe files so that they can be executed ? Does Apple provide anything by itself ? The alternative I am using now is to run the Java process in Windows. Yet, it is cumbersome in general.
[Darwine](http://darwine.sourceforge.net/) Edit: I should probably point out that this is not a 100% solution. Virtualized Windows will nearly always work better, through Parallels or some similar virtualization software. But Darwine is free and runs most Windows software acceptably.
Besides wine you can get [VirtualBox](http://www.virtualbox.org/)(free), [Parallels](http://www.parallels.com/products/desktop/)($$$) or [VMWare](https://www.vmware.com/products/fusion/)($$$).
Running .exe files in Mac OS X
[ "", "java", "macos", "exe", "" ]
I have a simple UserControl for database paging, that uses a controller to perform the actual DAL calls. I use a `BackgroundWorker` to perform the heavy lifting, and on the `OnWorkCompleted` event I re-enable some buttons, change a `TextBox.Text` property and raise an event for the parent form. Form A holds my UserControl. When I click on some button that opens form B, even if I don't do anything "there" and just close it, and try to bring in the next page from my database, the `OnWorkCompleted` gets called on the worker thread (and not my Main thread), and throws a cross-thread exception. At the moment I added a check for `InvokeRequired` at the handler there, but isn't the whole point of `OnWorkCompleted` is to be called on the Main thread? Why wouldn't it work as expected? EDIT: I have managed to narrow down the problem to arcgis and `BackgroundWorker`. I have the following solution wich adds a Command to arcmap, that opens a simple `Form1` with two buttons. The first button runs a `BackgroundWorker` that sleeps for 500ms and updates a counter. In the `RunWorkerCompleted` method it checks for `InvokeRequired`, and updates the title to show whethever the method was originaly running inside the main thread or the worker thread. The second button just opens `Form2`, which contains nothing. At first, all the calls to `RunWorkerCompletedare` are made inside the main thread (As expected - thats the whold point of the RunWorkerComplete method, At least by what I understand from the [MSDN](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(VS.80).aspx) on `BackgroundWorker`) After opening and closing `Form2`, the `RunWorkerCompleted` is always being called on the worker thread. I want to add that I can just leave this solution to the problem as is (check for `InvokeRequired` in the `RunWorkerCompleted` method), but I want to understand why it is happening against my expectations. In my "real" code I'd like to always know that the `RunWorkerCompleted` method is being called on the main thread. I managed to pin point the problem at the `form.Show();` command in my `BackgroundTesterBtn` - if I use `ShowDialog()` instead, I get no problem (`RunWorkerCompleted` always runs on the main thread). I do need to use `Show()` in my ArcMap project, so that the user will not be bound to the form. I also tried to reproduce the bug on a normal WinForms project. I added a simple project that just opens the first form without ArcMap, but in that case I couldn't reproduce the bug - the `RunWorkerCompleted` ran on the main thread, whether I used `Show()` or `ShowDialog()`, before and after opening `Form2`. I tried adding a third form to act as a main form before my `Form1`, but it didn't change the outcome. [Here](http://depositfiles.com/files/1cu4o0493) is my simple sln (VS2005sp1) - it requires ESRI.ArcGIS.ADF(9.2.4.1420) ESRI.ArcGIS.ArcMapUI(9.2.3.1380) ESRI.ArcGIS.SystemUI (9.2.3.1380)
It looks like a bug: <http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=116930> <http://thedatafarm.com/devlifeblog/archive/2005/12/21/39532.aspx> So I suggest using the bullet-proof (pseudocode): ``` if(control.InvokeRequired) control.Invoke(Action); else Action() ```
> Isn't the whole point of `OnWorkCompleted` is to be called on the Main thread? Why wouldn't it work as expected? No, it's not. You can't just go running any old thing on any old thread. Threads are not polite objects that you can simply say "run this, please". A better mental model of a thread is a freight train. Once it's going, it's off on it's own track. You can't change it's course or stop it. If you want to influence it, you either have to wait til it gets to the next train station (eg: have it manually check for some events), or derail it (`Thread.Abort` and CrossThread exceptions have much the same consequences as derailing a train... beware!). Winforms controls *sort of* support this behaviour (They have `Control.BeginInvoke` which lets you run any function on the UI thread), but that only works because they have a special hook into the windows UI message pump and write some special handlers. To go with the above analogy, their train checks in at the station and looks for new directions periodically, and you can use that facility to post it your own directions. The `BackgroundWorker` is designed to be general purpose (it can't be tied to the windows GUI) so it can't use the windows `Control.BeginInvoke` features. It has to assume that your main thread is an unstoppable 'train' doing it's own thing, so the completed event has to run in the worker thread or not at all. However, as you're using winforms, in your `OnWorkCompleted` handler, you can get the Window to execute *another* callback using the `BeginInvoke` functionality I mentioned above. Like this: ``` // Assume we're running in a windows forms button click so we have access to the // form object in the "this" variable. void OnButton_Click(object sender, EventArgs e ) var b = new BackgroundWorker(); b.DoWork += ... blah blah // attach an anonymous function to the completed event. // when this function fires in the worker thread, it will ask the form (this) // to execute the WorkCompleteCallback on the UI thread. // when the form has some spare time, it will run your function, and // you can do all the stuff that you want b.RunWorkerCompleted += (s, e) { this.BeginInvoke(WorkCompleteCallback); } b.RunWorkerAsync(); // GO! } void WorkCompleteCallback() { Button.Enabled = false; //other stuff that only works in the UI thread } ``` [Also, don't forget this:](http://msdn.microsoft.com/en-us/library/system.componentmodel.runworkercompletedeventargs.result.aspx) > Your RunWorkerCompleted event handler should always check the Error and Cancelled properties before accessing the Result property. If an exception was raised or if the operation was canceled, accessing the Result property raises an exception.
BackgroundWorker OnWorkCompleted throws cross-thread exception
[ "", "c#", "winforms", "backgroundworker", "arcgis", "multithreading", "" ]
how to send and return values in modal dialog form
Try this. It's designed to be a counterpart to MessageBox. It doesn't change its styling based on OS, though. It looks like Vista's. Here's an example of it in action, from it's original home (a Paint.NET plugin). It will expand to fit the prompt. ![](https://i185.photobucket.com/albums/x302/illusionaryz/inputboxexample.png) InputBox.cs: ``` internal partial class InputBoxForm : Form { Size lbltextoriginalsize; Size pnlwhiteoroginalsize; public InputBoxForm(string text, string defaultvalue, string caption) { InitializeComponent(); this.pnlWhite.Resize += new System.EventHandler(this.pnlWhite_Resize); this.lblText.Resize += new System.EventHandler(this.lblText_Resize); picIcon.Image = SystemIcons.Question.ToBitmap(); lbltextoriginalsize = lblText.Size; pnlwhiteoroginalsize = pnlWhite.Size; this.lblText.Text = text; this.txtOut.Text = defaultvalue; this.Text = caption; } private void lblText_Resize(object sender, EventArgs e) { pnlWhite.Size += lblText.Size - lbltextoriginalsize; } private void pnlWhite_Resize(object sender, EventArgs e) { this.Size += pnlWhite.Size - pnlwhiteoroginalsize; } public string Value { get { return txtOut.Text; } } } /// /// A counterpart to the MessageBox class, designed to look similar (at least on Vista) /// public static class InputBox { public static DialogResult Show(string text, out string result) { return ShowCore(null, text, null, null, out result); } public static DialogResult Show(IWin32Window owner, string text, out string result) { return ShowCore(owner, text, null, null, out result); } public static DialogResult Show(string text, string defaultValue, out string result) { return ShowCore(null, text, defaultValue, null, out result); } public static DialogResult Show(IWin32Window owner, string text, string defaultValue, out string result) { return ShowCore(owner, text, defaultValue, null, out result); } public static DialogResult Show(string text, string defaultValue, string caption, out string result) { return ShowCore(null, text, defaultValue, caption, out result); } public static DialogResult Show(IWin32Window owner, string text, string defaultValue, string caption, out string result) { return ShowCore(owner, text, defaultValue, caption, out result); } private static DialogResult ShowCore(IWin32Window owner, string text, string defaultValue, string caption, out string result) { InputBoxForm box = new InputBoxForm(text, defaultValue, caption); DialogResult retval = box.ShowDialog(owner); result = box.Value; return retval; } } ``` InputBox.Designer.cs: ``` partial class InputBoxForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.pnlWhite = new System.Windows.Forms.Panel(); this.lblText = new System.Windows.Forms.Label(); this.picIcon = new System.Windows.Forms.PictureBox(); this.txtOut = new System.Windows.Forms.TextBox(); this.btnOK = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.pnlWhite.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picIcon)).BeginInit(); this.SuspendLayout(); // // pnlWhite // this.pnlWhite.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pnlWhite.BackColor = System.Drawing.Color.White; this.pnlWhite.Controls.Add(this.lblText); this.pnlWhite.Controls.Add(this.picIcon); this.pnlWhite.Controls.Add(this.txtOut); this.pnlWhite.Location = new System.Drawing.Point(0, 0); this.pnlWhite.Margin = new System.Windows.Forms.Padding(0); this.pnlWhite.MinimumSize = new System.Drawing.Size(235, 84); this.pnlWhite.Name = "pnlWhite"; this.pnlWhite.Size = new System.Drawing.Size(235, 84); this.pnlWhite.TabIndex = 0; // // lblText // this.lblText.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.lblText.AutoSize = true; this.lblText.Location = new System.Drawing.Point(64, 26); this.lblText.Margin = new System.Windows.Forms.Padding(3, 0, 30, 30); this.lblText.MinimumSize = new System.Drawing.Size(159, 0); this.lblText.Name = "lblText"; this.lblText.Size = new System.Drawing.Size(159, 13); this.lblText.TabIndex = 2; // // picIcon // this.picIcon.BackColor = System.Drawing.Color.White; this.picIcon.Location = new System.Drawing.Point(25, 26); this.picIcon.Name = "picIcon"; this.picIcon.Size = new System.Drawing.Size(32, 32); this.picIcon.TabIndex = 1; this.picIcon.TabStop = false; // // txtOut // this.txtOut.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtOut.Location = new System.Drawing.Point(67, 50); this.txtOut.Name = "txtOut"; this.txtOut.Size = new System.Drawing.Size(159, 20); this.txtOut.TabIndex = 5; // // btnOK // this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOK.Location = new System.Drawing.Point(42, 96); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(88, 26); this.btnOK.TabIndex = 3; this.btnOK.Text = "OK"; this.btnOK.UseVisualStyleBackColor = true; // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(138, 96); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(88, 26); this.btnCancel.TabIndex = 4; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; // // InputBoxForm // this.AcceptButton = this.btnOK; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(235, 133); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.pnlWhite); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "InputBoxForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.pnlWhite.ResumeLayout(false); this.pnlWhite.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.picIcon)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel pnlWhite; private System.Windows.Forms.PictureBox picIcon; private System.Windows.Forms.Label lblText; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.TextBox txtOut; } ```
I usually do something like this: ``` public class MyInputDialog : Form { public static string Execute(string Prompt) { using (var f = new MyInputDialog() ) { f.lblPrompt.Text = Prompt; f.ShowModal(); return f.txtInput.Text; } } } ``` Leaving out all the error handling, what if the user cancels, etc.
Return values from dialog box
[ "", "c#", "" ]
I have lots of object defined in the system, perhaps 1000 objects, and some of them have this method: ``` public Date getDate(); ``` Is there anyway I can do something like this: ``` Object o = getFromSomeWhere.....; Method m = o.getMethod("getDate"); Date date = (Date) m.getValue(); ```
If you *can* make them all implement an interface, that would certainly be the best option. However, reflection will also work, and your code was nearly there: ``` Object o = getFromSomeWhere.....; Method m = o.getClass().getMethod("getDate"); Date date = (Date) m.invoke(o); ``` (There's a bunch of exceptions you'll need to handle, admittedly...) For a full example: ``` import java.lang.reflect.*; import java.util.*; public class Test { public static void main(String[] args) throws Exception { Object o = new Test(); Method m = o.getClass().getMethod("getDate"); Date date = (Date) m.invoke(o); System.out.println(date); } public Date getDate() { return new Date(); } } ```
Try this: ``` Object aDate = new Date(); Method aMethod = aDate.getClass().getMethod("getDate", (Class<Void>[]) null); Object aResult = aMethod.invoke(aDate, (Void) null); ``` You should add try-catch to determine if there really is a method getDate before invoking.
Java Question, how to get the value of a method from an unknown object
[ "", "java", "dynamic", "methods", "" ]
I am using Python 2.5.2. How can I tell whether it is `CPython` or `IronPython` or `Jython`? Another question: how can I **use a DLL** developed in VB.NET in my project?
If you downloaded it as the default thing from python.org, it's CPython. That's the “normal” version of Python, the one you get when you use the command “python”, and the one you'll have unless you specifically went looking for the projects targeting Java/CIL. And it's CPython because neither of the other projects have reached version number 2.5.2. > How can i use a dll developed in VB.NET in to my project? From CPython, using [Python-for-.NET](http://pythonnet.sourceforge.net/)(\*) and clr.AddReference. (\*: actually a bit of a misnomer, as with CPython in control it is more like .NET-for-Python.)
``` import platform platform.python_implementation() ``` The above one provide the type of interpreter you use .
How do I tell which Python interpreter I'm using?
[ "", "python", "" ]
### Background I have a `DataGridView` control which I am using, and I added my handler below to the `DataGridView.CellFormatting` event so the values in some cells can be made more human-readable. This event handler has been working great, formatting all values without issue. Recently however, I have discovered a very rare circumstance causes an unusual bug. The column in my `DataGridView` for the item's due date always has an `int` value. `0` indicates the event is never due, any other value is a UTC timestamp for the due date. The MySQL db column corresponding doesn't allow nulls. When the user has moved from one `DataGridView` row with a due date, to another `DataGridView` row with a due date (at this point everything is still appears fine), and then presses a button which reloads the data from the database (without sending updates, essentially calling `DataAdapter.Fill()`), the program generates a `StackOverflowException`\*\*. ### No recursion? What is so unusual to me is that I do not see where the recursion or infinte-looping is. I added `int cellFormatCallCount` as a class member, and increment it during each call, but at the time the exception is thrown, the debugger shows the value of that `int` as 1, which I would expect since I wasn't under the impression and recursion was occuring. Can somebody help me? How can I view a stack trace? In VS2008 it says: `{Cannot evaluate expression because the current thread is in a stack overflow state.}` Best regards, Robinson ``` private int cellFormatCallCount = 0; private void myDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { try { // to format the cell, we will need to know its value and which column its in string value = ""; string column = ""; // the event is sometimes called where the value property is null if (e.Value != null) { cellFormatCallCount++; // here is my test for recursion, this class member will increment each call // This is the line that throws the StackOverflowException /* ********************* */ value = e.Value.ToString(); /* ********************* */ column = actionsDataGridView.Columns[e.ColumnIndex].Name; } else { return; // null values cannont be formatted, so return } if (column == "id") { // different code for formatting each column } else if (column == "title") { // ... } else { // ... } } finally { cellFormatCallCount = 0; // after we are done with the formatting, reset our recursion counter } } ```
Apparently e.Value.ToString() invokes the CellFormatting event again. That seems somewhat logical. It should be easy enough to find out with a debugger. But the actual recursion could be caused somewhere else, like in the per-column formatting that you omitted. Your recursion check isn't reliable since Value==null will also reset it, and it appears to be shared by all columns. Make it surround the e.Value.ToString() more tightly: ``` if (e.Value != null) { cellFormatCallCount++; System.Diagnostics.Debug.Assert(cellFormatCallCount <= 1, "Recursion"); value = e.Value.ToString(); cellFormatCallCount--; ... } ```
Totally random guess (with no stack trace it's all I can do)... Are you attempting to display/format a type which has a potentially recursive `ToString()`? ``` public string ToString() { return ... this.ToString() ... // or return String.Format("The value is {0}", this); } ``` A typo/error like that could cause a `StackOverflowException`...
StackOverflowException without recursion or infinite loop?
[ "", "c#", "datagridview", "recursion", "stack-overflow", "" ]
I'm working on an application that lets registered users create or upload content, and allows anonymous users to view that content and browse registered users' pages to find that content - this is very similar to how a site like Flickr, for example, allows people to browse its users' pages. To do this, I need a way to identify the user in the anonymous HTTP GET request. A user should be able to type `http://myapplication.com/browse/<userid>/<contentid>` and get to the right page - should be unique, but mustn't be something like the user's email address, for privacy reasons. Through Google App Engine, I can get the email address associated with the user, but like I said, I don't want to use that. I can have users of my application pick a unique user name when they register, but I would like to make that optional if at all possible, so that the registration process is as short as possible. Another option is to generate some random cookie (a GUID?) during the registration process, and use that, I don't see an obvious way of guaranteeing uniqueness of such a cookie without a trip to the database. Is there a way, given an App Engine user object, of getting a unique identifier for that object that can be used in this way? I'm looking for a Python solution - I forgot that GAE also supports Java now. Still, I expect the techniques to be similar, regardless of the language.
Your timing is impeccable: Just yesterday, a new release of the SDK came out, with support for [unique, permanent user IDs](http://code.google.com/appengine/docs/python/users/userclass.html#User_user_id). They meet all the criteria you specified.
I think you should distinguish between two types of users: 1) users that have logged in via Google Accounts or that have already registered on your site with a non-google e-mail address 2) users that opened your site for the first time and are not logged in in any way For the second case, I can see no other way than to generate some random string (e.g. via `uuid.uuid4()` or from this user's session cookie key), as an anonymous user does not carry any unique information with himself. For users that are logged in, however, you already have a unique identifier -- their e-mail address. I agree with your privacy concerns -- you shouldn't use it as an identifier. Instead, how about generating a string that *seems* random, but is in fact generated from the e-mail address? Hashing functions are perfect for this purpose. Example: ``` >>> import hashlib >>> email = 'user@host.com' >>> salt = 'SomeLongStringThatWillBeAppendedToEachEmail' >>> key = hashlib.sha1('%s$%s' % (email, salt)).hexdigest() >>> print key f6cd3459f9a39c97635c652884b3e328f05be0f7 ``` As `hashlib.sha1` is not a random function, but for given data returns always the same result, but it is proven to be practically irreversible, you can safely present the hashed key on the website without compromising user's e-mail address. Also, you can safely assume that no two hashes of distinct e-mails will be the same (they can be, but probability of it happening is very, very small). For more information on hashing functions, consult [the Wikipedia entry](http://en.wikipedia.org/wiki/Cryptographic_hash_function).
Generating unique and opaque user IDs in Google App Engine
[ "", "python", "google-app-engine", "guid", "uniqueidentifier", "" ]
``` for (iy = 0; iy < h; iy++) { double angy = (camera.fov_y / h) * iy; for (ix = 0; ix < w; ix++) { double angx = (camera.fov_x / w) * ix; //output[ix,iy].r = (int)Math.Round(255 * (angy / camera.fov_y); //output[ix,iy].b = (int)Math.Round(255 * (angy / camera.fov_y); double tr = (angx / camera.fov_x) * 255D; double tb = (angy / camera.fov_y) * 255D; Console.Write("({0},{1})",Math.Round(tr),Math.Round(tb)); output.SetPixel(ix, iy, Color.FromArgb(Convert.ToInt32(tr), 0, Convert.ToInt32(tb)) ); Console.Write("."); } Console.WriteLine(); } ``` Can anyone see any immediate problems with that code? The variables `tr` and `tb` always evaluate to 0. I'm happy to provide more information if it is needed.
You haven't given the types for the other variables - in particular, what are the types of `camera.fov_x` and `camera.fov_y`? If they're both integers, then the lines initializing `angx` and `angy` will be evaluated using integer arithmetic. This can be fixed by casting one of the operands: ``` double angy = ((double) camera.fov_y / h) * iy; ``` The `fovy` and `fovx` variables are already doubles though, this isn't the problem. Could you give a complete example of this, which we can compile and test ourselves? EDIT: Koistya Navin's edit is overkill. You only need one operand of an expression to be a double for the whole thing to be computed using double arithmetic. (It needs to be the right expression though - if you do `(a/b) * c` and cast `c` a double, the multiplication will be done with double arithmetic but a/b might still be done as integers.) Here's the listing changed appropriately to make sure double arithmetic is used everywhere it should be: ``` // Changed loops to declare the variable, for stylistic purposes for (int iy = 0; iy < h; iy++) { // Changed here - cast camera.fov_y double angy = ((double) camera.fov_y / h) * iy; for (int ix = 0; ix < w; ix++) { // Changed here - cast camera.fov_x double angx = ((double) camera.fov_x / w) * ix; //output[ix,iy].r = (int)Math.Round(255 * (angy / camera.fov_y); //output[ix,iy].b = (int)Math.Round(255 * (angy / camera.fov_y); double tr = (angx / camera.fov_x) * 255D; double tb = (angy / camera.fov_y) * 255D; Console.Write("({0},{1})", Math.Round(tr), Math.Round(tb)); output.SetPixel(ix, iy, Color.FromArgb(Convert.ToInt32(tr), 0, Convert.ToInt32(tb)) ); Console.Write("."); } Console.WriteLine(); } ```
It know it's not part of your original question, but using SetPixel(..) is not very efficient and could be a problem if you are planning to use it in a ray-tracing engine. You might want to use the LockBits() method, see this [answer](https://stackoverflow.com/questions/190385/how-to-manipulate-images-at-pixel-level-in-c/190395#190395) and [this one](https://stackoverflow.com/questions/541331/effective-way-of-making-negative-of-image-without-external-dlls/552013#552013) for more details. They other way to go is to access the data using "unsafe" C# code, which allows you to uses pointers to the data. See [this question](https://stackoverflow.com/questions/702188/can-this-code-be-optimised) for more info, I got a ~x2 speed-up by using "unsafe" code.
Faulty C# code involving doubles and integers
[ "", "c#", "integer", "double", "" ]
I tried to learn shell(bash) scripting few times but was driven away by the syntax. Then I found Python and was able to do most of the things a shell script can do in Python. I am now not sure whether I should invest my time in learning shell scripting anymore. So I want to ask: What are strengths of shell scripting that make it an indispensable tool as compared to Python? I am not a system administration by profession, but I am interested in setting up Linux systems for home users, hence I think learning shell scripting can become necessary.
* Shell scripting has simpler notations for I/O redirection. * It is simpler to create pipelines out of existing programs in shell. * Shell scripting reuses entire programs. * Shell is universally available (on anything like Unix) - Python is not necessarily installed. 'Tis true that you can do everything in Python that you can do in shell; 'tis also true that there are things that are easy in Python that are hard in shell (just as there are things that are easy in shell but hard in Python). Knowing both will be best in the long term.
**"What are strengths of shell scripting that make it an indispensable tool as compared to Python?"** The shell is not indispensable. Why do you think there are so many? bash, tcsh, csh, sh, etc., etc., Python *is* a shell. Not the one you'd use for running *all* commands, but for scripting, it's ideal. Python is a more-or-less standard part of all Linux distro's. The more traditional shells do too many things. 1. They have a handy user interface for running commands. This includes one-line commands where the shell searches your PATH, forks and execs the requested program. It also includes pipelines, sequences and concurrent programs (using `;`, `|` and `&`) as well as some redirection (using `>` and `<`). 2. They have a crummy little programming-language-like capability for running scripts. This language is rather hard to use and extremely inefficient. Most statements in this language require forking one or more additional processes, wasting time and memory. Running programs from the shell, redirecting stderr to a log file and that kind of thing is good. Do that in the shell. Almost everything else can be done more efficiently and more clearly as a Python script. **You need both**. However, you should never write a script with if-statements or loops in a traditional shell language.
Strengths of Shell Scripting compared to Python
[ "", "python", "shell", "" ]
This is driving me nuts. I have been at it for over 2 hours trying to figure this out... Here is my problem. I am working on a fairly large program that works with Bayesian networks. Here is the main function: ``` using namespace std; int main() { DSL_network net; initializeNetwork(net); setEvidence(net); net.SetDefaultBNAlgorithm(7); net.SetNumberOfSamples(80000); cout << "Samples:\t" << net.GetNumberOfSamples() << endl; updateEvidence(net); //net.WriteFile("test.dsl"); return(DSL_OKAY); } ``` This all works fine. The problem comes when I want to print out a string: ``` using namespace std; int main() { //simple string creation string a = "test"; //should print out "test" cout << a << endl; DSL_network net; initializeNetwork(net); setEvidence(net); net.SetDefaultBNAlgorithm(7); net.SetNumberOfSamples(80000); cout << "Samples:\t" << net.GetNumberOfSamples() << endl; updateEvidence(net); //net.WriteFile("test.dsl"); return(DSL_OKAY); } ``` Here is the output (just from printing the string a...):    ▀ÇΦy♠≈6 ♦ What could be going on? UPDATE: ``` int main() { //simple string creation string a = "test"; //should print out "test" cout << a << endl; return(DSL_OKAY); } ``` still prints ``` ▀ÇΦy♠≈6 ♦ ``` ***BIG UPDATE:*** Here is the recent. I created a brand new project and pasted the code that Neil Butterworth posted (thanks btw). I ran the code and it printed correctly. Then I added the two .lib files to the Linker in the new project (smile.lib for the SMILE library, and wsock32.lib for socket use.) I tried the code again, and it printed the first "test" correctly, then it printed the giberish. It is a problem with one of the .libs I am linking together. I tried each on their own to see if they are just clashing, and it seems that the smile.lib library is causing the problem. I will need to go into their documentation and figure out why. Any ideas? Thanks all for the help Thanks
That's bizarre. I always like to break a problem down to it's minimal case. What does the following program do when you run it? ``` using namespace std; int main() { string a = "test"; cout << a << endl; return 0; } ``` If that works, then there's something else wrong and you need to add in one line at a time until it fails. Then examine that line *very* carefully ("I'm hunting wabbits"). Based on your edit, it may be a different string class being used. Try this: ``` int main() { std::string a = "test"; std::cout << a << std::endl; return 0; } ``` **Update:** Since it works in a new project and not the current one, check the following. * Make sure you're linking with the standard C++ runtimes. * make sure you don't #define `string` as something else (and the includes a `-Dstring=somethingelse` command line option to the compiler). * check the behavior using `std::string`, not just `string`.
Also try this: ``` int main() { //simple string creation string a = "test"; const char* cStr = a.c_str(); //should print out "test" cout << cStr << endl; return(DSL_OKAY); } ``` If the `const char*` line does not cause a compiler error, then we know that `std::str` is an 8 bit string. If the `cout` doesn't cause a compiler error, then we know that `cout` is defined for 8 bit chars. (And if the program produces the same result, then we're still confused :-} **EDIT** (based on your comment below): I notice that the buggy output from "test" works out to 9 characters -- "▀ÇΦy♠≈6 ♦". Try other "test" strings such as, oh, "retest" or "foo". I suspect that your output will generally be 2x or 2x+1 the number of chars in the original string (12 or 13 for "retest", 6 or 7 for "foo".) This suggests that you're feeding 16-bit strings into an 8-bit buffer. I don't know how you can be getting that past the compiler, though -- perhaps you've got a faulty or out-of-date definition for std::string and/or cout? **EDIT 2**: I remember where I've seen this before. A couple of years ago, I saw an issue where the DOS console window was corrupting the program's output. (I don't remember the exact details, but I think the problem was that the DOS console couldn't handle UTF-8 character sets.) If you're seeing this output in a DOS window (or, less likely, if it's being piped via `system()` to another program), then try re-directing it to a file, then open that file with Notepad. It just might work...
Strange C++ std::string behavior... How can I fix this?
[ "", "c++", "string", "" ]
I want to do something like this: ``` @Entity public class Bar { @Id @GeneratedValue long id; List<String> Foos } ``` and have the Foos persist in a table like this: ``` foo_bars ( bar_id int, foo varchar(64) ); ``` UPDATE: I know how to map other entities, but it's overkill in many cases. It looks like what I'm suggesting isn't possible without creating yet another entity or ending up with everything in some blob column.
This is in [Hibernate terms](http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e2770) a "collection of values" or "elements". There is a (Hibernate specific) annotation for it. JPA does not support this (yet). In short, annotate your collection like this: ``` @CollectionOfElements @JoinTable( table=@Table(name="..."), joinColumns = @JoinColumn(name="...") // References parent ) @Column(name="...value...", nullable=false) ``` This will create the necessary table with foreign keys and restrictions.
Here is how you would do this if you are using JPA2: ``` @Entity public class Bar { @Id @GeneratedValue long id; @ElementCollection @CollectionTable(name="foo_bars", joinColumns=@JoinColumn(name="bar_id")) @Column(name="foo") List<String> Foos; } ``` For a clearer example see section 2.2.5.3.3 in [the Hibernate Annotations Reference Guide](http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-association).
Map a list of strings with JPA/Hibernate annotations
[ "", "java", "hibernate", "jpa", "annotations", "" ]
I am having a bit of trouble building my project with Ant. I wanted to take a look at the Ant scripts that eclipse uses to build my project. How can I do this?
Select *Project » Properties » Builders* to see what runs when Eclipse builds your project.
I don't think eclipse uses ant scripts to build your project by default. However, eclipse can generate ant scripts for you. This can be done by right click project > export > General > Ant buildfiles. Make sure you uncheck the 'use eclipse compiler' if you want the build file to be usable from outside of eclipse.
How do I view Ant scripts that eclipse uses?
[ "", "java", "eclipse", "ant", "" ]
Using C# how can I test a file is a jpeg? Should I check for a .jpg extension? Thanks
Several options: You can check for the file extension: ``` static bool HasJpegExtension(string filename) { // add other possible extensions here return Path.GetExtension(filename).Equals(".jpg", StringComparison.InvariantCultureIgnoreCase) || Path.GetExtension(filename).Equals(".jpeg", StringComparison.InvariantCultureIgnoreCase); } ``` or check for the correct [magic number](https://web.archive.org/web/20100212180433/http://www.obrador.com/essentialjpeg/headerinfo.htm) in the header of the file: ``` static bool HasJpegHeader(string filename) { using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open, FileAccess.Read))) { UInt16 soi = br.ReadUInt16(); // Start of Image (SOI) marker (FFD8) UInt16 marker = br.ReadUInt16(); // JFIF marker (FFE0) or EXIF marker(FFE1) return soi == 0xd8ff && (marker & 0xe0ff) == 0xe0ff; } } ``` Another option would be to load the image and check for the correct type. However, this is less efficient (unless you are going to load the image anyway) but will probably give you the most reliable result (Be aware of the additional cost of loading and decompression as well as possible exception handling): ``` static bool IsJpegImage(string filename) { try { using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename)) { // Two image formats can be compared using the Equals method // See http://msdn.microsoft.com/en-us/library/system.drawing.imaging.imageformat.aspx // return img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg); } } catch (OutOfMemoryException) { // Image.FromFile throws an OutOfMemoryException // if the file does not have a valid image format or // GDI+ does not support the pixel format of the file. // return false; } } ```
OMG, So many of these code examples are wrong, wrong wrong. EXIF files have a marker of 0xff\**e1*\*, JFIF files have a marker of 0xff\**e0*\*. So all code that relies on 0xffe0 to detect a JPEG file will miss all EXIF files. Here's a version that will detect both, and can easily be altered to return only for JFIF or only for EXIF. (Useful when trying to recover your iPhone pictures, for example). ``` public static bool HasJpegHeader(string filename) { try { // 0000000: ffd8 ffe0 0010 4a46 4946 0001 0101 0048 ......JFIF.....H // 0000000: ffd8 ffe1 14f8 4578 6966 0000 4d4d 002a ......Exif..MM.* using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open, FileAccess.ReadWrite))) { UInt16 soi = br.ReadUInt16(); // Start of Image (SOI) marker (FFD8) UInt16 marker = br.ReadUInt16(); // JFIF marker (FFE0) EXIF marker (FFE1) UInt16 markerSize = br.ReadUInt16(); // size of marker data (incl. marker) UInt32 four = br.ReadUInt32(); // JFIF 0x4649464a or Exif 0x66697845 Boolean isJpeg = soi == 0xd8ff && (marker & 0xe0ff) == 0xe0ff; Boolean isExif = isJpeg && four == 0x66697845; Boolean isJfif = isJpeg && four == 0x4649464a; if (isJpeg) { if (isExif) Console.WriteLine("EXIF: {0}", filename); else if (isJfif) Console.WriteLine("JFIF: {0}", filename); else Console.WriteLine("JPEG: {0}", filename); } return isJpeg; return isJfif; return isExif; } } catch { return false; } } ```
C# How can I test a file is a jpeg?
[ "", "c#", "jpeg", "" ]
I would like to export the image in my JPanel to a vector graphics file so it can be edited and printed at a higher-than-screen resolution. Essentially I want its `paint()` function to be called with a destination Graphics that saves the drawing commands into a vector graphic file. What is a good, simple way to do this? What libraries are recommended? Which vector format would be best, and why?
Have a look at [The Java EPS Graphics2D package](http://www.jibble.org/epsgraphics/). > Many Java programs use Graphics2D to draw stuff on the screen, and while it is easy to save the output as a png or jpeg file, it is a little harder to export it as an EPS for including in a document or paper. > > This package makes the whole process extremely easy, because you can use the EpsGraphics2D object as if it's a Graphics2D object. The only difference is that all of the implemented methods create EPS output, which means the diagrams you draw can be resized without leading to any of the jagged edges you may see when resizing pixel-based images, such as JEPG and PNG files.
Apache [Batik](http://xmlgraphics.apache.org/batik/) will let you paint to a specialised implementation of a Graphics2D object and then export as an scalable vector graphics (.svg) file. You can then view/process/print it using an SVG-enabled browser (Firefox will handle it nativly, ISTR, IE and others can use plugins). See the [SVGGraphics2D](http://xmlgraphics.apache.org/batik/javadoc/org/apache/batik/svggen/SVGGraphics2D.html) object (process documented [here](http://xmlgraphics.apache.org/batik/using/svg-generator.html))
Export JPanel to vector graphics
[ "", "java", "swing", "graphics", "awt", "vector-graphics", "" ]
Is it possible to do following without the `i`? ``` for i in range(some_number): # do something ``` If you just want to do something N amount of times and don't need the iterator.
Off the top of my head, no. I think the best you could do is something like this: ``` def loop(f,n): for i in xrange(n): f() loop(lambda: <insert expression here>, 5) ``` But I think you can just live with the extra `i` variable. Here is the option to use the `_` variable, which in reality, is just another variable. ``` for _ in range(n): do_something() ``` Note that `_` is assigned the last result that returned in an interactive python session: ``` >>> 1+2 3 >>> _ 3 ``` For this reason, I would not use it in this manner. I am unaware of any idiom as mentioned by Ryan. It can mess up your interpreter. ``` >>> for _ in xrange(10): pass ... >>> _ 9 >>> 1+2 3 >>> _ 9 ``` And according to [Python grammar](https://docs.python.org/2/reference/lexical_analysis.html#identifiers), it is an acceptable variable name: ``` identifier ::= (letter|"_") (letter | digit | "_")* ```
You may be looking for ``` for _ in itertools.repeat(None, times): ... ``` this is THE fastest way to iterate `times` times in Python.
Is it possible to make a `for` loop without an iterator variable? (How can I make code loop a set number of times?)
[ "", "python", "loops", "for-loop", "range", "" ]
I basically want to produce the following: from int 67 to 1 minute 7 seconds from int 953 to 15 minutes 53 seconds from int 3869 to 1 hour 4 minutes 29 seconds pseudo code: ``` // original <span class="time">67</span> //output <span class="time">1 minute 7 seconds</span> // js $('.time').format_duration(); ```
Borrowing most of Guffa's answer, this should do the trick as a jQuery plugin: ``` jQuery.fn.time_from_seconds = function() { return this.each(function() { var t = parseInt($(this).text(), 10); $(this).data('original', t); var h = Math.floor(t / 3600); t %= 3600; var m = Math.floor(t / 60); var s = Math.floor(t % 60); $(this).text((h > 0 ? h + ' hour' + ((h > 1) ? 's ' : ' ') : '') + (m > 0 ? m + ' minute' + ((m > 1) ? 's ' : ' ') : '') + s + ' second' + ((s > 1) ? 's' : '')); }); }; ``` If you have HTML like this: ``` <span class='time'>67</span> <span class='time'>953</span> <span class='time'>3869</span> ``` And you call it like this: ``` $('.time').time_from_seconds(); ``` The HTML is turned to: ``` <span class="time">1 minute 7 seconds</span> <span class="time">15 minutes 53 seconds</span> <span class="time">1 hour 4 minutes 29 seconds</span> ``` Each element also has a [data attribute](http://docs.jquery.com/Data) of 'original' with the seconds it originally contained. My answer directly answers your question, but I'm going to take a shot in the dark: if you want to show how long ago something happened in human time (ie, "5 minutes ago") there is the [jQuery timeago plugin](http://timeago.yarp.com/) for this. I don't think it accepts seconds as the format, though. It has to be a [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601) date.
``` <html> <head> <script language="javascript" type="text/javascript" src="jquery.js"></script> <script> var tbl = [ [ 7*24*60*60, 'week' ], [ 24*60*60, 'day' ], [ 60*60, 'hour' ], [ 60, 'minute' ], [ 1, 'second' ] ]; function convert() { var t = parseInt($('#val').val()); var r = ''; for (var i = 0; i < tbl.length; i++) { var d = tbl[i]; if (d[0] < t) { var u = Math.floor(t / d[0]); t -= u * d[0]; r += u + ' ' + d[1] + (u == 1 ? ' ' : 's '); } } $('#result').html(r); } </script> </head> <body> <input id='val' type='text' size='10' /> <input type='button' value='convert' onclick='convert()' /> <div id='result' /> </body> </html> ```
Is there a good jQuery plugin or JS code for time durations?
[ "", "javascript", "jquery", "jquery-plugins", "time", "" ]
Say you have a Many-Many table between Artists and Fans. When it comes to designing the table, do you design the table like such: ``` ArtistFans ArtistFanID (PK) ArtistID (FK) UserID (FK) (ArtistID and UserID will then be contrained with a Unique Constraint to prevent duplicate data) ``` Or do you build use a compound PK for the two relevant fields: ``` ArtistFans ArtistID (PK) UserID (PK) (The need for the separate unique constraint is removed because of the compound PK) ``` --- Are there are any advantages (maybe indexing?) for using the former schema?
``` ArtistFans ArtistID (PK) UserID (PK) ``` The use of an auto incremental PK has no advantages here, even if the parent tables have them. I'd also create a "reverse PK" index automatically on `(UserID, ArtistID)` too: you will need it because you'll query the table by both columns. Autonumber/ID columns have their place. You'd choose them to improve certain things after the normalisation process based on the physical platform. But not for link tables: if your braindead ORM insists, then change ORMs... Edit, Oct 2012 It's important to note that you'd still need unique `(UserID, ArtistID)` and `(ArtistID, UserID)` indexes. Adding an auto increments just uses more space (in memory, not just on disk) that shouldn't be used
Assuming that you're already a devotee of the surrogate key (you're in good company), there's a case to be made for going all the way. A key point that is sometimes forgotten is that relationships themselves can have properties. Often it's not enough to state that two things are related; you might have to describe the nature of that relationship. In other words, there's nothing special about a relationship table that says it can only have two columns. If there's nothing special about these tables, why not treat it like every other table and use a surrogate key? If you do end up having to add properties to the table, you'll thank your lucky presentation layers that you don't have to pass around a compound key just to modify those properties. I wouldn't even call this a rule of thumb, more of a something-to-consider. In my experience, some slim majority of relationships end up carrying around additional data, essentially becoming entities in themselves, worthy of a surrogate key. The rub is that adding these keys after the fact can be a pain. Whether the cost of the additional column and index is worth the value of preempting this headache, that really depends on the project. As for me, once bitten, twice shy – I go for the surrogate key out of the gate.
SQL: Do you need an auto-incremental primary key for Many-Many tables?
[ "", "sql", "database-design", "" ]
I'm basically looking for a python version of [Combination of `List<List<int>>`](https://stackoverflow.com/questions/545703/combination-of-listlistint) Given a list of lists, I need a new list that gives all the possible combinations of items between the lists. ``` [[1,2,3],[4,5,6],[7,8,9,10]] -> [[1,4,7],[1,4,8],...,[3,6,10]] ``` The number of lists is unknown, so I need something that works for all cases. Bonus points for elegance!
you need [`itertools.product`](https://docs.python.org/2/library/itertools.html#itertools.product): ``` >>> import itertools >>> a = [[1,2,3],[4,5,6],[7,8,9,10]] >>> list(itertools.product(*a)) [(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 5, 10), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 6, 10), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 4, 10), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 5, 10), (3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 6, 10)] ```
Simply use `itertools.product`: ``` listOLists = [[1,2,3],[4,5,6],[7,8,9,10]] for l in itertools.product(*listOLists): print(l) ```
All combinations of a list of lists
[ "", "python", "cartesian-product", "" ]
I've got an IronPython script that executes a bunch of SQL statements against a SQL Server database. the statements are large strings that actually contain multiple statements, separated by the "GO" keyword. That works when they're run from sql management studio and some other tools, but not in ADO. So I split up the strings using the 2.5 "re" module like so: ``` splitter = re.compile(r'\bGO\b', re.IGNORECASE) for script in splitter.split(scriptBlob): if(script): [... execute the query ...] ``` This breaks in the rare case that there's the word "go" in a comment or a string. How in the heck would I work around that? i.e. correctly parse this string into two scripts: ``` -- this is a great database script! go team go! INSERT INTO myTable(stringColumn) VALUES ('go away!') /* here are some comments that go with this script. */ GO INSERT INTO myTable(stringColumn) VALUES ('this is the next script') ``` --- **EDIT:** I searched more and found this SQL documentation: <http://msdn.microsoft.com/en-us/library/ms188037(SQL.90).aspx> As it turns out, GO must be on its own line as some answers suggested. However it can be followed by a "count" integer which will actually execute the statement batch that many times (has anybody actually used that before??) and it can be followed by a single-line comments on the same line (but not a multi-line, I tested this.) So the magic regex would look something like: ``` "(?m)^\s*GO\s*\d*\s*$" ``` Except this doesn't account for: * a possible single-line comment (`"--"` followed by any character except a line break) at the end. * the whole line being inside a larger multi-line comment. I'm not concerned about capturing the "count" argument and using it. Now that I have some technical documentation i'm tantalizingly close to writing this "to spec" and never having to worry about it again.
Is "GO" always on a line by itself? You could just split on "^GO$".
since you can have comments inside comments, nested comments, comments inside queries, etc, there is no sane way to do it with regexes. Just immagine the following script: ``` INSERT INTO table (name) VALUES ( -- GO NOW GO 'GO to GO /* GO */ GO' + /* some comment 'go go go' -- */ 'GO GO' /* GO */ ) ``` That without mentioning: ``` INSERT INTO table (go) values ('xxx') GO ``` The only way would be to build a stateful parser instead. One that reads a char at a time, and has a flag that will be set when it is inside a comment/quote-delimited string/etc and reset when it ends, so the code can ignore "GO" instances when inside those.
regex for parsing SQL statements
[ "", "python", "regex", "" ]
I'm currently stuck. I have a webform with a button that registers or saves a record. What i'd like to is have it display a javascript alert and then redirect to a page. Here is the code i am using ``` protected void Save(..) { // Do save stuff DisplayAlert("The changes were saved Successfully"); Response.Redirect("Default.aspx"); } ``` This code just redirects without giving the prompt Saved Successfully. Here is my DisplayAlert Code ``` protected virtual void DisplayAlert(string message) { ClientScript.RegisterStartupScript( this.GetType(), Guid.NewGuid().ToString(), string.Format("alert('{0}');", message.Replace("'", @"\'").Replace("\n", "\\n").Replace("\r", "\\r")), true ); } ``` Can anyone help me find a solution to this? Thanks
You can't do a Response.Redirect because your javascript alert will never get displayed. Better to have your javascript code actually do a `windows.location.href='default.aspx'` to do the redirection after the alert is displayed. Something like this: ``` protected virtual void DisplayAlert(string message) { ClientScript.RegisterStartupScript( this.GetType(), Guid.NewGuid().ToString(), string.Format("alert('{0}');window.location.href = 'default.aspx'", message.Replace("'", @"\'").Replace("\n", "\\n").Replace("\r", "\\r")), true); } ```
The DisplayAlert method adds the client script to the currently executing page request. When you call Response.Redirect, ASP.NET issues a HTTP 301 redirect to the browser, therefore starting a new page request where the registered client script no longer exists. Since your code is executing on the server-side, there is no way to display the alert client-side and perform the redirect. Also, displaying a JavaScript alert box can be confusing to a user's mental workflow, an inline message would be much more preferable. Perhaps you could add the message to the Session and display this on the Default.aspx page request. ``` protected void Save(..) { // Do save stuff Session["StatusMessage"] = "The changes were saved Successfully"; Response.Redirect("Default.aspx"); } ``` Then in Default.aspx.cs code behind (or a common base page class so this can happen on any page, or even the master page): ``` protected void Page_Load(object sender, EventArgs e) { if(!string.IsNullOrEmpty((string)Session["StatusMessage"])) { string message = (string)Session["StatusMessage"]; // Clear the session variable Session["StatusMessage"] = null; // Enable some control to display the message (control is likely on the master page) Label messageLabel = (Label)FindControl("MessageLabel"); messageLabel.Visible = true; messageLabel.Text = message; } } ``` The code isn't tested but should point you in the right direction
Asp.net Webform Display Alert and redirect
[ "", "asp.net", "javascript", "redirect", "alert", "" ]
I'm editing some Python code with rather long functions and decided it would be useful to quickly get the function name without scrolling up. I put this bit of code together to do it. Is there something built in to emacs in general, or the standard python mode in particular, which I can use instead? ``` (defun python-show-function-name() "Message the name of the function the point is in" (interactive) (save-excursion (beginning-of-defun) (message (format "%s" (thing-at-point 'line))))) ```
You may find decent results with [which-function-mode](http://www.gnu.org/software/emacs/manual/html_node/emacs/Which-Function.html): > Which Function mode is a minor mode > that displays the current function > name in the mode line, updating it as > you move around in a buffer. > > To either enable or disable Which > Function mode, use the command M-x > which-function-mode. This command is > global; it applies to all buffers, > both existing ones and those yet to be > created. However, it takes effect only > in certain major modes, those listed > in the value of which-func-modes. If > the value is t, then Which Function > mode applies to all major modes that > know how to support it—in other words, > all the major modes that support > Imenu. Although I see it getting a little confused in one Python file that I have here...
Did you try `py-beginning-of-def-or-class`? ``` (defun python-show-function-name() "Message the name of the function the point is in" (interactive) (save-excursion (py-beginning-of-def-or-class) (message (format "%s" (thing-at-point 'line))))) ``` I find it gives me better results than your `beginning-of-defun`, but if that's not the problem you're having, then maybe I'm just seeing another symptom of the cause of the wonkiness in [my other answer](https://stackoverflow.com/questions/782357/emacs-function-to-message-the-python-function-im-in/782413#782413).
Emacs function to message the python function I'm in
[ "", "python", "emacs", "elisp", "" ]
Hi I'm stuck doing this, not sure how to go about it. If I have two binary trees, how would I check if the have the same shape? Data in the nodes doesn't matter, just if the tree structures are equal. Any ideas on how to solve this problem?
You can easily do that with recursion. This following code works because two non-empty trees have the same shape if and only if their respective subtrees have the same shape. ``` boolean equalTrees(Node lhs, Node rhs) { // Empty trees are equal if (lhs == null && rhs == null) return true; // Empty tree is not equal to a non-empty one if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) return false; // otherwise check recursively return equalTrees(lhs.left(), rhs.left()) && equalTrees(lhs.right(), rhs.right()) } ``` To check two trees, pass their root nodes to the function above. ``` equalTrees(tree1.root(), tree2.root()) ```
Two Breadth First Searches in parallel would be one way. <http://en.wikipedia.org/wiki/Breadth-first_search> With BFS, you can examine all nodes a particular level of the tree at the same time. That way, if you don't distinguish between right and left children (i.e. if your tree is considered the same if a node's counterpart has one child, regardless of "right" or "left" child) you can handle that at that time.
Binary Trees question. Checking for similar shape
[ "", "java", "algorithm", "tree", "" ]
I have a basic question regarding the const pointers. I am not allowed to call any non-const member functions using a const pointer. However, I am allowed to do this on a const pointer: ``` delete p; ``` This will call the destructor of the class which in essence is a non-const 'method'. Why is this allowed? Is it just to support this: ``` delete this; ``` Or is there some other reason?
It's to support: ``` // dynamically create object that cannot be changed const Foo * f = new Foo; // use const member functions here // delete it delete f; ``` But note that the problem is not limited to dynamically created objects: ``` { const Foo f; // use it } // destructor called here ``` If destructors could not be called on const objects we could not use const objects at all.
Put it this way - if it *weren't* allowed there would be no way to delete const objects without using const\_cast. Semantically, const is an indication that an object should be immutable. That does not imply, however, that the object should not be deleted.
Deleting a pointer to const (T const*)
[ "", "c++", "constants", "delete-operator", "" ]
I would like to implement a simple in-memory LRU cache system and I was thinking about a solution based on an IDictionary implementation which could handle an hashed LRU mechanism. Coming from java, I have experiences with `LinkedHashMap`, which works fine for what I need: I can't find anywhere a similar solution for .NET. Has anyone developed it or has anyone had experiences like this?
There is nothing in the base class libraries that does this. On the free side, maybe something like C5's [HashedLinkedList](http://www.itu.dk/research/c5/Release1.1/c5doc/types/C5.HashedLinkedList_1.htm) would work. If you're willing to pay, maybe check out [this C# toolkit.](http://recursionsw.com/Products/csharp.html) It contains an implementation.
This a very simple and fast implementation we developed for a web site we own. We tried to improve the code as much as possible, while keeping it thread safe. I think the code is very simple and clear, but if you need some explanation or a guide related to how to use it, don't hesitate to ask. ``` namespace LRUCache { public class LRUCache<K,V> { private int capacity; private Dictionary<K, LinkedListNode<LRUCacheItem<K, V>>> cacheMap = new Dictionary<K, LinkedListNode<LRUCacheItem<K, V>>>(); private LinkedList<LRUCacheItem<K, V>> lruList = new LinkedList<LRUCacheItem<K, V>>(); public LRUCache(int capacity) { this.capacity = capacity; } [MethodImpl(MethodImplOptions.Synchronized)] public V get(K key) { LinkedListNode<LRUCacheItem<K, V>> node; if (cacheMap.TryGetValue(key, out node)) { V value = node.Value.value; lruList.Remove(node); lruList.AddLast(node); return value; } return default(V); } [MethodImpl(MethodImplOptions.Synchronized)] public void add(K key, V val) { if (cacheMap.TryGetValue(key, out var existingNode)) { lruList.Remove(existingNode); } else if (cacheMap.Count >= capacity) { RemoveFirst(); } LRUCacheItem<K, V> cacheItem = new LRUCacheItem<K, V>(key, val); LinkedListNode<LRUCacheItem<K, V>> node = new LinkedListNode<LRUCacheItem<K, V>>(cacheItem); lruList.AddLast(node); // cacheMap.Add(key, node); - here's bug if try to add already existing value cacheMap[key] = node; } private void RemoveFirst() { // Remove from LRUPriority LinkedListNode<LRUCacheItem<K,V>> node = lruList.First; lruList.RemoveFirst(); // Remove from cache cacheMap.Remove(node.Value.key); } } class LRUCacheItem<K,V> { public LRUCacheItem(K k, V v) { key = k; value = v; } public K key; public V value; } } ```
Is it there any LRU implementation of IDictionary?
[ "", "c#", "dictionary", "caching", "lru", "" ]
I'm writing an agglomerative clustering algorithm in java and having trouble with a remove operation. It seems to always fail when the number of clusters reaches half the initial number. In the sample code below, `clusters` is a `Collection<Collection<Integer>>`. ``` while(clusters.size() > K){ // determine smallest distance between clusters Collection<Integer> minclust1 = null; Collection<Integer> minclust2 = null; double mindist = Double.POSITIVE_INFINITY; for(Collection<Integer> cluster1 : clusters){ for(Collection<Integer> cluster2 : clusters){ if( cluster1 != cluster2 && getDistance(cluster1, cluster2) < mindist){ minclust1 = cluster1; minclust2 = cluster2; mindist = getDistance(cluster1, cluster2); } } } // merge the two clusters minclust1.addAll(minclust2); clusters.remove(minclust2); } ``` After a few runs through the loop, `clusters.remove(minclust2)` eventually returns false, but I don't understand why. I tested this code by first creating 10 clusters, each with one integer from 1 to 10. Distances are random numbers between 0 and 1. Here's the output after adding a few println statements. After the number of clusters, I print out the actual clusters, the merge operation, and the result of clusters.remove(minclust2). ``` Clustering: 10 clusters [[3], [1], [10], [5], [9], [7], [2], [4], [6], [8]] [5] <- [6] true Clustering: 9 clusters [[3], [1], [10], [5, 6], [9], [7], [2], [4], [8]] [7] <- [8] true Clustering: 8 clusters [[3], [1], [10], [5, 6], [9], [7, 8], [2], [4]] [10] <- [9] true Clustering: 7 clusters [[3], [1], [10, 9], [5, 6], [7, 8], [2], [4]] [5, 6] <- [4] true Clustering: 6 clusters [[3], [1], [10, 9], [5, 6, 4], [7, 8], [2]] [3] <- [2] true Clustering: 5 clusters [[3, 2], [1], [10, 9], [5, 6, 4], [7, 8]] [10, 9] <- [5, 6, 4] false Clustering: 5 clusters [[3, 2], [1], [10, 9, 5, 6, 4], [5, 6, 4], [7, 8]] [10, 9, 5, 6, 4] <- [5, 6, 4] false Clustering: 5 clusters [[3, 2], [1], [10, 9, 5, 6, 4, 5, 6, 4], [5, 6, 4], [7, 8]] [10, 9, 5, 6, 4, 5, 6, 4] <- [5, 6, 4] false ``` The the [10, 9, 5, 6, 4, 5, 6, 4, ...] set just grows infinitely from there. **Edit: to clarify, I'm using a `HashSet<Integer>` for each cluster in clusters (a `HashSet<HashSet<Integer>>)`.**
Ah. When you alter a value that is already in a `Set` (or a `Map` key), then it is not necessarily in the right position and hash codes will be cached. You need to remove it, alter it and then re-insert it.
In the test shown, the `remove` fails the first time you try to remove a Collection containing more than one Integer. Is this always the case? What is the concrete type of the Collection used?
Remove from a HashSet failing after iterating over it
[ "", "java", "collections", "hash", "iterator", "hashset", "" ]
Right now I'm trying to serve CSS and JS files from a server that won't let me enable `mod_gzip` or `mod_deflate`. So I wrote a small PHP script to compress with GZIP and return to the user. Example Code: ``` $filename = "style.css"; if (!file_exists($filename) || !($info = stat($filename))) { header("HTTP/1.1 404 Not Found"); die(); } header("Date: ".gmdate("D, j M Y H:i:s e", time())); header("Cache-Control: max-age=2592000"); header("Last-Modified: ".gmdate("D, j M Y H:i:s e", $info['mtime'])); header("Etag: ".sprintf("\"%x-%x-%x\"", $info['ino'], $info['size'], $info['mtime'])); header("Accept-Ranges: bytes"); header("Cache-Control: Expires ".gmdate("D, j M Y H:i:s e", $info['mtime']+2592000)); header("Content-Type: text/html"); ob_start("ob_gzhandler"); echo file_get_contents($filename); ob_end_flush(); ``` I'm having two problems right now. The first is, I'm having trouble determining the resulting size of the compressed file to inform the browser of the content-length. Normally, I would include this line: ``` header("Content-Length: ".$info["size"]); ``` But, if I do, the browser hangs while trying to wait for more data. Is there a way to calculate the total size? Or should I ignore this header directive. The other issue is, whenever I view this PHP file in Firefox, it tries to have me download the result. In Chrome, it just displays it like I would expect. Any suggestions? **Edit:** Thanks to SoapBox, I replaced the end of the code with this: ``` header("Content-Encoding: gzip"); $compressed = gzencode(file_get_contents($filename), 5); header("Content-Length: ".strlen($compressed)); die($compressed); ``` This works great for the content-length! But I'm still getting Firefox to download the file instead of display it. :( **Edit Again:** Here is the modified end-of-code code, courtesy of Cletus. ``` // Start buffered output ob_start(); // Check for gzip capability if (stripos($_SERVER['HTTP_ACCEPT_ENCODING'], "gzip") !== false) { ob_start("ob_gzhandler"); echo file_get_contents($filename); ob_end_flush(); } else echo file_get_contents($filename); // Write the content length header('Content-Length: '.ob_get_length()); ob_end_flush(); ``` I'm going to start a new question to figure out why Firefox keeps trying to download the file.
The problem here is that to know the content length you need to know whether or not the client supports gzip encoding and you've delegated that decision by using ob\_gzhandler. From [HTTP Headers](http://www.edginet.org/techie/website/http.html): > ``` > ob_start(); > ob_start('ob_gzhandler'); > > ... output the page content... > > ob_end_flush(); // The ob_gzhandler one > > header('Content-Length: '.ob_get_length()); > > ob_end_flush(); // The main one > ``` Complete version: ``` $filename = "style.css"; if (!file_exists($filename) || !($info = stat($filename))) { header("HTTP/1.1 404 Not Found"); die(); } header("Date: ".gmdate("D, j M Y H:i:s e", time())); header("Cache-Control: max-age=2592000"); header("Last-Modified: ".gmdate("D, j M Y H:i:s e", $info['mtime'])); header("ETag: ".sprintf("\"%x-%x-%x\"", $info['ino'], $info['size'], $info['mtime'])); header("Accept-Ranges: bytes"); header("Expires: ".gmdate("D, j M Y H:i:s e", $info['mtime']+2592000)); header("Content-Type: text/css"); // note: this was text/html for some reason? ob_start(); ob_start("ob_gzhandler"); echo file_get_contents($filename); ob_end_flush(); header('Content-Length: '.ob_get_length()); ob_end_flush(); ``` This is **much** better than taking on the gzip encoding issue yourself.
You need to first do the entire gzip and measure the result (either holding the contents in memory, or writing them to disk as you compress and then stat'ing the gzipped file), then write the Content-Length header and then send the file contents. Or use [chunked transfer encoding](http://en.wikipedia.org/wiki/Chunked_transfer_encoding).
How to determine the Content-Length of a gzipped file?
[ "", "php", "http-headers", "gzip", "header", "" ]
I have a thread that is supposed to listen for acknowledgements of messages and process them, but it seems that the thread is never reciving the acknowledgements. Here is the relevant code in the thread: ``` private class TcpReader extends Thread { BufferedReader reader; boolean running = false; public TcpReader(BufferedReader reader) { this.reader = reader; } public void run() { running = true; while (running) { try { String line = reader.readLine(); logger.debug("TCP READER RECIEVED MESSAGE ["+ line + "]"); // Do stuff } catch (Exception e) { } } } } ``` The thread is created in the following code which happens in a different class: ``` sock = new Socket(hostName, port); out = new PrintWriter(sock.getOutputStream(), true); isConnected = true; BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream())); tcpReader = new TcpReader(reader); tcpReader.start(); ``` The Variables are instantiated in the as member variables: ``` Socket sock; PrintWriter out; BufferedReader in; ``` The flow of execution is my server class recives a message and then replies with an ACK that the client is supposed to pick up on. However since the client is not to wait for the ack to continue A separate thread waits for all responses. The readline code never reads anything. The messages are being sent from my server and they have "\r\n" as their last two chars.
Is the end-of-line character being transmitted from the server, i.e. is it flushing the output stream at the other end? You could use `telnet` or a simple packet sniffer to check what's being sent. On a side note, `running` probably ought to be marked as volatile.
If an `Exception` is raised by `readLine`, nothing is logged.
Why is this buffered reader not receiving any data?
[ "", "java", "sockets", "" ]
What are some cross platform and high performance image libraries for image processing (resizing and finding the color/hue histograms). No gui needed. This is for C/C++. So far I have looked in to * OpenCV * GIL as part of Boost * DevIL * CImg My questions * How's the performance of the ones I have listed above * What are some other libraries Your input much appreciated.
[OpenCV](http://opencv.org/) has quite good performance. It should be sufficient for most cases. To improve performance, you can also use OpenCV together with [Intel IPP](http://software.intel.com/en-us/intel-ipp/), which is however a non-free commercial product. If OpenCV detects that IPP is installed it will use it where possible. As a third option you can use IPP directly. IPP was designed with high performance (on Intel architectures) as a goal. It is optimized to use the intel SIMD instructions.
[imagemagick](http://www.imagemagick.org/script/index.php) is quite popular.
Fast Cross-Platform C/C++ Image Processing Libraries
[ "", "c++", "c", "image-processing", "cross-platform", "performance", "" ]
The host I'm considering for hosting a Django site has mod\_python installed, but does not have Django. Django's INSTALL file indicates that I can simply copy the django directory to Python's site-packages directory to install Django, so I suspect that it might be possible to configure Python / mod\_python to look for it elsewhere (namely my user space) by modifying sys.path, but I don't know how to change it from .htaccess or mod\_python. **How do I modify `sys.path` from `.htaccess` to allow mod\_python to see Django?** P.S. I can only access the site via FTP (i.e. no shell access). I realize that it sounds like I should just switch hosts, but there are compelling reasons for me to make this work so I'm at least going to try.
According to [ticket #2255](http://code.djangoproject.com/ticket/2255) for Django, you need admin access to httpd.conf in order to use Django with mod\_python, and this is not going to change, so you may be dead in the water. To answer the basic question of how to modify `sys.path` from `.htaccess`, you can use the [PythonPath](http://www.modpython.org/live/current/doc-html/dir-other-pp.html) directive in `.htaccess`.
You're using mod\_python wrong. It was never intended to serve python web applications. You should be using WSGI for this... or at least FastCGI.
How do I modify sys.path from .htaccess to allow mod_python to see Django?
[ "", "python", "django", "apache", ".htaccess", "mod-python", "" ]
Here is my query: ``` select word_id, count(sentence_id) from sentence_word group by word_id having count(sentence_id) > 100; ``` The table sentenceword contains 3 fields, wordid, sentenceid and a primary key id. It has 350k+ rows. This query takes a whopping 85 seconds and I'm wondering (hoping, praying?) there is a faster way to find all the wordids that have more than 100 sentenceids. I've tried taking out the select count part, and just doing 'having count(1)' but neither speeds it up. I'd appreciate any help you can lend. Thanks!
> having count(sentence\_id) > 100; There's a problem with this... Either the table has duplicate word/sentence pairs, or it doesn't. If it does have duplicate word/sentence pairs, you should be using this code to get the correct answer: ``` HAVING COUNT(DISTINCT Sentence_ID) > 100 ``` --- If the table does not have duplicate word/sentence pairs... then you shouldn't count sentence\_ids, you should just count rows. ``` HAVING COUNT(*) > 100 ``` In which case, you can create an index on ***word\_id only***, for optimum performance.
If you don't already have one, create a composite index on sentence\_id, word\_id.
is there something faster than "having count" for large tables?
[ "", "sql", "count", "query-optimization", "having", "" ]
I have a string serialization utility that takes a variable of (almost) any type and converts it into a string. Thus, for example, according to my convention, an integer value of 123 would be serialized as "i:3:123" (i=integer; 3=length of string; 123=value). The utility handles all primitive type, as well as some non-generic collections, like ArrayLists and Hashtables. The interface is of the form `public static string StringSerialize(object o) {}` and internally I detect what type the object is and serialize it accordingly. Now I want to upgrade my utility to handle generic collections. The funny thing is, I can't find an appropriate function to detect that the object is a generic collection, and what types it contains - both of which pieces of information I need in order to serialize it correctly. To date I've been using coding of the form `if (o is int) {// do something}` but that doesn't seem to work with generics. What do you recommend? --- EDIT: Thanks to [Lucero](https://stackoverflow.com/questions/755200/how-do-i-detect-that-an-object-is-a-generic-collection-and-what-types-it-contain/755217#755217), I've gotten closer to the answer, but I'm stuck at this little syntactical conundrum here: ``` if (t.IsGenericType) { if (typeof(List<>) == t.GetGenericTypeDefinition()) { Type lt = t.GetGenericArguments()[0]; List<lt> x = (List<lt>)o; stringifyList(x); } } ``` This code doesn't compile, because "`lt`" is not allowed as the `<T>` argument of a `List<>` object. Why not? And what is the correct syntax?
Re your conundrum; I'm assuming `stringifyList` is a generic method? You would need to invoke it with reflection: ``` MethodInfo method = typeof(SomeType).GetMethod("stringifyList") .MakeGenericMethod(lt).Invoke({target}, new object[] {o}); ``` where `{target}` is `null` for a static method, or `this` for an instance method on the current instance. Further - I wouldn't assume that all collections are a: based on `List<T>`, b: generic types. The important thing is: **do they implement `IList<T>` for some `T`**? Here's a complete example: ``` using System; using System.Collections.Generic; static class Program { static Type GetListType(Type type) { foreach (Type intType in type.GetInterfaces()) { if (intType.IsGenericType && intType.GetGenericTypeDefinition() == typeof(IList<>)) { return intType.GetGenericArguments()[0]; } } return null; } static void Main() { object o = new List<int> { 1, 2, 3, 4, 5 }; Type t = o.GetType(); Type lt = GetListType(t); if (lt != null) { typeof(Program).GetMethod("StringifyList") .MakeGenericMethod(lt).Invoke(null, new object[] { o }); } } public static void StringifyList<T>(IList<T> list) { Console.WriteLine("Working with " + typeof(T).Name); } } ```
Use the Type to gather the required information. For generic objects, call GetType() to get their type and then check `IsGenericType` to find out if it is generic at all. If it is, you can get the generic type definition, which can be compared for instance like this: `typeof(List<>)==yourType.GetGenericTypeDefinition()`. To find out what the generic types are, use the method `GetGenericArguments`, which will return an array of the types used. To compare types, you can do the following: `if (typeof(int).IsAssignableFrom(yourGenericTypeArgument))`. --- EDIT to answer followup: Just make your `stringifyList` method accept an `IEnumerable` (not generic) as parameter and maybe also the known generic type argument, and you'll be fine; you can then use `foreach` to go over all items and handle them depending on the type argument if necessary.
How do I detect that an object is a generic collection, and what types it contains?
[ "", "c#", "generics", "typechecking", "" ]
Would be gratefull for some advice on the following - Is it possible to validate email and postcode fields through some kind of check constraint in the sql in oracle ? or this kind of thing as i suspect pl/sql with regular expressions ? Thanks
If you're only concerned with the US, there are several sources of zip codes that you can obtain in flat-file format and import into a table, and then apply a foreign key constraint in your addresses to that table. Email addresses can be matched against a regular expression (needs 10g or higher) to validate the format, but checking to see if they are actual addresses is a much more difficult task.
Here's the regexp syntax for an email address, including quotes ``` '[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+\.[a-zA-Z]{2,4}' ``` So you can use regexp\_like() in a where clause or regexp\_substr() to check whether your field contains a valid email address. Here's an example-you'll see that the regexp\_substr() returns NULL on the address missing the .domain, which fails the substring validation. From there you can build a check constraint around it, or enforce it using a trigger(yuck), etc. ``` SQL> desc email Name Null? Type ----------------------------------------- -------- ---------------------------- EMAIL_ID NUMBER EMAIL_ADDRESS VARCHAR2(128) SQL> select * from email; EMAIL_ID EMAIL_ADDRESS ---------- ---------------------------------------- 1 NEIL@GMAIL.COM 2 JOE@UTAH.GOV 3 lower_name@lower.org 4 bad_address@missing_domaindotorg SQL> @qry2 SQL> column email_address format a40 SQL> column substr_result format a30 SQL> SELECT email_address 2 , regexp_substr(email_address,'[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+\.[a-zA-Z]{2,4}') substr_result 3 FROM email 4 / EMAIL_ADDRESS SUBSTR_RESULT ---------------------------------------- ------------------------------ NEIL@GMAIL.COM NEIL@GMAIL.COM JOE@UTAH.GOV JOE@UTAH.GOV lower_name@lower.org lower_name@lower.org bad_address@missing_domaindotorg ``` Using the same data, here is a query which limits only valid email addresses, using REGEXP\_LIKE ``` SQL> column email_address format a40 SQL> column substr_result format a30 SQL> SELECT email_address 2 FROM email 3 WHERE REGEXP_LIKE (email_address, '[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+\.[a-zA-Z]{2,4}'); EMAIL_ADDRESS ---------------------------------------- NEIL@GMAIL.COM JOE@UTAH.GOV lower_name@lower.org ``` Search the contents page of the [SQL Reference](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/toc.htm) for regexp to see the regular expression support.
validation on email / postcode fields in sql/oracle
[ "", "sql", "oracle", "plsql", "constraints", "" ]
I want to run a simulation that uses as parameter a value generated from a triangular probability distribution with lower limit A, mode B and and upper limit C. How can I generate this value in Python? Is there something as simple as expovariate(lambda) (from random) for this distribution or do I have to code this thing?
If you download the NumPy package, it has a function numpy.random.triangular(left, mode, right[, size]) that does exactly what you are looking for.
Since, I was checking random's documentation from Python 2.4 I missed this: ***random.triangular(low, high, mode)***¶ Return a random floating point number N such that low <= N <= high and with the specified mode between those bounds. The low and high bounds default to zero and one. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution. **New in version 2.6**.
Python, SimPy: How to generate a value from a triangular probability distribution?
[ "", "python", "distribution", "probability", "simpy", "" ]
Let's say I have one class "User", and it "has" a property of type "Profile". How can I configure my mappings to generate the schema and create both tables in the database?
``` <many-to-one/> ```
As an aside, if you are not a great fan of scripting up hibernate mappings (which I'm not) then you have a couple of other options. [Castle ActiveRecord](http://www.castleproject.org/activerecord/index.html) is one alternative - it's a layer on top of NHibernate which (among other things) lets you declare your relationships using attributes on your classes and properties. And [Fluent NHibernate](http://wiki.fluentnhibernate.org/show/GettingStarted%3A+Introduction) is another - it lets you programmatically setup your classes and relationships. Both are a great improvement over writing your mapping xml by hand!
How can I relate 2 classes via NHibernate?
[ "", "c#", "nhibernate", "nhibernate-mapping", "" ]
I am looking here for some hints and tips on how to manage multiple versions of a projet. Currently I have a development version of the application which includes some improvements and new functionnalities. In meanwhile I have to do some bug resolving. It is easy to fix the bugs on files that have not been touched by new functionnalitites but as soon as I touch the page that have the new func. I need to comment several lines of code each time. I feel it is not the best way to play around. There must be a method good enought to solve this issue. On another side of the problem is the deployment. It is quite often that I must wait several weeks before uploading a new functionnality on the website. In meanwhile I tend to forget sometimes each files that have been modified (or commented for bugs) and it can create errors. I have heard of capistrano for ruby fans, could that help me ? I am mostly a PHP/asp.net developper.
You are experiencing the classical case of "**incompatible** development effort": you cannot both fix a bug and develop on the same file on the same time. This is a classical case for branching, which would allow for a same file to: * freeze its state to the one initially deployed (stating point for the branch) * fix the bug in a bugfix branch * retrofit some of those bugs into the current development branch * develop new features in the development branch. If you are not comfortable with the immediate setup of a VCS (Version Control System), you could at least duplicate the tree of files representing your server into 2 directories (one `1.0` and one '`DEV`'), effectively doing some "manual" revision control. Then a tool like [WinMerge](https://stackoverflow.com/questions/413649/how-to-diff-merge-changes-to-a-deployment-project-file/417962#417962) would help you to track the difference and do some merging But a true VCS would be more efficient, and can be used as a stable source for deployment, as illustrated by this [Best version-control for a one-man web-app](https://stackoverflow.com/questions/330848/best-version-control-for-a-one-man-web-app/330883#330883) question (with subversion). That version-controlled source can also be used by a deployment system like [capistrano](https://stackoverflow.com/questions/tagged/capistrano).
Most version control systems have the ability to "branch" your software, so that you can have multiple versions of the same code-base going at the same time. For example, your "1.0" branch might be the current production version. For new development, you might create a "1.1" branch, which starts off as a copy of 1.0. All your new features should go in 1.1, and any production bug fixes should go in 1.0 (and eventually 1.1 too). There are usually tools available to merge changes between branches (e.g. merge bug fixes from 1.0 to 1.1). Here is a good description of subversion branching. <http://svnbook.red-bean.com/en/1.1/ch04.html> Check your current version control system for how it handles branching.
project management / multiple versions
[ "", "php", "version-control", "deployment", "project-management", "versioning", "" ]
Is there a way that I can configure custom [node types](http://jackrabbit.apache.org/node-type-notation.html) for [Apache Jackrabbit](http://jackrabbit.apache.org) to be registered when a new repository is instantiated? I am automating my build using [Apache Maven](http://maven.apache.org) and have some unit tests to run with [JUnit](http://junit.org) and integration tests to run with [Jetty](http://www.mortbay.org/jetty) and want to be able to easily set-up and tear-down a test repository.
If you are able to upgrade to the newly-released Jackrabbit 2.0.0, you can programmatically create and register nodetypes. The main hook is the JSR-283 [NodeTypeManager](http://www.day.com/maven/javax.jcr/javadocs/jcr-2.0/javax/jcr/nodetype/NodeTypeManager.html) which doubles as a factory for new NodeTypes, and a place for them to be registered. Just register them in the setup method of your JUnit tests, and you should be good to go.
I suggest that you define your nodetypes using a [CND file](http://jackrabbit.apache.org/node-type-notation.html) and configure your JUnit test cases to register them for you, as in this [example](http://jackrabbit.apache.org/node-types.html#NodeTypes-RegisteringNodeTypes). I would say the most appropriate way to do so is to define an abstract test case which performs this configuration. Also notice that the node types are associated to a workspace, and not to the whole repository.
How do I configure custom node definitions in Apache Jackrabbit?
[ "", "java", "jackrabbit", "jcr", "jsr170", "" ]
for me I will answer this question based on my experience. **so if I'm gonna start new project I will use the following technologies:** 1. [AndroMDA](http://www.andromda.org/) as [MDA](http://en.wikipedia.org/wiki/Model-driven_architecture) framework. 2. Spring (DI, Interceptors, Quartz, ACEGI, ... etc). 3. Hibernate. 4. JSF. **off course you might need to play with some helper frameworks/libraries such as:** 1. Velocity. 2. CAS; if you need SSO. 3. JXLs; if you need small and easy library for generating Excel files using XLS templates. 4. Drools; which is Artificial Intelligence a Rule Engine that uses the Rule Based approached to implement an Expert System and is more correctly classified as a Production Rule System. **in terms of testing I will consider the following frameworks:** 1. TestNG; you may want to use JUnit in the part of Unit Testing but TestNG is more than a unite testing framework; 2. WATIR or SELENIUM as web testing; Can anybody else suggest other options?
Here are just a few answers to your question that can be found on StackOverflow. * [Best Java framework?](https://stackoverflow.com/questions/257712/) * [What is the most commonly used Java web framework?](https://stackoverflow.com/questions/742223/) * [Best java mvc framework implementation for web apps](https://stackoverflow.com/questions/309254/) * [What are the best MVC web frameworks on the market?](https://stackoverflow.com/questions/24450/) * [What are the best Java social networking frameworks?](https://stackoverflow.com/questions/283922/) * [Best server-side framework for heavy AJAX Java application](https://stackoverflow.com/questions/73736/) * [What Web Application Framework for Java is Recommended?](https://stackoverflow.com/questions/24596/) * [Java Validation Frameworks](https://stackoverflow.com/questions/397852/) * [Validation Framework in Java](https://stackoverflow.com/questions/580686/) * [Java 2D Game Frameworks](https://stackoverflow.com/questions/293079/) * [What are good docking frameworks for Java/Swing?](https://stackoverflow.com/questions/304874/) * [Which framework should I choose - Seam, Wicket, JSF or GWT?](https://stackoverflow.com/questions/745029/) * [Java Frameworks War: Spring and Hibernate](https://stackoverflow.com/questions/100243/) * [Recommended framework for Java Web Services](https://stackoverflow.com/questions/289977/) * [Java Desktop application framework](https://stackoverflow.com/questions/51002/) * [Alternate Java GUI Frameworks](https://stackoverflow.com/questions/286251/) * [What’s the best mock framework for Java?](https://stackoverflow.com/questions/22697/) * [Java configuration framework](https://stackoverflow.com/questions/25765/) You can do this search yourself via [Google](http://www.google.com/search?q=site:stackoverflow.com+java+framework&hl=en)
I can't be sure, what I am gonna use in the coming new project. Unless otherwise, I am planning to do [RDD](http://shahid.shah.org/index.php/archives/15), also [here](http://willcode4beer.com/opinion.jsp?set=in_favor_of_rdd) and [here](http://www.thousandtyone.com/blog/ResumeDrivenDevelopmentTheHammerAndTheNail.aspx).
What are the most commonly used Java Frameworks?
[ "", "java", "frameworks", "" ]
I have a small single-threaded C++ application, compiled and linked using Visual Studio 2005, that uses boost (crc, program\_options, and tokenizer), a smattering of STL, and assorted other system headers. (It's primary purpose is to read in a .csv and generate a custom binary .dat and a paired .h declaring structures that "explain" the format of the .dat.) The tool is crashing (access violation on NULL) when run outside the debugger, only in release. E.g. pressing F5 does not cause the tool to crash, Ctrl-F5 does. When I re-attach the debugger, I get this stack: ``` ntdll.dll!_RtlAllocateHeap@12() + 0x26916 bytes csv2bin.exe!malloc(unsigned int size=0x00000014) Line 163 + 0x63 bytes C csv2bin.exe!operator new(unsigned int size=0x00000014) Line 59 + 0x8 bytes C++ >csv2bin.exe!Record::addField(const char * string=0x0034aac8) Line 62 + 0x7 bytes C++ csv2bin.exe!main(int argc=0x00000007, char * * argv=0x00343998) Line 253 C++ csv2bin.exe!__tmainCRTStartup() Line 327 + 0x12 bytes C ``` The line it's crashing on is a somewhat innocuous-looking allocation: ``` pField = new NumberField(this, static_cast<NumberFieldInfo*>(pFieldInfo)); ``` ...I don't believe it has reached the constructor yet, it's just allocating memory before jumping to the constructor. It has also executed this code dozens of times by the time it crashes, usually in a consistent (but otherwise non-suspicious) location. The problem goes away when compiling with /MTd or /MDd (debug runtime), and comes back when using /MT or /MD. The NULL is loaded from the stack, and I can see it in memory view. \_RtlAllocateHeap@12 + 0x26916 bytes seems like a *huge* offset, like an incorrect jump has been made. I've tried `_HAS_ITERATOR_DEBUGGING` in a debug build and that hasn't brought up anything suspicious. Dropping a HeapValidate at the beginning and end of Record::addField shows an OK heap right up to when it crashes. This used to work -- I'm not entirely sure what changed between now and the last time we compiled the tool (probably years ago, maybe under an older VS). We've tried an older version of boost (1.36 vs 1.38). Before dropping back to manual investigation of the code or feeding this to PC-Lint and combing through its output, any suggestions on how to effectively debug this? [I'll be happy to update the question with more info, if you request info in the comments.]
One little know difference between running with debugger attached or not is the OS Debug Heap (see also [Why does my code run slowly when I have debugger attached](https://stackoverflow.com/questions/1060337/why-does-my-stl-code-run-so-slowly-when-i-have-the-debugger-ide-attached/1060929#1060929)?). You can turn the debug heap off by using environment variable \_NO\_DEBUG\_HEAP . You can specify this either in your computer properties, or in the Project Settings in Visual Studio. Once you turn the debug heap off, you should see the same crash even with debugger attached. That said, be aware memory corruptions can be hard to debug, as often the real cause of the corruption (like some buffer overrun) may be very far from where you see the symptoms (the crash).
Crashing inside new or malloc usually is a hint that the (internal) structure of the malloc implementation has been corrupted. This is most of the time done by writing past a previous allocation (buffer overflow). Then on the next call to new or malloc the app crashes as the internal structure now contains invalid data. Check if you may overwrite any previous allocated space. If your application is portable you may try to build it on Linux and run it under [Valgrind](http://en.wikipedia.org/wiki/Valgrind).
/MT and /MD builds crashing, but only when debugger isn't attached: how to debug?
[ "", "c++", "visual-studio", "visual-studio-2005", "boost", "" ]
Windows XP, Python 2.5: ``` hash('http://stackoverflow.com') Result: 1934711907 ``` Google App Engine (<http://shell.appspot.com/>): ``` hash('http://stackoverflow.com') Result: -5768830964305142685 ``` Why is that? How can I have a hash function that will give me same results across different platforms (Windows, Linux, Mac)?
Use [hashlib](http://docs.python.org/library/hashlib.html?highlight=hash#module-hashlib) as `hash()` [was designed to be used to](https://docs.python.org/2/library/functions.html#hash): > quickly compare dictionary keys during a dictionary lookup and therefore does not guarantee that it will be the same across Python implementations.
As stated in the documentation, built-in hash() function is *not* designed for storing resulting hashes somewhere externally. It is used to provide object's hash value, to store them in dictionaries and so on. It's also implementation-specific (GAE uses a modified version of Python). Check out: ``` >>> class Foo: ... pass ... >>> a = Foo() >>> b = Foo() >>> hash(a), hash(b) (-1210747828, -1210747892) ``` As you can see, they are different, as hash() uses object's `__hash__` method instead of 'normal' hashing algorithms, such as SHA. Given the above, the rational choice is to use the [hashlib](http://docs.python.org/library/hashlib.html) module.
Built in Python hash() function
[ "", "python", "google-app-engine", "hash", "" ]
How can I show the 'Save as' dialog box using PHP which will ask the user to download a string as a text file? Basically I will retrieve some values from the database, and want then to be able to download a .txt file which contains this data.
This should work: ``` header('Content-type: text/plain'); header('Content-disposition: attachment; filename="test.txt"'); ```
Just to expand on @Emil H's answer: Using those header calls will only work in the context of a new request. You'll need to implement something that allows your script to know when it's actually sending the file as opposed to when it's displaying a form telling the user to download the file.
How to show 'Save as' dialog box using PHP for text files
[ "", "php", "http", "mime-types", "" ]
I am a bit new to ThreadPool in .NET. I was wondering, if I can only send one object to my callback method, how am I able to access the class member variable to call its methods? (see customClass in CallBack()) And how would I load the data from customClass? Do I pass the customClass to a different CallBack method? is this approach alright? As you can see it is a bit of lack of experience, so any tips along the way would really be appreciated. Thank you, Kave ``` class Program { static void Main(string[] args) { CustomClass customClass = new CustomClass(); ThreadPool.QueueUserWorkItem(CallBack, "Hello"); Console.Read(); } private static void CallBack(object state) { customClass.SaveData(state.ToString()); } } ```
``` class Program { static void Main(string[] args) { CustomClass customClass = new CustomClass(); ThreadPool.QueueUserWorkItem(x => CallBack(customClass, "Hello")); Console.Read(); } private static void CallBack(CustomClass custom, string text) { customClass.SaveData(text); } } ```
The easiest way to do this is to use a [closure](http://csharpindepth.com/Articles/Chapter5/Closures.aspx) to capture all the variables you want (i.e. use an anonymous method or a lambda expression). You need to be careful about exactly what's captured if you're using a loop, but it's handier than passing through an object and having to cast it back to the right type etc.
How to deal with ThreadPool and member variables?
[ "", "c#", ".net", "multithreading", "variables", "member", "" ]
I am writing an editor which has lot of parameters that could be easily interacted with through text. I find it inconvenient to implement a separate text-editor or lots of UI code for every little parameter. Usual buttons, boxes and gadgets would be burdensome and clumsy. I'd much rather let user interact with those parameters through vim. The preferable way for me would be to get editor open vim with my text buffer. Then, when one would save the text buffer in vim, my editor would get notified from that and update it's view.
Write your intermediate results (what you want the user to edit) to a temp file. Then use the `$EDITOR` environment variable in a system call to make the user edit the temp file, and read the results when the process finishes. This lets users configure which editor they want to use in a pseudo-standard fashion.
Check out [It's All Text!](https://addons.mozilla.org/en-US/firefox/addon/4125). It's a Firefox add-in that does something similar for `textarea`s on web pages, except the editor in question is configurable.
How to interact through vim?
[ "", "python", "linux", "vim", "" ]
There was a passing comment in a book of mine about people inputting commas into integers and messing up your program, but it didn't elaborate. That got me thinking, so I tried writing a little algorithm to take an std::string and remove all non-integer characters. This code compiles but skips over output. Why isn't anything being assigned to newstring? Does if(isdigit(fstring[i])) evaluate to true of the address it's pointing to hold a digit? ``` //little algorithm to take the non-integers out of a string //no idea on efficiency #include <iostream> #include <string> int main() { std::cout << "Enter a number with non-integer characters: "; std::string fstring; getline(std::cin, fstring); std::string newstring; int i = 0, x = 0; while (i != fstring.length()) { if (isdigit(fstring[i])) { newstring[x] = fstring[i]; i++; x++; } else { i++; } } std::cout << std::endl; std::cout << newstring; system("PAUSE"); } ``` Secondary question, that perhaps belongs elsewhere: how do you convert a string to an int (or a floating point number)?
newstring is of length 0, so newstring[x] where x=0 is actually illegal. You should append to the string using: newstring.append(1, fstring[i]) For the secondary question, look for atoi(), atof(), strtol(0, strtof() functions.
Strings are like arrays, but the default constructor for a string creates an empty string. Why should it allocate more memory than it needs? Even if it does, there's no saying how much, or if it will be big enough for a filtered copy of fstring. I'm impressed it doesn't crash. A simple modification would be to change: ``` std::string newstring; ``` to: ``` std::string newstring(fstring.length(), '\0') ``` And after the loop add: ``` newstring.resize(x); ``` This will ensure that `newstring` will have at least enough room (probably more) during the filtration and will be trimmed down to the appropriate size when you are finished filtering. You may also be interested in the [`std::remove_copy_if`](http://www.sgi.com/tech/stl/remove_copy_if.html) function in `<algorithm>`. E.g. ``` struct isnotdigit { bool operator()(char c) { return !isdigit(c); } }; std::string newstring(fstring.length(), '\0'); std::string::iterator i = std::remove_copy_if(fstring.begin(), fstring.end(), newstring.begin(), isnotdigit()); newstring.erase(i, newstring.end()); ``` As for converting a string to an integer / float, in addition to `atoi`, `strtol`, `atof`, `strtof`, etc. functions already mentioned you can also make using of the iostream library: ``` #include <sstream> std::string integer("23"); std::istringstream iss(integer); int result; iss >> result; std::string floatingpoint("3.14"); std::istringstream iss2(floatingpoint); double result2; iss2 >> result2; ``` Also, if you are familiar with the printf family of functions you may be interested in `scanf`, `sscanf` ``` const char *s = "23"; int result; sscanf(s, "%d", &result); ```
Removing non-integers from a string in C++
[ "", "c++", "casting", "variable-assignment", "" ]
I have a repository class that wraps my LINQ to SQL Data Context. The repository class is a business line class that contains all the data tier logic (and caching and such). Here's my v1 of my repo interface. ``` public interface ILocationRepository { IList<Location> FindAll(); IList<Location> FindForState(State state); IList<Location> FindForPostCode(string postCode); } ``` But to handle paging for FindAll, I'm debating whether or not to expose IQueryable<ILocation> instead of IList to simplify the interface for circumstances such as paging. What are the pros and cons to exposing IQueryable from the data repo? Any help is very much appreciated.
The pros; composability: * callers can add filters * callers can add paging * callers can add sorting * etc The cons; non-testability: * Your repository is no longer properly unit testable; you can't rely on a: it working, b: **what** it does; + the caller could add a non-translatable function (i.e. no TSQL mapping; breaks at runtime) + the caller could add a filter/sort that makes it perform like a dog * Since callers expect `IQueryable<T>` to be composable, it rules out non-composable implementations - or it forces you to write your own query provider for them * it means you can't optimize / profile the DAL For stability, I've taken to **not** exposing `IQueryable<T>` or `Expression<...>` on my repositories. This means I know how the repository behaves, and my upper layers can use mocks without worrying "does the actual repository support this?" (forcing integration tests). I still use `IQueryable<T>` etc *inside* the repository - but not over the boundary. I posted some [more thoughts on this theme here](http://marcgravell.blogspot.com/2009/02/pragmatic-linq.html). It is just as easy to put paging parameters on the repository interface. You can even use extension methods (on the interface) to add *optional* paging parameters, so that the concrete classes only have 1 method to implement, but there may be 2 or 3 overloads available to the caller.
**As mentioned by previous answer, exposing IQueryable gives access to callers to play with IQueryable itself, which is or it can become dangerous.** Encapsulating business logic's first responsibility is to maintain integrity of your database. You can continue exposing IList and may be change your parameters as following, this is how we are doing... ``` public interface ILocationRepository { IList<Location> FindAll(int start, int size); IList<Location> FindForState(State state, int start, int size); IList<Location> FindForPostCode(string postCode, int start, int size); } ``` if size == -1 then return all... **Alternative way...** If you still want to return IQueryable, then you can return IQueryable of List inside your functions.. for example... ``` public class MyRepository { IQueryable<Location> FindAll() { List<Location> myLocations = ....; return myLocations.AsQueryable<Location>; // here Query can only be applied on this // subset, not directly to the database } } ``` First method has an advantage over memory, because you will return less data instead of all.
To return IQueryable<T> or not return IQueryable<T>
[ "", "c#", ".net", "linq-to-sql", "iqueryable", "" ]
Is there a way to create a non nullable type in C# (like DateTime or TimeSpan).? Also is there a way (an attribute maybe) to enforce that not null arguments wouldn't be passed to methods and properties without adding ``` if(arg1 == null) { throw new ArgumentNullException("this attribute is null") } ```
`DateTime` and `TimeSpan` are not-nullable since they are `struct`s rather than `class`es. As for your second question, there is no standard way you can do this in C#. You can do this using PostSharp, which is an AOP framework, or with [Spec#](http://research.microsoft.com/SpecSharp), which is a whole new language (an extension of C#) which allows for some of desired behavior.
The null-checking you refer to will be easier in .NET 4.0 / C# 4.0 via code-contracts, which does pretty much what you want. Structs are already non-nullable, but don't go creating your own structs like crazy - you rarely need them (classes are **far** more common). There is no real concept of a "non-nullable class"; people have *proposed* syntax changes like: ``` void Foo(string! arg1) {...} ``` which would have the compiler do the non-null check on `arg1` - but in reality, code-contracts does this and more. There are some things you can do in PostSharp, but it probably isn't worth the hastle. One other thought on a non-nullable class (and one of the reasons they aren't implemented); what would `default(T)` be for a non-nullable class? ;-p The spec *demands* that `default(T)` is well defined...
Not nullable types
[ "", "c#", "" ]
I've been looking to improve my programming habits and I heard that OO is the way to go. Also I'd much prefer online tutorials over books.
Here are a few good tutorials from the PHP guys themselves. * [PHP 101 (part 7): The Bear Necessities](http://devzone.zend.com/node/view/id/638) * [The OO Evolution of PHP](http://devzone.zend.com/article/1717-The-OO-Evolution-of-PHP) * [Using Objects to Create an Application](http://devzone.zend.com/article/1240-Using-Objects-to-Create-an-Application)
Learning how to use classes, methods, and attributes is not sufficient for making you a good object oriented programmer. The other (and usually much more difficult) part is understanding how to solve problems in an object-oriented way. It's a bit like chess: Even if you have memorized the rules perfectly, it does not mean you automatically are a good chess player. You still need to learn a about strategy and gather a lot of experience. I haven't found a good web tutorial on how to become a good object-oriented programmer. The topic is too large to be covered within just a few web pages. You are probably better off reading a book on the subject. It doesn't even have to be specific to php, most OO pricinples can be applied to many different OO languages. Once you have learned the basics of OO programming, I'd also recommend reading a book on design patterns such as the classic [Design Patterns](http://www.amazon.co.uk/Design-patterns-elements-reusable-object-oriented/dp/0201633612/ref=sr_1_1?ie=UTF8&s=books&qid=1238931499&sr=1-1) by Gamma et al. or the more casual [Head-First Design patterns](https://rads.stackoverflow.com/amzn/click/com/0596007124).
Where can I find some good tutorials to learn object orientated programming particularly for php?
[ "", "php", "oop", "" ]
What I am trying to do is the following: I have an array of values, these values will eventually be used to generate a random unique string but that's a little later. First I would like to loop through all the values in the array (foreach loop) then I would like to limit this (while loop) Is this a correct method for doing this? The below code does not work, can anybody see what I'm doing wrong? ``` <?php $array = array( '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '!', '£', '$', '%', '^', '&', '*', '(', ')', '_', '+', '{', '}' ); $length_of_unique_key = 15; $counter = 0; foreach($array as $values) { $counter++; while ($counter <= $length_of_unique_key) { } } ?> ```
Shouldn't you be incrementing your counter within the `while` loop, so it can exit?
The best way to see what is wrong with a loop (or any other control structure) is just to run through it. Sometimes you can do it in your head; at other times, it might be helpful to insert trace points into your code. In this case, I think if you simply run through the code in your head, you'll be able to pick up what's wrong with it. But for didactic purposes, I'll run through it here. First let's number each line of code: ``` $array = array(...); // line 1 $length = 15; // line 2 $counter = 0; // line 3 foreach($array as $values) // line 4 { $counter++; // line 5 while ($counter <= $length) // line 6 { // line 7 } // line 8 // line 9 } // line 10 ``` Now let's run through it: 1. `$array` is assigned a single dimensional array: `array(0 => '1', 1 => '2', 2 => '3', ...)` 2. `$length` is set to **15**. 3. `$counter` is to set **0**. 4. Begin `for loop`; `$values` = `$array[0]` = **'1'**. 5. `$counter` is incremented. `$counter` = **1**. 6. Begin `while loop`; check that `$counter` (**1**) <= `$length` (**15**). 7. Do nothing. 8. Go back to line 6. 9. Line 6: If `$counter` (**1**) <= `$length` (**15**), continue loop. 10. Line 7: Do nothing. 11. Line 8: Go back to line 6. 12. Line 6: `$counter` (**1**) is still <= `$length` (**15**), go into loop again. 13. Line 7: Do nothing. 14. Line 8: Go back to line 6. As you can see, you are stuck in an infinite loop because neither `$counter` nor `$length` change values. So the `while` condition in line 6 always evaluates to **true** (1 <= 15).
Possible to use a while loop within a loop?
[ "", "php", "while-loop", "" ]
I am in the phase of learning Zend Framework for PHP development, I have been doing 'dirty' PHP programming for about 2 years now and I have learnt quite a bit from my mistakes. I have been introduced to Ruby On Rails, it is a great framework and Ruby is quite an interesting language too, but not everyone wants their web sites to be in RoR, at least not all of my clients. Hence as a result I do a lot of PHP. Having worked on RoR, I find Zend Framework to provide very similar functionality and environment and hence I am really excited about the same. However I am interested to know if there are any 'generator' scripts that help you along the process to generate / automate common tasks such as project structure creation, model creation, controller creation, just like those in RoR? If such a thing already exists, great, otherwise I will go ahead and build such scripts myself as I am very certain they will come in very handy, especially for me.
[Zend Tool](http://framework.zend.com/manual/en/zend.tool.framework.html) is your friend!
i have made several code snippets and file types in editor ( netbeans ) to help me with automation. You could look into zend studio that has a built in integration for zend framework that work quite well, but its commercial and would mean switching IDE's wich is always a burdain
PHP Zend Framework Generator
[ "", "php", "zend-framework", "" ]
This code is taken from a SCJP practice test: ``` 3. public class Bridge { 4. public enum Suits { 5. CLUBS(20), DIAMONDS(20), HEARTS(30), SPADES(30), 6. NOTRUMP(40) { public int getValue(int bid) { return ((bid-1)*30)+40; } }; 7. Suits(int points) { this.points = points; } 8. private int points; 9. public int getValue(int bid) { return points * bid; } 10. } 11. public static void main(String[] args) { 12. System.out.println(Suits.NOTRUMP.getBidValue(3)); 13. System.out.println(Suits.SPADES + " " + Suits.SPADES.points); 14. System.out.println(Suits.values()); 15. } 16. } ``` On line 8 `points` is declared as private, and on line 13 it's being accessed, so from what I can see my answer would be that compilation fails. But the answer in the book says otherwise. Am I missing something here or is it a typo in the book?
All code inside single outer class can access anything in that outer class whatever access level is.
To expand on what stepancheg said: From the [Java Language Specification section 6.6.1 "Determining Accessibility"](http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.1): > if the member or constructor is > declared private, then access is > permitted if and only if it occurs > within the body of the top level class > that encloses the declaration of the > member or constructor. Essentially, `private` doesn't mean private to this class, it means private to the top-level class.
A question about enums defined inside a class in java
[ "", "java", "enums", "" ]
I need to import data from Excel into a SQL 2000 db. I need to import 6 fields from the worksheet and increment a string field containing an integer padded to 5 characters with leading zeros. This field is not the primary key and the db does not automatically populate this. Also the DB *will* allow this field to be entered as NULL if this helps and then change afterwards if this helps. I can get the data into the table I need using a combination of rookie DTS and insert statments and manually update the string field for the 20 records I have to do today, but next week I need to import around 1000 records. Should I write a C#/ADO.net app to do this, [bearing in mind I'm a newbie so that'll take me a couple of days :-) ] or is there a way I can increment a string field using DTS directly or some sort of loop in an insert statement? Thanks in advance G **EDIT:** The table I'm inserting into is constructed as below and I need to update "cedeviceid", "vanwarehouse", "username", "devicesimnumber", "UserGroup" and "ServiceMgr". from the Excel sheet. "sendercode" is the string I need to increment CREATE TABLE [dbo].[mw\_gsmprofile]( [cedeviceid] varchar NOT NULL, [mainwarehouse] varchar NULL, [vanwarehouse] varchar NULL, [username] varchar NULL, [sendercode] varchar NULL, [devicesimnumber] varchar NULL, [usersupportgsm] [int] NULL, [userisonline] [int] NULL, [onlinedate] varchar NULL, [lastsentsequenceno] [int] NULL, [lastsentdate] varchar NULL, [lastreceivedsequenceno] [int] NULL, [lastreceiveddate] varchar NULL, [EnableAutoDownloading] [int] NULL, [EnableCompressFile] [int] NULL, [LogonUserName] varchar NULL, [LogonPassword] varchar NULL, [LogonDomain] varchar NULL, [UserGroup] varchar NULL, [UseStorageCard] [int] NULL, [SMSMapProfile] varchar NULL, [SMPPClientFlag] [int] NULL, [LASTUPDATE] varchar NULL, [ServiceMgr] varchar NULL, [VanLocation] varchar NULL, [OnHireWarehouse] varchar NULL, [OnHireWhsRepType] [int] NULL, [HireDepotWarehouse] varchar NULL, [HireDepotWhsRepType] [int] NULL, CONSTRAINT [PK\_mw\_gsmprofile] PRIMARY KEY CLUSTERED ( [cedeviceid] ASC )WITH (PAD\_INDEX = OFF, STATISTICS\_NORECOMPUTE = OFF, IGNORE\_DUP\_KEY = OFF, ALLOW\_ROW\_LOCKS = ON, ALLOW\_PAGE\_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] **SAMPLE DATA** cedeviceid,vanwarehouse, username, devicesimnumber, UserGroup, ServiceMgr 3431, 999, INSTALL TEAM 1,,INSTAL, AHOA 3441, 999, INSTALL TEAM 2,,INSTAL, AHOA 3451, 999, INSTALL TEAM 3,,INSTAL, AHOA 3461, 999, INSTALL TEAM 4,,INSTAL, AHOA 3471, 999, INSTALL TEAM 5,,INSTAL, AHOA 3472, 999, INSTALL TEAM 6,,INSTAL, AHOA
I would do this with a small app. You have to get the first item of the table, sorted in reverse order (this will give you the maximum value of the id). After knowing the maximum value, you can increment it very easily with the expressiveness of a programming language.
Some slifght own trumpet blowing here, but my own FOSS tool [CSVfix](http://code.google.com/p/csvfix/) can do this without writing any code, using the (inexplicably) uundocmented **sequence** commanbd. For example, given a CSV file: ``` foo,bar one,two three,four ``` then: ``` csvfix sequence -n 42 -p 5 afile.csv ``` would produce the output: ``` 00042, foo, bar 00043, one, two 00044, three,four ``` the -p option specifies the padding and the -n option the starting number. Now to find out how it got omitted from the help file....
How can I import data to SQL from CSV or XLS automatically incrementing a string field based on current records in DB?
[ "", "sql", "import", "auto-increment", "" ]
I have a table with the following structure: ID, Month, Year, Value with values for one entry per id per month, most months have the same value. I would like to create a view for that table that collapses the same values like this: ID, Start Month, End Month, Start Year, End Year, Value, with one row per ID per value. The catch is that if a value changes and then goes back to the original, it should have two rows in the table So: * 100 1 2008 80 * 100 2 2008 80 * 100 3 2008 90 * 100 4 2008 80 should produce * 100 1 2008 2 2008 80 * 100 3 2008 3 2008 90 * 100 4 2008 4 2008 80 The following query works for everything besides this special case, when the value returns to the original. ``` select distinct id, min(month) keep (dense_rank first order by month) over (partition by id, value) startMonth, max(month) keep (dense_rank first order by month desc) over (partition by id, value) endMonth, value ``` Database is Oracle
I got it to work as follows. It is heavy on analytic functions and is Oracle specific. ``` select distinct id, value, decode(startMonth, null, lag(startMonth) over(partition by id, value order by startMonth, endMonth), --if start is null, it's an end so take from the row before startMonth) startMonth, decode(endMonth, null, lead(endMonth) over(partition by id, value order by startMonth, endMonth), --if end is null, it's an start so take from the row after endMonth) endMonth from ( select id, value, startMonth, endMonth from( select id, value, decode(month+1, lead(month) over(partition by id,value order by month), null, month) startMonth, --get the beginning month for each interval decode(month-1, lag(month) over(partition by id,value order by month), null, month) endMonth --get the end month for each interval from Tbl ) a where startMonth is not null or endMonth is not null --remain with start and ends only )b ``` It might be possible to simplify some of the inner queries somewhat The inner query checks if the month is a first/last month of the interval as follows: if the month + 1 == the next month (lag) for that grouping, then since there is a next month, this month is obviously not the end month. Otherwise, it *is* the last month of the interval. The same concept is used to check for the first month. The outer query first filters out all rows that are not either start or end months (`where startMonth is not null or endMonth is not null`). Then, each row is either a start month or an end month (or both), determined by whether start or end is not null). If the month is a start month, get the corresponding end month by getting the next (lead) endMonth for that id,value ordered by endMonth, and if it is an endMonth get the startMonth by looking for the previous startMonth (lag)
I'm going to develop my solution incrementally, decomposing each transformation into a view. This both helps explain what's being done, and helps in debugging and testing. It's essentially applying the principle of functional decomposition to database queries. I'm also going to do it without using Oracle extensions, with SQL that ought to run on any modern RBDMS. So no keep, over, partition, just subqueries and group bys. (Inform me in the comments if it doesn't work on your RDBMS.) First, the table, which since I'm uncreative, I'll call month\_value. Since the id is not actually a unique id, I'll call it "eid". The other columns are "m"onth, "y"ear, and "v"alue: ``` create table month_value( eid int not null, m int, y int, v int ); ``` After inserting the data, for two eids, I have: ``` > select * from month_value; +-----+------+------+------+ | eid | m | y | v | +-----+------+------+------+ | 100 | 1 | 2008 | 80 | | 100 | 2 | 2008 | 80 | | 100 | 3 | 2008 | 90 | | 100 | 4 | 2008 | 80 | | 200 | 1 | 2008 | 80 | | 200 | 2 | 2008 | 80 | | 200 | 3 | 2008 | 90 | | 200 | 4 | 2008 | 80 | +-----+------+------+------+ 8 rows in set (0.00 sec) ``` Next, we have one entity, the month, that's represented as two variables. That should really be one column (either a date or a datetime, or maybe even a foreign key to a table of dates), so we'll make it one column. We'll do that as a linear transform, such that it sorts the same as (y, m), and such that for any (y,m) tuple there is one and only value, and all values are consecutive: ``` > create view cm_abs_month as select *, y * 12 + m as am from month_value; ``` That gives us: ``` > select * from cm_abs_month; +-----+------+------+------+-------+ | eid | m | y | v | am | +-----+------+------+------+-------+ | 100 | 1 | 2008 | 80 | 24097 | | 100 | 2 | 2008 | 80 | 24098 | | 100 | 3 | 2008 | 90 | 24099 | | 100 | 4 | 2008 | 80 | 24100 | | 200 | 1 | 2008 | 80 | 24097 | | 200 | 2 | 2008 | 80 | 24098 | | 200 | 3 | 2008 | 90 | 24099 | | 200 | 4 | 2008 | 80 | 24100 | +-----+------+------+------+-------+ 8 rows in set (0.00 sec) ``` Now we'll use a self-join in a correlated subquery to find, for each row, the earliest successor month in which the value changes. We'll base this view on the previous view we created: ``` > create view cm_last_am as select a.*, ( select min(b.am) from cm_abs_month b where b.eid = a.eid and b.am > a.am and b.v <> a.v) as last_am from cm_abs_month a; > select * from cm_last_am; +-----+------+------+------+-------+---------+ | eid | m | y | v | am | last_am | +-----+------+------+------+-------+---------+ | 100 | 1 | 2008 | 80 | 24097 | 24099 | | 100 | 2 | 2008 | 80 | 24098 | 24099 | | 100 | 3 | 2008 | 90 | 24099 | 24100 | | 100 | 4 | 2008 | 80 | 24100 | NULL | | 200 | 1 | 2008 | 80 | 24097 | 24099 | | 200 | 2 | 2008 | 80 | 24098 | 24099 | | 200 | 3 | 2008 | 90 | 24099 | 24100 | | 200 | 4 | 2008 | 80 | 24100 | NULL | +-----+------+------+------+-------+---------+ 8 rows in set (0.01 sec) ``` last\_am is now the "absolute month" of the first (earliest) month (after the month of the current row) in which the value, v, changes. It's null where there is no later month, for that eid, in the table. Since last\_am is the same for all months leading up to the change in v (which occurs at last\_am), we can group on last\_am and v (and eid, of course), and in any group, the min(am) is the absolute month of the *first* consecutive month that had that value: ``` > create view cm_result_data as select eid, min(am) as am , last_am, v from cm_last_am group by eid, last_am, v; > select * from cm_result_data; +-----+-------+---------+------+ | eid | am | last_am | v | +-----+-------+---------+------+ | 100 | 24100 | NULL | 80 | | 100 | 24097 | 24099 | 80 | | 100 | 24099 | 24100 | 90 | | 200 | 24100 | NULL | 80 | | 200 | 24097 | 24099 | 80 | | 200 | 24099 | 24100 | 90 | +-----+-------+---------+------+ 6 rows in set (0.00 sec) ``` Now this is the result set we want, which is why this view is called cm\_result\_data. All that's lacking is something to transform absolute months back to (y,m) tuples. To do that, we'll just join to the table month\_value. There are only two problems: 1) we want the month *before* last\_am in our output, and 2) we have nulls where there is no next month in our data; to met the OP's specification, those should be single month ranges. EDIT: These could actually be longer ranges than one month, but in every case they mean we need to find the latest month for the eid, which is: ``` (select max(am) from cm_abs_month d where d.eid = a.eid ) ``` Because the views decompose the problem, we could add in this "end cap" month earlier, by adding another view, but I'll just insert this into the coalesce. Which would be most efficient depends on how your RDBMS optimizes queries. To get month before, we'll join (cm\_result\_data.last\_am - 1 = cm\_abs\_month.am) Wherever we have a null, the OP wants the "to" month to be the same as the "from" month, so we'll just use coalesce on that: coalesce( last\_am, am). Since last eliminates any nulls, our joins don't need to be outer joins. ``` > select a.eid, b.m, b.y, c.m, c.y, a.v from cm_result_data a join cm_abs_month b on ( a.eid = b.eid and a.am = b.am) join cm_abs_month c on ( a.eid = c.eid and coalesce( a.last_am - 1, (select max(am) from cm_abs_month d where d.eid = a.eid ) ) = c.am) order by 1, 3, 2, 5, 4; +-----+------+------+------+------+------+ | eid | m | y | m | y | v | +-----+------+------+------+------+------+ | 100 | 1 | 2008 | 2 | 2008 | 80 | | 100 | 3 | 2008 | 3 | 2008 | 90 | | 100 | 4 | 2008 | 4 | 2008 | 80 | | 200 | 1 | 2008 | 2 | 2008 | 80 | | 200 | 3 | 2008 | 3 | 2008 | 90 | | 200 | 4 | 2008 | 4 | 2008 | 80 | +-----+------+------+------+------+------+ ``` By joining back we get the output the OP wants. Not that we have to join back. As it happens, our absolute\_month function is bi-directional, so we can just recalculate the year and offset month from it. First, lets take care of adding the "end cap" month: ``` > create or replace view cm_capped_result as select eid, am, coalesce( last_am - 1, (select max(b.am) from cm_abs_month b where b.eid = a.eid) ) as last_am, v from cm_result_data a; ``` And now we get the data, formatted per the OP: ``` select eid, ( (am - 1) % 12 ) + 1 as sm, floor( ( am - 1 ) / 12 ) as sy, ( (last_am - 1) % 12 ) + 1 as em, floor( ( last_am - 1 ) / 12 ) as ey, v from cm_capped_result order by 1, 3, 2, 5, 4; +-----+------+------+------+------+------+ | eid | sm | sy | em | ey | v | +-----+------+------+------+------+------+ | 100 | 1 | 2008 | 2 | 2008 | 80 | | 100 | 3 | 2008 | 3 | 2008 | 90 | | 100 | 4 | 2008 | 4 | 2008 | 80 | | 200 | 1 | 2008 | 2 | 2008 | 80 | | 200 | 3 | 2008 | 3 | 2008 | 90 | | 200 | 4 | 2008 | 4 | 2008 | 80 | +-----+------+------+------+------+------+ ``` And there's the data the OP wants. All in SQL that should run on any RDBMS, and is decomposed into simple, easy to understand and easy to test views. Is is better to rejoin or to recalculate? I'll leave that (it's a trick question) to the reader. (If your RDBMS doesn't allow group bys in views, you'll have to join first and then group, or group and then pull in the month and year with correlated subqueries. This is left as an exercise for the reader.) --- Jonathan Leffler asks in the comments, > What happens with your query if there > are gaps in the data (say there's an > entry for 2007-12 with value 80, and > another for 2007-10, but not one for > 2007-11? The question isn't clear what > should happen there. Well, you're exactly right, the OP doesn't specify. Perhaps there's an (unmentioned) pre-condition that there are no gaps. In the absence of a requirement, we shouldn't try to code around something that might not be there. But, the fact is, gaps make the "joining back" strategy fail; the "recalculate" strategy doesn't fail under those conditions. I'd say more, but that would reveal the trick in the trick question I alluded to above.
SQL Query to Collapse Duplicate Values By Date Range
[ "", "sql", "oracle", "" ]
My site is suffering from the [Operation Aborted error](http://support.microsoft.com/kb/927917). What I find weird is that in my case the error only sometimes happens. The site has been running fine for three months then today it starts happening but not every time. The page this is occuring on is rather large with a lot of third party controls. What I'd like is a tool that could pinpoint where the failure is occuring. Seems like the best I can do is find the first javascript error that occurs after the operation aborted; however, this doesn't help much. This failure is because an element of the dom isn't available which I'd expect since IE stopped parsing the HTML. Any one have any ideas or tricks to narrow this down? # Edit I appreciate additional ways to resolve the issue; however, what I am looking for is a way to identify which script is causing the issue. # Final Edit After switching to IE8, I was able to determine the cause was the AjaxControl Toolkit's modal popup dialog. There was no concrete way to determine this which is dissapointing, but the debugger let me see where it was failing which was very consistent. Since there is no way in the control to tell it to move its initialization, I disabled it, and have the script to create the client side control in my document load event handler. This issue is no fault of the control, it was occuring because the content for the popup is actually in a second form. Frankly I'm surprised it ever worked.
Do you have any javascript that is manipulating the DOM, as the case is described at <http://support.microsoft.com/kb/927917#more_information> ? Try moving all script blocks to the very bottom of the page, just before the `</body>` tag, and don't try to set the innerHTML property of the body tag itself. If the problem is with javascript executing before the DOM is fully built, try moving any initialization calls into a function that will run only after the page is fully loaded. So, instead of something like this: ``` <div class="myWidgetControl"/> <script type="text/javascript"> initializeWidgets(); </script> ``` Try something like this: ``` <div class="myWidgetControl"/> <script type="text/javascript"> $(document).ready( function () { initializeWidgets(); } ); </script> ```
You can use script provided by IE Blog to investigate the problem. See: <http://blogs.msdn.com/ie/archive/2009/09/03/preventing-operation-aborted-scenarios.aspx>
Detecting cause of IE's Operation Aborted Issue
[ "", "javascript", "internet-explorer", "" ]
In VS2008 (and earlier if I'm not mistaking) I have dropdown that lets me choose between Debug and Release mode. All well. When I switch VS to Release, the debug attribute in my web.config files isn't set to false at all though. Is this the way it is supposed to be? I am bound to forget to set it to the correct value on deploying.. What measures should I take to make sure this is working like it should?
This is one solution to this problem: <http://blog.aggregatedintelligence.com/2009/04/aspnet-never-again-fear-publishing-your.html>
Well your web.config would probably be different for debug and release (connection string, passwords, etc...) but if it's not, look at a postbuild event which would copy over a different file. Also check [this blog post](http://weblogs.asp.net/scottgu/archive/2007/09/21/tip-trick-automating-dev-qa-staging-and-production-web-config-settings-with-vs-2005.aspx) from Scott Guthrie.
Why doesn't switching to release in VS set the debug parameter to false in web.config
[ "", "c#", ".net", "asp.net-mvc", "visual-studio", "" ]
Does anyone know which characters are allowed in a VS project name? Is there a reference somewhere?
> * Cannot contain any of the following characters: / ? : & \ \* " < > | # % > * Cannot contain unicode characters > * Cannot contain surrogate characters > * Cannot be reserved names including 'CON', 'AUX', 'PRN', 'COM1' or 'LPT2' > * Cannot be '.' or '..' I obtained this information by trying to create a project with a character I knew would not be accepted. I.e. a character that is not allowed in NTFS file paths. I.e. I used a project with the name | to get the error.
Visual Studio returns the following error on trying to create a project with invalid characters: ![Invalid project name error in Visual Studio 2012](https://i.stack.imgur.com/AV1tv.png) > ### Microsoft Visual Studio > > --- > > New Project > > Project and solution names cannot: > > * contain any of the following characters: `/` `?` `:` `&` `\` `*` `"` `<` `>` `|` `#` `%` > * contain Unicode control characters > * contain surrogate characters > * be system reserved names, including `CON`, `AUX`, `PRN`, `COM1` or `LPT2` > * be `.` or `..` > > Please enter a valid name. > > --- > > `OK`
Which characters are allowed in a VS project name?
[ "", "c#", ".net", "visual-studio", "visual-studio-2008", "" ]
I have the following tables: ``` Country: Country_ID, CountryName Regions: Region_ID, RegionName, Country_ID Areas: Area_ID, AreaName, RegionID ``` I am not using foreign keys and not planning to do so, all I wanna do now is to be able in one query in the tableAdapter of country table to delete Country and all related regions, areas... How?
In one query? I doubt you could. But you could do it in a three: ``` delete from Areas where RegionID in (select Region_ID from Regions where Country_ID in (select Country_ID where CountryName='Somelandia')) delete from Regions where Country_ID in (select Country_ID where CountryName='Somelandia') delete from Country where CountryName = 'Somelandia' ``` That being said, I strongly recommend you reconsider using foreign key relationships and cascade delete for this purpose.
Use transactions. Start a transaction, then use three DELETE statements, then COMMIT TRANSACTION statement.
SQL Cascading delete without foreign keys?
[ "", "sql", "database", "" ]
I have recently added a HasValue function to our internal javascript library: ``` function HasValue(item) { return (item !== undefined && item !== null); } ``` A during a convorsation with a coworker, we came up with the idea of also adding another function that would basically just be the inverse: perhaps HasNoValue, or IsNothing If we ended up doing that we would have: ``` function HasNoValue(item) { return (item === undefined || item === null); } function HasValue(item) { return !HasNoValue(item); } ``` However, we're not sure whether it is more readable to have both, or HasValue. Which is more readable/preferred? A: ``` if (HasValue(x) && !HasValue(y)) ``` B: ``` if (HasValue(x) && HasNoValue(y)) ```
I vastly prefer A to B. "!" is a programming idiom that should be understood by all.
If `!HasValue(y)` and `HasNoValue(y)` are guaranteed to be logically equivalent over the entire input range of `y`, then I would greatly prefer `!HasValue(y)`. I would hesitate to even *have* a function named `HasNoValue(y)` because inevitably someone will write `!HasNoValue(y)`.
Is it worth the effort to have a function that returns the inverse of another function?
[ "", "javascript", "readability", "syntactic-sugar", "" ]
Here is a snippet of an HTML file I'm exploring with Beautiful Soup. ``` <td width="50%"> <strong class="sans"><a href="http:/website">Site</a></strong> <br /> ``` I would like to get the `<a href>` for any line which has the `<strong class="sans">` and which is inside a `<td width="50%">`. Is it possible to query a HTML file for those multiple conditions using Beautiful Soup ?
BeautifulSoup's search mechanisms accept a callable, which the docs appear to recommend for your case: "If you need to impose complex or interlocking restrictions on a tag's attributes, pass in a callable object for name,...". (ok... they're talking about attributes specifically, but the advice reflects an underlying spirit to the BeautifulSoup API). If you want a one-liner: ``` soup.findAll(lambda tag: tag.name == 'a' and \ tag.findParent('strong', 'sans') and \ tag.findParent('strong', 'sans').findParent('td', attrs={'width':'50%'})) ``` I've used a lambda in this example, but in practice you may want to define a callable function if you have multiple chained requirements as this lambda has to make two `findParent('strong', 'sans')` calls to avoid raising an exception if an `<a>` tag has no `strong` parent. Using a proper function, you could make the test more efficient.
``` >>> BeautifulSoup.BeautifulSoup("""<html><td width="50%"> ... <strong class="sans"><a href="http:/website">Site</a></strong> <br /> ... </html>""" ) <html><td width="50%"> <strong class="sans"><a href="http:/website">Site</a></strong> <br /> </td></html> >>> [ a for a in strong.findAll("a") for strong in tr.findAll("strong", attrs = {"class": "sans"}) for tr in soup.findAll("td", width = "50%")] [<a href="http:/website">Site</a>] ```
Complex Beautiful Soup query
[ "", "python", "beautifulsoup", "" ]
I would like to have a clean C# class that authenticates from Active Directory. It should be pretty simple, it just has to ask for credentials and check if it matches what AD is expecting. I am responsible for a number of C# applications, and I would like all of them to use the same class. Could someone please provide a clean code sample of such a class? It should have good error handling, be well commented, and specifically ask for credentials rather than try to read if a user is already logged in to AD for another application. (This is a security requirement because some applications are used in areas with shared computers: People with multiple roles and different permission levels may use the same computer and forget to log out between sessions)
<http://support.microsoft.com/kb/316748> ``` public bool IsAuthenticated(String domain, String username, String pwd) { String domainAndUsername = domain + "\\" + username; DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd); try { //Bind to the native AdsObject to force authentication. Object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + username + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if(null == result) { return false; } //Update the new path to the user in the directory. _path = result.Path; _filterAttribute = (String)result.Properties["cn"][0]; } catch (Exception ex) { throw new Exception("Error authenticating user. " + ex.Message); } return true; } ```
Admittedly I have no experience programming against AD, but the link below seems it might address your problem. <http://www.codeproject.com/KB/system/everythingInAD.aspx#35>
Generic Authentication Call to Active Directory in C#
[ "", "c#", "authentication", "active-directory", "" ]
How to get user mails in my free gmail inbox through contact us form on my website. I do not use email with my website name . i use free gmail. I tried many script but the all need email account on domain.
Does this question have something to do with [This One](https://stackoverflow.com/questions/751259/i-need-a-free-php-ajax-enabled-contact-us-form-script-and-mail-should-come-in-gma "This One?")? Well, so you have a form on your site, your users fill it up and you need an email with that data, right? Simple example: ``` <form action="sendMail.php" method="post"> Name: <input type="text" name="name" id="name" /><br /> Email: <input type="text" name="email" id="email" /><br /> Text: <textarea name="text"></textarea><br /> <input type="submit" value="Send" /> </form> ``` then, the php page wich send the mail: ``` //php sendThis.php page <?php require("class.phpmailer.php"); $name = $_POST['name']; $email = $_POST['email']; $text = $name . ', ' . $email . ' has filled the form with the text:<br />' . $_POST['text']; $from = 'your.email@gmail.com'; $to = 'your.email@gmail.com'; $gmailPass = 'your gmail password'; $mail = new PHPMailer(); $mail->IsSMTP(); // enable SMTP authentication $mail->SMTPAuth = true; // sets the prefix to the server $mail->SMTPSecure = "ssl"; // sets GMAIL as the SMTP server $mail->Host = 'smtp.gmail.com'; // set the SMTP port $mail->Port = '465'; // GMAIL username $mail->Username = $from; // GMAIL password $mail->Password = $gmailPass; $mail->From = $from; $mail->FromName = $from; $mail->AddReplyTo($from, $from); $mail->Subject = 'This is a test!'; $mail->Body = $text; $mail->MsgHTML($text); $mail->IsHTML(true); $mail->AddAddress($to, $to); if(!$mail->Send()){ echo $mail->ErrorInfo; }else{ echo 'sent!'; $mail->ClearAddresses(); $mail->ClearAttachments(); } ?> ``` **EDIT: just tested and works fine. Make sure that the 3 files (class.phpmailer.php, class.pop3.php and class.smtp.php) are in the correct include path**
Basically, it involves the PHP `mail()` function: ``` <?php mail(yourGmailAddress, object, message); ?> ``` As you have already observed, this solution works only if the webserver operates a mail server. This mail server may forbid unknown users. So you need to have an email account on that web/mail server (I believe this is the case). The second step then is to forward mail from your website address to you gmail account. I am 90% certain that it is possible from your gmail configuration. It may also be possible from your website mail configuration. But don't configure both!
How to get user mails in my free gmail inbox through contact us form on my website
[ "", "php", "email", "" ]
I'd thought i do a regex replace ``` Regex r = new Regex("[0-9]"); return r.Replace(sz, "#"); ``` on a file named aa514a3a.4s5 . It works exactly as i expect. It replaces all the numbers including the numbers in the ext. How do i make it NOT replace the numbers in the ext. I tried numerous regex strings but i am beginning to think that its a all or nothing pattern so i cant do this? do i need to separate the ext from the string or can i use regex?
This one does it for me: `(?<!\.[0-9a-z]*)[0-9]` This does a negative lookbehind (the string must not occur before the matched string) on a period, followed by zero or more alphanumeric characters. This ensures only numbers are matched that are not in your extension. Obviously, the [0-9a-z] must be replaced by which characters you expect in your extension.
I don't think you can do that with a single regular expression. Probably best to split the original string into base and extension; do the replace on the base; then join them back up.
Replacing numbers in strings with C#
[ "", "c#", "regex", "filenames", "" ]
What is the C# equivalent (.NET 2.0) of `_rotl` and `_rotr` from C++?
Is this what you are trying to do? [Jon Skeet answered this in another site](http://www.developmentnow.com/g/6_2004_3_0_0_71603/-rotl.htm) Basically what you want is (for left) ``` (original << bits) | (original >> (32 - bits)) ``` or (for right) ``` (original >> bits) | (original << (32 - bits)) ``` Also, as Mehrdad has already suggested, this only works for uint, which is the example that Jon gives as well.
There's no built-in language feature for bit rotation in C#, but these extension methods should do the job: ``` public static uint RotateLeft(this uint value, int count) { return (value << count) | (value >> (32 - count)) } public static uint RotateRight(this uint value, int count) { return (value >> count) | (value << (32 - count)) } ``` **Note:** As Mehrdad points out, right-shift (`>>`) for signed integers is a peculiarity: it fills the MSBs with sign bit rather than 0 as it does for unsigned numbers. I've now changed the methods to take and return `uint` (unsigned 32-bit integer) instead - this is also in greater accordance with the C++ `rotl` and `rotr` functions. If you want to rotate integers, just case them before passing, and again cast the return value, of course. Example usage: ``` int foo1 = 8.RotateRight(3); // foo1 = 1 int foo2 = int.MinValue.RotateLeft(3); // foo2 = 4 ``` (Note that `int.MinValue` is 111111111111111111111111 - 32 1s in binary.)
C# bitwise rotate left and rotate right
[ "", "c#", "bitwise-operators", "" ]
VS 2008 I am using the code below to detect if the client can connect to our SIP server. This was working fine. However, the client has changed there network and now my application has to connect to the SIP server from behind a proxy server. The error I get is the: > "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond xxx.xxx.xx.xx:xx" This code was working ok, until I have to connect from behind a proxy server. I could not see any properties there I can add the proxy address to the socket. Am I missing something? Many thanks for any suggestions, ``` public bool IsSIPServerAvailable() { bool isAvailable = true; Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { sock.Connect("xxx.xxx.xx.xx", xx); } catch (SocketException ex) { Console.WriteLine(ex.Message); isAvailable = false; } catch (Exception ex) { Console.WriteLine(ex.Message); isAvailable = false; } finally { if (sock.Connected) { sock.Close(); } } return isAvailable; } ```
See my answer [here](https://stackoverflow.com/questions/3127127/how-to-open-socket-thru-proxy-server-in-net-c/3127176#3127176), maybe it will be helpful. The general idea is to first establish connection to a proxy, and then use HTTP CONNECT command to open another TCP connection to a given host and port.
This is very similar to this [question](https://stackoverflow.com/questions/691550/c-tcpclient-proxy). I don't think it is possible to create a socket connection through a proxy server. You would need some kind of a protocol and more over, usually administrators set up proxy servers to refuse connections from ports other than standard HTTP, HTTPS. One solution would be to use tunneling over HTTP.
C# Socket: connect to server through proxy server
[ "", "c#", "networking", "proxy", "sockets", "" ]
I am using this C# code to access an image file in order to read metadata from it. ``` BitmapSource img = BitmapFrame.Create(uri); ``` Unfortunately the image file specified by `uri` becomes locked until the program ends. How do I prevent the image from being locked?
maybe [this could help](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/3cb97997-941f-42a8-a03b-f84b152c1139/) ? ***edit*** ``` BitmapSource img = BitmapFrame.Create(uri,BitmapCreateOptions.None,BitmapCacheOption.OnLoad); ``` BitmapCreateOptions.None = default option BitmapCacheOption.OnLoad = Caches the entire image into memory at load time. All requests for image data are filled from the memory store. from [here](http://msdn.microsoft.com/en-us/library/ms616004.aspx)
If you want to be able to delete/change the file immediately afterwards, read the whole file into memory, and then give it the `MemoryStream` instead. For example: ``` MemoryStream data = new MemoryStream(File.ReadAllBytes(file)); BitmapSource bitmap = BitmapFrame.Create(data); ```
.NET BitmapSource is locking file
[ "", "c#", ".net", "" ]
Duplicate of [What is the "< >" syntax within C#](https://stackoverflow.com/questions/155260/what-is-the-functionality-within-c) --- Actually i want to know 'why and when should i use generics?'. What is the need for it?
Generics are a way of ensuring Type Safety at Compile time in C#. Example- Pre-Generics: ``` class Person { string name; string lastname; public Person(string _name ) { this.name = _name; } } class ClientCode { public static void Main() { //create a list of person ArrayList personList = new ArrayList(); Person p1 = new Person("John"); Person p2 = new Person("Ram"); personList.Add(p1); personList.Add(p2); // BUT, someone can do something like: // ArrayList does not stop adding another type of object into it object q = new object(); personList.Add(q); // while accessing personlist foreach(object obj in personlist) { Person p = obj as Person; // do something, for person // But it will fail for last item in list 'q' since its is not person. } } } ``` Example- Post-Generics: ``` class ClientCode { public static void Main() { //create a list of person List<Person> personList = new List<Person>(); Person p1 = new Person("John"); Person p2 = new Person("Ram"); personList.Add(p1); personList.Add(p2); // Someone can not add any other object then Person into personlist object q = new object(); personList.Add(q); // Compile Error. // while accessing personlist, No NEED for TYPE Casting foreach(Person obj in personlist) { // do something, for person } } } ```
Generics let you parameterize code over types in the same way that arguments let you parameterize it over values. That probably doesn't explain a whole lot, so lets go through it a step at a time: Imagine you want a program to print "I like bunnies". You write this: ``` static void Main() { ILikeBunnies(); } void ILikeBunnies() { Console.WriteLine("I like bunnies"); } ``` All well and good. But you also like cheese, so now you have: ``` static void Main() { ILikeBunnies(); ILikeCheese(); } void ILikeBunnies() { Console.WriteLine("I like bunnies"); } void ILikeCheese() { Console.WriteLine("I like cheese"); } ``` You notice that your two functions are almost identical. You want to reuse the *same* function, but provide different *values* for what you like: ``` static void Main() { ILike("bunnies"); ILike("cheese"); } void ILike(string what) { Console.WriteLine("I like " + what); } ``` This is what function arguments are for: they let you reuse the same code with different values. Generics are like that, but instead of passing in different values, you pass in *types*. Lets say you've got code that needs to bundle two strings into an array: ``` static void Main() { string[] s = Pair("a", "b"); } string[] Pair(string a, string b) { return new string[] { a, b }; } ``` Fine and dandy. Later you realize you also need to bundle ints into an array: ``` static void Main() { string[] s = Pair("a", "b"); int[] i = Pair(1, 2); } string[] Pair(string a, string b) { return new string[] { a, b }; } int[] Pair(int a, int b) { return new int[] { a, b }; } ``` Just like before, we can see there's a bunch of redundancy there. What we need is a function that returns a pair of *whatever* and a way to *pass in* the type of what we want a pair of. This is what generics are for: ``` static void Main() { string[] s = Pair<string>("a", "b"); int[] i = Pair<int>(1, 2); } T[] Pair<T>(T a, T b) { return new T[] { a, b }; } ``` The angle brackets let you pass in a type to a function in the same way parentheses let you pass in values. "T" here is the name of a type argument just like "what" was the value argument above. Any place T appears in the function will be replaced with the actual type you pass in (string and int in the example). There's a bunch of stuff you can do with generics beyond this, but that's the basic idea: generics let you pass types into functions (and classes) in the same way arguments let you pass in values.
Explain Generics in layman style in C#?
[ "", "c#", "generics", "" ]
I have a .txt file like: ``` Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT |00000004| |.data __ctype_tab |00000000| r | OBJECT |00000101| |.rodata Symbols from _ashldi3.o: Name Value Class Type Size Line Section __ashldi3 |00000000| T | FUNC |00000050| |.text ``` How can i parsr this file and get the functions with type FUNC ? Also,from this txt how can i parse and extract .o name ? How can i get them by column wise parsing or else how. I need an immediate help...Waiting for an appropriate solution as usual
I think this might cost less than the use of regexes though i am not totally clear on what you are trying to accomplish ``` symbolList=[] for line in open('datafile.txt','r'): if '.o' in line: tempname=line.split()[-1][0:-2] pass if 'FUNC' not in line: pass else: symbolList.append((tempname,line.split('|')[0])) ``` I have learned from other posts it is cheaper and better to wrap up all of the data when you are reading through a file the first time. Thus if you wanted to wrap up the whole datafile in one pass then you could do the following instead ``` fullDict={} for line in open('datafile.txt','r'): if '.o' in line: tempname=line.split()[-1][0:-2] if '|' not in line: pass else: tempDict={} dataList=[dataItem.strip() for dataItem in line.strip().split('|')] name=dataList[0].strip() tempDict['Value']=dataList[1] tempDict['Class']=dataList[2] tempDict['Type']=dataList[3] tempDict['Size']=dataList[4] tempDict['Line']=dataList[5] tempDict['Section']=dataList[6] tempDict['o.name']=tempname fullDict[name]=tempDict tempDict={} ``` Then if you want the Func type you would use the following: ``` funcDict={} for record in fullDict: if fullDict[record]['Type']=='FUNC': funcDict[record]=fullDict[record] ``` Sorry for being so obsessive but I am trying to get a better handle on creating list comprehensions and I decided that this was worthy of a shot
``` for line in open('thefile.txt'): fields = line.split('|') if len(fields) < 4: continue if fields[3].trim() != 'FUNC': continue dowhateveryouwishwith(line, fields) ```
Parse a .txt file
[ "", "python", "parsing", "text-files", "" ]
``` INSERT INTO timecrunch.dbo.intervals (IntervalID, Duration) SELECT ixInterval, DATEDIFF(hour, dtStart, dtEnd) FROM fogbugz.dbo.TimeInterval WHERE dtEnd is not NULL ``` IntervalID is an int, Duration is a float I am trying to put all the hourly durations into the Duration column... I assume that even if it is less than an hour it will use a fraction which is why I put a float? Help. PS: It's running fine no errors, but after it's done the intervals table is still empty... I know the data is in the TimeInterval table though...
I'm not sure why your data is not showing up, but DATEDIFF is not going to return a float. To get a float, you'll probably want to use a smaller unit of time and divide by the number of your units per minute. Example: ``` DATEDIFF(second, dtStart, dtEnd) / (3600.0) ```
DATEDIFF returns an Int of the number of date part boundaries crossed. I would expect you to get the floor of the number of hours duration, unless there is an issue with implicit conversion from Int to Float. It is also helpful to post the error message received.
Why isn't this INSERT with DATEDIFF statement working right?
[ "", "sql", "insert", "datediff", "" ]
In ASP>Net using C#, I declared a variable as member of the class as follows: ``` public class sales: System.Web.UI.Page { string type=null; } ``` And i have an Image Button in my UI for which I've defined the event called ``` protected void ImageButton2_Click(object sender, ImageClickEventArgs e) ``` in this method, any value assigned to variable 'type'(by any other method of the class) is not retained and only value null is being retrieved though I've assigned some value to 'type' somewhere inside the class... What could be the problem that I cant access the assigned value????
This is probably a result of the render pipeline. Remember, even though your event is being fired, the page and all variables are recreated with their default value. Create it as a property with at least a backing viewstate storage. ``` public String Type { get { return ViewState["Type"].ToString(); } set { ViewState["Type"] = value; } } ```
You have to persist data between postbacks. I recommend you to read these articles: * [ASP.NET Page Life Cycle Overview](http://msdn.microsoft.com/en-us/library/ms178472.aspx) * [Understanding ASP.NET View State](http://msdn.microsoft.com/en-us/library/ms972976.aspx) * [Nine Options for Managing Persistent User State in Your ASP.NET Application](http://msdn.microsoft.com/en-us/magazine/cc300437.aspx) * [ASP.NET State Management Recommendations](http://msdn.microsoft.com/en-us/library/z1hkazw7.aspx)
Variable's value not retained in the method of a class
[ "", "c#", "asp.net", "" ]
I've inherited a legacy system with lots (160+) of stored procedures. I'm looking for a way to create a diagram that would * show which of the procedures are called by other procedures * show which part of the C# code uses which stored procedures * group the procedures by the parts of the system in which they are used Is there a tool that does this? Or would help me to perform the task?
Red Gate's [SQL Dependency Tracker](http://www.red-gate.com/products/SQL_Dependency_Tracker/index.htm) can handle your first item. As for your second item, your only real option there is doing a Find In Files (control-shift-F by default) and searching your solution for that stored procedure name. You'll have to do your own analysis as to where that string actually gets used, though. For the third, there are no tools that I'm aware of that can produce such a broad overview.
DBScribe and DOxygen may help you.
stored procedure structure
[ "", "c#", "sql-server", "sql-server-2008", "t-sql", "stored-procedures", "" ]
I am trying to debug my web app and i have realised that firebug is making it damn slow. Is there any reason for this? Are there any set of reasons like maybe long js file which cause this problem? Thank you very much. **UPDATE** Am developing a web-app which will be primarily used by developers. Now if I dont find out what exactly is making firebug make my website slow, I will have to display one of those ugly Gmail style warnings. :(
Firebug is pretty intense on the ram. Certain applications like gmail detect that firebug is opened and warn the user that they might have a slower experience than usual. Just turn it off when you don't need it. > UPDATE Am developing a web-app which > will be primarily used by developers. **EDIT**: Based on what you edited, I remembered that article concerning firebug : <http://blog.getfirebug.com/?p=124> > In the new model, if you can see > Firebug, then its active. If you can’t > it’s not. I guess the developers using your website can figure on their own that if they have firebug opened it will slow down the website, right? If not I suppose that you have no choice but detecting if FB is opened and display an error message. This chunk of code could also help : ``` if (window.console && window.console.firebug) { /* firebug found! */ } ``` There is also a way to disable some functionnalities : ``` if (! ('console' in window) || !('firebug' in console)) { var names = ['log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd']; window.console = {}; for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {}; } ``` I haven't tested it (found here : <http://davidwalsh.name/how-to-sniff-firebug-disable>) Hope that helps
Firebug is a debugger. It must inject itself into Firefox in various ways in order to provide you with information you would normally not have available to you. Use it for debugging, turn it off when you don't need it, turn off the features you don't need (network, script, console...) when you don't need them.
Why is Firebug making website slow and how to fix it?
[ "", "javascript", "firebug", "" ]
Say my javascript scripts **aren't embedded in html/xml**... I want to write a small library of helper functions to use in my scripts. Obviously there has to be an "#include" or "require" keyword in javascript, but I can't find any. Anything I could with Google relies on the code being part of html/xml, which doesn't help in my case. What should I do?
I believe you mean to write some sort of dependency tracking framework for your javascript files and use a process called "Lazy-Loading" to load the required JS file only when it's needed. Check out [Using.js](http://ajaxian.com/archives/usingjs-manage-javascript-dependencies), it seems to do what you need. Also you might want to check `addModule` from [YUILoader](http://developer.yahoo.com/yui/yuiloader/#addmodule). It allows loading non-YUI framework components on the fly.
There actually isn't a really #include or require in javascript. You're actually supposed to handle all the dependencies yourself. I've seen people do a hack where they do a document.write to include other javascript files.
How to #include in javascript?
[ "", "javascript", "" ]
I am currently developing an application that use the System.DirectoryServices namespace to create a DirectoryEntry object and loop through the entire hierarchy to collect information. I do not know number of child entries for each DirectoryEntry object in the hierarchy, so I can not create a N number of nested loops to spiders through the Children property Here is my pseudo code example: ``` //root directory DirectoryEntry root = new DirectoryEntry(path); if(DirectoryEntry.Childern != null) { foreach(DirectoryEntry child in root.Children) { //loop through each Children property unitl I reach the last sub directory } } ``` My question is, what is the best way to create a loop to collect information if you so not know the number of sub directories in your object? (This can be applied to any type of object that you do not know the object hierarchy)
Use a recursive function if you don't know the depth of the hierarchy and need to traverse down through all levels. Below is an example using depth-first traversal. ``` using (DirectoryEntry root = new DirectoryEntry(someDN)) { DoSomething(root); } function DoSomething(DirectoryEntry de) { // Do some work here against the directory entry if (de.Children != null) { foreach (DirectoryEntry child in de.Children) { using (child) { DoSomething(child); } } } } ``` Alternatively, without recursion, you can do a traversal by adding a Queue or Stack data structure and storing the objects you've seen but havent visited yet. ``` Queue<DirectoryEntry> queue = new Queue<DirectoryEntry>(); DirectoryEntry root = new DirectoryEntry(someDN); queue.Add(root); while (queue.Any()) { using (DirectoryEntry de = queue.Dequeue()) { // Do some work here against the directory entry if (de.Children != null) { foreach (DirectoryEntry child in de.Children) { queue.Enqueue(child); } } } } ```
You have to write recursive function as... ``` DirectoryEntry root = new DirectoryEntry(path); DoForEveryNode(root); void DoForEveryNode(DirectoryEntry node) { // do something.. foreach(DirectoryEntry child in node.Children) { DoForEveryNode(child); } } ```
Looping through DirectoryEntry or any object hierarchy - C#
[ "", "c#", "loops", "hierarchy", "web-crawler", "directoryservices", "" ]
No doubt some of you have seen my recent posting, all regarding the same program. I keep running into problems with it. To reiterate: still learning, not very advanced, don't understand pointers very well, not taking a class, don't understand OOP concepts at all, etc. This code just merges two sorted vectors, farray and sarray, into a single sorted vector. At least, I hope that's what it does. Tell me: ``` //int num is to find the size of the original vector and //build up farray and sarray; not used in the merge process int num = original.size() std::vector<int> final; std::vector<int>::iterator it = farray.begin(); std::vector<int>::iterator iter = sarray.begin(); //farray.size() == (0 thru (num / 2)) //sarray.size() == ((num / 2) thru num) for (;it != farray.end() && iter != sarray.end();) { if (*it > *iter) { final.push_back(*it); it++; } else { final.push_back(*iter); iter++; } if (it == farray.end()) { for (int i = 0; iter < sarray.end(); i++) { final.push_back(*iter); } } if (iter == sarray.end()) { for (int i = 0; it < farray.end(); i++) { final.push_back(*iter); } } } ``` I rewrote the merge part of my merge sort function so as to...well, make it work. I actually have several questions about this code: 1. Is it good form to compare against std::vector::iterators it && iter for my last two if statements if the for loop might change them on its next pass? 2. Will the values of iter and it change on this loop's last pass and screw up my code? Will putting my last if statements before the \*it and \*iter comparison? 3. Does the end() member function refer to the last value of whatever is calling it? It seems like it might extend past it somehow. EDIT: I will respond to all replies tomorrow, so check back then if you want to hear more. It's past midnight. G'night.
1 . It's fine to compare iterators which are from the same container as a for loop condition, but this only makes sense if you are moving one or other iterators in either the increment part if the for loop statement or in the body of the for loop itself. In this for loop you compare `iter` against `sarray.end()` but the for loop never changes `iter`. This means that either there will be no iterations or the for loop will never terminate. Also, you probably want to use `!=` and not `<` for the comparison. `==` and `!=` work for all iterators, `<` doesn't. ``` for (int i = 0; iter != sarray.end(); i++) { final.push_back(*iter); } ``` As `iter` starts where you want the loop to begin, you may want something like this: ``` for (; iter != sarray.end(); ++iter) { final.push_back(*iter); } ``` As you're still learning (although aren't we all!), it's probably instructive to work through an algorithm like this, but you should be aware of `std::merge` which probably does what you want. ``` std::merge( farray.begin(), farray.end(), sarray.begin(), sarray.end(), std::back_inserter( final ) ); ``` (You need to `#include <iterator>` and `<algorithm>`.) 2 . I don't see incrementing iter or it in the outer for loop invalidating the logic in the later for loops, the point in 1. aside. 3 . `end()` points to one past the end of a container, so you can use it for loop termination checks, but you shouldn't try to dereference an iterator which is "`==`" to "`.end()`".
I didn't check your algorithm's implementation, I will just refer to your three questions: 1. Iterators are much like pointers to values of a container. It's exactly like using size\_t i and then ++i in the for loop. would you feel it's problematic to compare farray[i] with sarray[i]? probably not, therefore it's OK. 2. What I see you doing in your code here, is that you just read the values of \*it and \*iter, you don't actually change them, therefore they won't change. 3. The end() points to an invalid place. It doesn't point to the last value, but to "after it". It's like "NULL" if you will, therefore if(iter == sarray.end()) is true, you will crash if you will write \*iter, because you can't dereference an iterator which is equal to end().
Is it good form to compare against changing values in a loop in C++?
[ "", "c++", "merge", "vector", "coding-style", "member-functions", "" ]
The sentence below is from, **[The Positive Legacy of C++ and Java](http://www.artima.com/weblogs/viewpost.jsp?thread=252441)** by Bruce Eckel, about operator overloading in C++: > C++ has both stack allocation and heap > allocation and you must overload your > operators to handle all situations and > not cause memory leaks. Difficult > indeed. I do not understand how operator overloading has anything to do with memory allocation. Can anyone please explain how they are correlated?
I can imagine a couple possible interpretations: First, in C++ `new` and `delete` are both actually operators; if you choose to provide custom allocation behavior for an object by overloading these operators, you must be very careful in doing so to ensure you don't introduce leaks. Second, some types of objects require that you overload `operator=` to avoid memory management bugs. For example, if you have a reference counting smart pointer object (like the Boost shared\_ptr), you must implement `operator=`, and you must be sure to do so correctly. Consider this broken example: ``` template <class T> class RefCountedPtr { public: RefCountedPtr(T *data) : mData(data) { mData->incrRefCount(); } ~RefCountedPtr() { mData->decrRefCount(); } RefCountedPtr<T>& operator=(const RefCountedPtr<T>& other) { mData = other.mData; return *this; } ... protected: T *mData; }; ``` The `operator=` implementation here is broken because it doesn't manage the reference counts on `mData` and `other.mData`: it does not decrement the reference count on `mData`, leading to a leak; and it does not increment the reference count on `other.mData`, leading to a possible memory fault down the road because the object being pointed to could be deleted before all the actual references are gone. Note that if you do not explicitly declare your own `operator=` for your classes, the compiler will provide a default implementation which has behavior identical to the implementation shown here -- that is, completely broken for this particular case. So as the article says -- in some cases you must overload operators, and you must be careful to handle all situations correctly. **EDIT**: Sorry, I didn't realize that the reference was an online article, rather than a book. Even after reading the full article it's not clear what was intended, but I think Eckel was probably referring to situations like the second one I described above.
new and delete are actually operators in C++ which you can override to provide your own customized memory management. Take a look at the [example](http://www.relisoft.com/book/tech/9new.html) here.
Operator overloading with memory allocation?
[ "", "c++", "memory-leaks", "operator-overloading", "" ]