Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm working on code that does nearest-neighbor queries. There are two simple ideas that underlie how a user might query for data in a search: * closest N points to a given point in space. * all points within a given distance. In my code, Points are put into a PointList, and the PointList is a container has the job of keeping track of the points that have been found in the search. Right now my PointList object has one constructor: ``` PointList( unsigned int maxvals ); // #1 ``` The next two constructors that I'd like to add are these: ``` PointList( float maxdist ); // #2 PointList( unsigned int maxvals, float maxdist ); // #3 ``` My question is: how do I ensure that my users and the C++ compiler will generate the right constructor for the PointList and differentiates between constructors 1 and 2? Should I just implement #3 and provide constants that define arbitrary large values for maxvals and maxdist? Another alternative might be to write another system of lightweight objects that govern the logic for adding Points to the list, but that feels like overkill for such a simple idea. I'm really trying to make this transparent for my users, who are mostly scientists who have learned C++ sometimes without the benefit of formal education. Thanks!
Overload resolution for integer types happen on two categories, which can be very roughly summarized to * Promotion: This is a conversion from types smaller than `int` to `int` or `unsigned int`, depending on whether `int` can store all the values of the source type. * Conversion: This is a conversion from any integer type to another integer type. Similar, conversion for floating point types happen on two categories * Promotion: This is a conversion from `float` to `double` * Conversion: This is a conversion from any floating point type to another floating point type And there is a conversion from integer to floating or back. This is ranked as a conversion, rather than a promotion. A promotion is ranked better than a conversion, and where only a promotion is needed, that case will be preferred. Thus, you can use the following constructors ``` PointList( int maxVals ); PointList( unsigned int maxVals ); PointList( long maxVals ); PointList( unsigned long maxVals ); PointList( double maxDist ); PointList( long double maxDist ); ``` For any integer type, this should select the first group of constructor. And for any floating point type, this should select the second group of constructors. Your original two constructors could easily result in an ambiguity between `float` and `unsigned int`, if you pass an `int`, for example. For the other, two argument constructor, you can go with your solution, if you want. --- That said, i would use a factory function too, because deciding on the type the meaning of the parameter is quite fragile i think. Most people would expect the following result to equal ``` PointList p(floor(1.5)); PointList u((int)1.5); ``` But it would result in a different state of affairs.
Why not use factory methods instead of constructors? Factory methods have the advantage of customizable names. ``` static PointList createNearestValues(unsigned int maxvals) {} static PointList createByDistance(float maxdist) {} ```
Managing Implicit Type Conversion in C++
[ "", "c++", "c", "type-conversion", "" ]
I am using a xml web service on my web app and sometimes remote server fails to respond in time. I came up with the idea of re-request if first attempt fails. To prevent loop I want to limit concurrent request at 2. I want to get an opinion if what I have done below is ok and would work as I expect it. ``` public class ScEngine { private int _attemptcount = 0; public int attemptcount { get { return _attemptcount; } set { _attemptcount = value; } } public DataSet GetStat(string q, string job) { try { //snip.... attemptcount += attemptcount; return ds; } catch { if (attemptcount>=2) { return null; } else { return GetStat(q, job); } } } } ```
``` public class ScEngine { public DataSet GetStat(string q, string job) { int attemptCount; while(attemptCount < 2) { try { attemptCount++; var ds = ...//web service call return ds; } catch {} } //log the error return null; } } ```
You forgot to increment the attemptcount. Plus, if there's any error on the second run, it will not be caught (thus, becomes an unhandled exception).
Retry the request if the first one failed
[ "", "c#", "web-services", "" ]
I have been reading the docs and playing with different EventQuery parameters for days now. I am using C# .NET with google's .net api to get the events from a public calendar I set up. I can get the events from the api just fine but I can't get it to give me the next upcoming events by date. My calendar has mixed recurrence events with one-shot events. I have read stuff on the internet to use direct query parameter strings in the request uri but doesn't seem to work right when using it in the .net api structure. Here is what I have currently as my base: ``` CalendarService myService = new CalendarService("testGoogleCalendar-1"); EventQuery myQuery = new EventQuery(); myQuery.Uri = new Uri(CalendarURI); myQuery.NumberToRetrieve = NumberOfEvents; EventFeed calFeed = myService.Query(myQuery); foreach (AtomEntry entry in calFeed.Entries) { LiteralControl test = new LiteralControl("<p><b>" + entry.Title.Text + "</b></p>"); this.Controls.Add(test); } ``` I have tried playing with the EventQuery's members StartDate, StartTime, EndTime, SortOrder, FutureEvents and even tried adding "?orderby=starttime" to the CalendarURI local member. The api query's seems to return the order of published date of the event which is when I created the event in the calendar not when the event is going to take place. I have also been trying to get just the date and time of the event from the AtomEntry object so I can sort it myself and format it with the title in my control but the only place I see it is in AtomEntry's Content.Content which also has other stuff I don't really want. Is there a DateTime member to AtomEntry for this so I can just get the date? This one has really got me confused right now so any help is appreciated.
I haven't used the GData calendar API from .NET, but I'm pretty familiar with it in Java. The start time of an event will depend on the type of an event. A recurrent event doesn't have any start times as such, but a "single" event may actually have multiple times. These are stored as `<gd:when>` elements - that's what you need to look for. It does look like `orderby=starttime` really *should* work though. It may be worth using WireShark or something similar to see the exact query going out and the exact results coming back, to check it's not something in the API causing problems - in particular, it could be that using that in the Uri property isn't supported for some reason... EDIT: Have you tried setting ``` query.ExtraParameters = "orderby=starttime"; ``` ? That's probably the safest way of getting it into the final query uri...
``` myQuery.ExtraParameters = "orderby=starttime&sortorder=ascending"; ``` Works like a charm!
.NET Google Calendar API Sort Events by Date
[ "", "c#", "asp.net", ".net", "google-calendar-api", "" ]
Let's say I have two tables, users and notes. Let's say the schemas look like this: ``` users id, name, field2, field3 notes id, user_id, subject, heading, body, timestamp ``` What I want to do is select every user, and the LATEST (just 1) note posted by each user based on the timestamp to show in an overview report. How would I go about doing this? Please note that the DB is MySQL. Thanks!
``` select users.name, notes.subject, notes.heading, notes.body from users, notes where users.id = notes.user_id and notes.timestamp = (select max(timestamp) from notes where user_id = users.id) ```
``` select u.id, u.name, n.id as note_id, n.subject, n.heading, n.body, n.timestamp from users u left outer join ( select user_id, max(timestamp) as timestamp from notes group by user_id ) nm left outer join notes n on nm.user_id = n.user_id and nm.timestamp = n.timestamp ``` Note that this could potentially return duplicates if the user has two notes with the exact same timestamp. I have assumed this is not the case.
Retrieving the latest note (by timestamp) in a single query from a 1:n table
[ "", "php", "mysql", "database", "" ]
I need a class that works like this: ``` >>> a=Foo() >>> b=Foo() >>> c=Foo() >>> c.i 3 ``` Here is my try: ``` class Foo(object): i = 0 def __init__(self): Foo.i += 1 ``` It works as required, but I wonder if there is a more pythonic way to do it.
Nope. That's pretty good. From The Zen of Python: "Simple is better than complex." That works fine and is clear on what you're doing, don't complicate it. Maybe name it `counter` or something, but other than that you're good to go as far as pythonic goes.
Abuse of decorators and metaclasses. ``` def counting(cls): class MetaClass(getattr(cls, '__class__', type)): __counter = 0 def __new__(meta, name, bases, attrs): old_init = attrs.get('__init__') def __init__(*args, **kwargs): MetaClass.__counter += 1 if old_init: return old_init(*args, **kwargs) @classmethod def get_counter(cls): return MetaClass.__counter new_attrs = dict(attrs) new_attrs.update({'__init__': __init__, 'get_counter': get_counter}) return super(MetaClass, meta).__new__(meta, name, bases, new_attrs) return MetaClass(cls.__name__, cls.__bases__, cls.__dict__) @counting class Foo(object): pass class Bar(Foo): pass print Foo.get_counter() # ==> 0 print Foo().get_counter() # ==> 1 print Bar.get_counter() # ==> 1 print Bar().get_counter() # ==> 2 print Foo.get_counter() # ==> 2 print Foo().get_counter() # ==> 3 ``` You can tell it's Pythonic by the frequent use of double underscored names. (Kidding, kidding...)
I need a Python class that keep tracks of how many times it is instantiated
[ "", "python", "class", "instances", "" ]
I have a method ... where I can't find the error: ``` public String getUsernameforID(int id) { String statment = "SELECT USERNAME FROM `BENUTZER` WHERE `ID` = ? ;"; String username = null; try { PreparedStatement ps = dbCommunicator.getStatment(statment); // HERE : NULL POINTER EXECTION ps.setInt(1, id); ResultSet rs = dbCommunicator.readFromDB(ps); if (rs.first()) { username = rs.getString("USERNAME"); } } catch (SQLException ex) { Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex); } return username; ``` I think it's the statement ... but how can I find this out? I get a Null Pointer Exeption. Edit : my getStatment-method: ``` public PreparedStatement getStatment(String st) { connect(); PreparedStatement ps = null; try { ps = (PreparedStatement) connection.prepareStatement(st); } catch (SQLException ex) { Logger.getLogger(DBCommunicator.class.getName()).log(Level.SEVERE, null, ex); } return ps; } ``` The Exception: ``` Exception in thread "main" java.lang.NullPointerException at test.DBCommunicator.getStatment(DBCommunicator.java:107) at test.database.DBManager.getUsernameforID(DBManager.java:359) at dbtestdrive.Main.main(Main.java:25) ```
Although this question may have been solved, here's a little bit on how to go about debugging given an stack trace. In this case, the stack trace is the following: ``` Exception in thread "main" java.lang.NullPointerException at test.DBCommunicator.getStatment(DBCommunicator.java:107) at test.database.DBManager.getUsernameforID(DBManager.java:359) at dbtestdrive.Main.main(Main.java:25) ``` What this shows is that in the `test.DBCommunicator.getStatment` method, a `NullPointerException` was thrown at the location of line 107 of `DBCommunicator.java`. Furthermore, the `getStatment` method was called from line 358 of `DBManager.java` which is in the `DBManager.getUsernameforID` method. Therefore, the first place that should be checked is what is going on at line 107 of `DBCommunicator.java`. Although there are no line numbers in the code snippet given, one can presume that a `NullPointerException` occurred in the following line: ``` ps = (PreparedStatement) connection.prepareStatement(st); ``` There's one thing that is fairly common about `NullPointerException`s -- they generally arise when method calls are performed on an `null` reference. Invoking a method on an object that doesn't exist will throw a `NullPointerException`. In the above code, one can expect that the `connection` variable is actually `null`, rather than having a `Connection`. This should lead to trying to track down why the `connection` variable is `null` rather than having a valid connection to the database that is initialized.
It is probably because your query is failing, try changing it to: ``` String statment = "SELECT USERNAME FROM `BENUTZER` WHERE `ID` = ?"; ``` Your original query had a trailing semi-colon, which is illegal. This could have caused a nullpointerexception to be thrown up at a later stage, I would advise you to post the contents of your exception. EDIT: ``` dbCommunicator.getStatment(statment); ``` Should be: ``` dbCommunicator.getStatement(statment); ``` You're misspelling 'statement' as 'statment', which is fine for a variable name, but not when referring to a method :)
Why am I getting a Null Pointer Exception from this Java code?
[ "", "java", "jdbc", "" ]
The Javadoc about [`String.intern()`](http://java.sun.com/javase/6/docs/api/java/lang/String.html#intern()) doesn't give much detail. (In a nutshell: It returns a canonical representation of the string, allowing interned strings to be compared using `==`) * When would I use this function in favor to `String.equals()`? * Are there side effects not mentioned in the Javadoc, i.e. more or less optimization by the JIT compiler? * Are there further uses of `String.intern()`?
> When would I use this function in favor to String.equals() when you need **speed** since you can compare strings by reference (== is faster than equals) > Are there side effects not mentioned in the Javadoc? The primary disadvantage is that you have to remember to make sure that you actually do intern() all of the strings that you're going to compare. It's easy to forget to intern() all strings and then you can get confusingly incorrect results. Also, for everyone's sake, please be sure to very clearly document that you're relying on the strings being internalized. The second disadvantage if you decide to internalize strings is that the intern() method is relatively expensive. It has to manage the pool of unique strings so it does a fair bit of work (even if the string has already been internalized). So, be careful in your code design so that you e.g., intern() all appropriate strings on input so you don't have to worry about it anymore. (from JGuru) Third disadvantage (Java 7 or less only): interned Strings live in PermGen space, which is usually quite small; you may run into an OutOfMemoryError with plenty of free heap space. (from Michael Borgwardt)
This has (almost) nothing to do with string comparison. [String interning](http://en.wikipedia.org/wiki/String_interning) is intended for saving memory if you have many strings with the same content in you application. By using `String.intern()` the application will only have one instance in the long run and a side effect is that you can perform fast reference equality comparison instead of ordinary string comparison (but this is usually not advisable because it is realy easy to break by forgetting to intern only a single instance).
Is it good practice to use java.lang.String.intern()?
[ "", "java", "string", "" ]
I' trying to use *window.pageYOffset* & *window.scrollMaxY* to calculate the current page progress. This approach works under FF3.5 but under webkit *window.scrollMaxY* is undefined.
I've got away with `document.body.scrollHeight` so that ``` document.body.scrollHeight = window.pageYOffset + screen height in pixels ``` at the end of the page (on Android).
Alternative to `window.scrollMaxY`: ``` document.documentElement.scrollHeight - document.documentElement.clientHeight ``` gives same result as `window.scrollMaxY` with ie7, ie8, ff3.5, Safari 4, Opera 10, Google Chrome 3 under DOCTYPE XHTML 1.0 Transitional.
Alternatives to window.scrollMaxY?
[ "", "javascript", "android", "webkit", "" ]
Here's a [sample page](http://jsbin.com/omoya) with a couple datepickers. Here's the Drip result for that: [alt text http://www.picvault.info/images/537090308\_omoya.png](http://www.picvault.info/images/537090308_omoya.png) This page leaks indefinitely in IE6sp1 when I click the Refresh button repeatedly (IE6sp3+, Opera 9, Chrome2, and FF3+ seem to be good). The memory goes up and never goes down until I actually close the browser completely. I've also tried using the latest nightly of jquery (r6414) and the latest stable UI (1.7.2) but it didn't make any difference. I've tried various things with no success ([CollectGarbage](http://www.mail-archive.com/jquery-dev@googlegroups.com/msg03851.html), [AntiLeak](http://groups.google.com/group/jquery-ui/browse_thread/thread/d0093cf0199e26b4/acd3cecae3f5b055?hl=en&lnk=gst&q=dialog+memory+leak#acd3cecae3f5b055), others). I'm looking for a solution other than "use a different browser!!1" as I don't have any control over that. Any help will be greatly appreciated! **Update 1:** I added that button event to a loop and this is what happens (the sudden drop off is when I terminate IE): ![alt text](https://i.stack.imgur.com/6pmp5.png) **Update 2:** I filed a [bug report](http://dev.jqueryui.com/ticket/4644) (fingers crossed). **Update 3:** This is also on the [mailing list](http://groups.google.com/group/jquery-dev/browse_thread/thread/861282378f94a37e). **Update 4:** This (as reported on the mailing list) doesn't work, and in fact makes things worse: ``` $(window).bind("unload", function() { $('.hasDatepicker').datepicker('destroy'); $(window).unbind(); }); ``` It's not enough to just call destroy. I'm still stranded with this one and getting very close to ripping jquery out of the project. I love it (I really do!) but if it's broken, I can't use it. **Update 5:** Starting the bounty, another 550 points to one helpful individual! **Update 6:** Some more testing has shown that this leak exists in IE6 and IE6sp1, but has been fixed in IE6sp2+. Now, about the answers I have so far... So far all answers have been any one of these: 1. Abandon IE6sp0/sp1 users or ignore them 2. Debug jquery and fix the problem myself 3. I can't repro the problem. I know beggars can't be choosers, but those simply are not answers to my problem. I cannot abandon my users. They make up 25% of the userbase. This is a custom app written for a customer, designed to work on IE6. *It is not an option to abandon IE6sp0/sp1.* It's not an option to tell my customers to just deal with it. It leaks so fast that after five minutes, some of the weaker machines are unusable. Further, while I'd love to become a JS ninja so I can hunt down obscure memory leaks in jquery code (granted this is MS's fault, not jquery's), I don't see that happening either. Finally, multiple people have reproduced the problem here and on the mailing list. If you can't repro it, you might have IE6SP2+, or you might not be refreshing enough. Obviously this issue is very important to me (hence the 6 revisions, bounty, etc.) so I'm open to new ideas, but please keep in mind that none of those three suggestions will work for me. Thanks to all for your consideration and insights. Please keep them coming! **Update 7:** The bounty has ended and Keith's answer was auto-accepted by SO. I'm sorry that only half the points were awarded (since I didn't select the answer myself), but I'm still really stuck so I think half is fair. I am hopeful that the jquery/jquery-ui team can fix this problem but I'm afraid that I'll have to write this off as "impossible (for now)" and stop using some or all of jquery. Thanks to everyone for your help and consideration. If someone comes along with a real solution to my problem, please post and I'll figure out some way to reward you.
I hate to say this, your approach is correct and professional, but I'd be tempted to just leave it. The consequences of not fixing this is that IE6 users will notice their machine getting slower and slower and ultimately either crashing completely or more likely crashing IE6. So what? Really - *why is this your problem?* Yours definitely won't be the only site they visit with this leak, and they will see IE6 crash regularly regardless of what you do, because that's what it does. It's unlikely that anyone still on IE6 could even point out your application as one that leaks. Finally when IE6 does crash it reports IE6 as the culprit - you can legitimately point out that this is a bug in IE6 that Microsoft have fixed in a new release. Your expensive time is better spent on improving the application for the users not trapped in legacy hell - your app should basically work for IE6 users, but this sort of issue can suck away all of your time and not fix their problem. IE6 is still going to be an unsupported, crash ridden, security hole of a browser. I suspect the jQuery devs take a similar view to me. Also you have to do some really ugly stuff to get round this bug in IE6, including hacky DOM work that stops the leak but is actually much slower. --- **Update** Ok, this isn't an easy problem to fix - MS describe the IE6 bug (and provide advice on how to fix it) here: <http://msdn.microsoft.com/en-us/library/bb250448(VS.85).aspx> Basically this isn't a problem with javascript or jQuery - the actual issue is with the IE6 DOM - when HTML elements are added to the page (by javascript, rather than being in the page when it loads) IE can't garbage collect them unless they are created in a very specific way. This is back to front from how jQuery UI builds elements (see DOM insertion order bug in the link above) and so this isn't something that either the jQuery devs or you can easily fix. So how do you fix the issue? Well, you can stick with the legacy pop-up calendar for IE6 or you can write your own one. I would recommend the former, but if you really want to built the latter there are some basic rules to follow: 1. Always add elements top-down - for instance if you want to built a table add the `<table>` element into the page's DOM, then add `<tr>` then `<td>` and so on. This is back to front as it's much quicker to build the entire table and then add it to the DOM - unfortunately that's where IE6 loses track of it. 2. Only use CSS and HTML 3.2 attributes - sounds dumb, but IE6 creates extra objects to store the extra attributes (or 'expando' properties) and these also leak. 3. Kinda related to (2), but as @gradbot mentions IE6 has problems garbage collecting javascript variables - if they reference a DOM element inside an event fired from that element you can get problems. This is also compounded by javascript references to DOM elements that have 'expando' properties. If you have a look around online there may already be a drop-down DHTML calendar that sticks to these rules - it won't be as pretty, quick or configurable as the jQuery UI one, but I'm sure I've seen it done without leaking in IE6. I think the best bet is to keep as much static as possible - for instance you could load the calendar grid (week numbers and day column headings) with the page and then dynamically load in the numbers (and nothing else). Create the day numbers as links, with javascript in the href - not best practice normally but far less likely to leak in IE6.
It's obvious that the problems you've been describing stem from a flaw in IE6 that you can't subvert with a software fix (be it a jQuery update, a manual call to CollectGarbage, or some other JavaScript/DOM hack). There are 3 options, in my mind, that would fix this problem. 1. I would imagine that your customers/users are using IE6 SP0 because of some company standard or regulation, or even because some older web-app they still use doesn't support newer browsers. If it's not an option to upgrade to IE7 (or therefore IE8), you could get in contact with your customers' IT department and politely point out that updating IE6 with the latest service packs would not only fix a problem with an application that they are paying for, but also patch many security and performance flaws that undoubtedly exist in IE6 SP0. Admittedly, that might not be a comfortable situation, but it might solve the problems you are encountering, while still allowing them to work with a browser that require for whatever reason. 2. If you can convince your customers' IT department that IE6 is antiquated, they may be willing to allow your users to upgrade to a newer browser. It's not a stretch to say that someone running an IT department would be more willing to force employees to upgrade a piece of software if they knew it was either a) riddled with flaws and security holes or b) approaching its end of support date (as IE6 SP0 is). IE6 SP0 on XP Pro SP2 is supported until July 13, 2010 - so it still has some time, but pointing that out, along with other flaws/limitations you could find might make them think seriously about upgrading sooner rather than later. 3. If you can't convince anyone to upgrade their browsers either to IE6 SPX, or to IE7/8, then I don't know if you have a choice but to remove the offending control from your page, and pursue a different option until the user's browser permits it. There are assuredly many implementations of a date picker control available online which would suit your needs. It might not be as snazzy as the jQuery version, but you don't have many other options at this point. I hope you find a solution!
How can I control IE6+jQuery+jQuery-ui memory leaks?
[ "", "javascript", "jquery", "jquery-ui", "memory-leaks", "internet-explorer-6", "" ]
I have a DetailsView with a number of textboxes setup with RequiredFieldValidators. The code for both is: ``` <InsertItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("date_time") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ControlToValidate="TextBox1" ErrorMessage="Please update date_time." ValidationGroup="InsertDetailsView1">*</asp:RequiredFieldValidator> </InsertItemTemplate> ``` The problem is that the validation control is now creating a space (ie ) between the textbox and the one below it. How do I get rid of the space? Is it a CSS thing? [![alt text](https://i.stack.imgur.com/wiMA5.jpg)](https://i.stack.imgur.com/wiMA5.jpg)
Set this property: `Display="Dynamic"`.
You can set Display="Dynamic" and the message will only show up when the error occurs.
ASP .NET - RequiredFieldValidator creates space after textbox
[ "", "c#", "asp.net", "" ]
How can I make sure in the following code snippet that `IDataReader` is disposed of if `ExecuteReader` throws an exception? ``` using (IDataReader rdr = cmd.ExecuteReader()) { // use it } ``` It makes sense to me that the `using` syntatic sugar does not call Dispose (since there is no instance to call it on). However, how can I be sure that the scarce resources that are normally allocated by classes that implement IDisposable will be releases?
If ExecuteReader, in your example, throws an exception it never returns anything. It is then up to the implementation of ExecuteReader to dispose of anything created before the exception.
If the constructor of an object fails to run then you do not have an object that needs to be disposed. If you are writing a constructor which could throw an exception, you had better make sure you clean up anything you need to by using `using` or try-catch block. In your IDataReader example, it is sufficient to simply dispose of the command object if the `cmd.ExecuteReader()` method call fails.
How do I dispose an IDisposable object if the using statement throws an exception?
[ "", "c#", "exception", "dispose", "idisposable", "" ]
I need to get up to speed with C++ quite quickly (I've never used it previously) - is learning through Visual Studio (i.e. Managed C++) going to be any use? Or will I end up learning the extensions and idiosyncracies of C++ in VS, rather then the language itself? If learning in VS is not recommended, what platform / IDE do you guys suggest? **Edit:** Can anyone elaborate on what VS will hide or manage for me when coding unmanaged C++? I really need to be learning things like pointers, garbage collection and all the nuts and bolts of the low level language.. does VS abstract or hide any of this kind of stuff from you? Thanks for all the suggestions..
Visual Studio (or the free version, Visual C++ Express) is a perfectly fine choice on Windows. On Linux, you'll probably end up using GCC. Both are fine compilers. Visual C++ supports both "real" native C++ and C++/CLI, the managed .NET version, so if you want to learn C++, simply create a regular C++ project. If you're concerned with learning "proper" standard C++, note that the compiler by default enables a number of Microsoft extensions, which you may want to disable. (Project properties -> C/C++ -> Language -> Disable Language Extensions). For the record, GCC has similar extensions (which can be disabled by calling the compiler with --ansi), so this isn't just Microsoft being big and evil and nonstandard. ;)
Visual Studio has a **very good debugger**. It has support for STL types (version 2008 is better) which will help you while debugging. Visual Studio insists with the Microsoft specifics from the very first console project you make (New->Project->Win32 Console Application) ``` // test123.cpp : Defines the entry point for the console application. // #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; } ``` What is stdafx.h? What is \_tmain? What is \_TCHAR? (BTW no need to answer them here) These are question which should not appear in the head of a novice. That's why I suggest to use the "Empty project" checkbox in the Win32 Console Application project and then "Add new item" from Project menu and choose a cpp file which will give you a blank page where you can implement the code you read from a good C++ book.
Learning C++ from scratch in Visual Studio?
[ "", "c++", "visual-studio", "managed-c++", "" ]
> "The major difference between a thing > that might go wrong and a thing that > cannot possibly go wrong is that when > a thing that cannot possibly go wrong > goes wrong it usually turns out to be > impossible to get at or repair." > -Douglas Adams I have an class FileItems. FileItems constructor takes a file, and throws an exception (FileNotFoundException) if the file doesn't exist. Other methods of that class also involve file operations and thus have the ability throw the FileNotFoundException. I would like to find a better solution. A solution which doesn't require that other programmers handle all of these extremely unlikely FileNotFoundExceptions. The facts of the matter: 1. The file has been checked to exist but the extremely unlikely possibility exists that through some major fault of reality the file might be deleted before this method is called. 2. Since the probability of 1 happening is extremely unlike and unrecoverable, I would prefer to define an unchecked exception. 3. The file is has already been found to exist, forcing other programmers to write code and catch the checked FileNotFoundException seems tedious and useless. The program should just fail completely at that point. For example there is always the chance that a computer may [catch fire, but no one is insane enough to force other programmers to handle that as a checked exception](http://en.wikipedia.org/wiki/Lp0_on_fire). 4. I run into this sort of Exception issue from time to time, and defining custom unchecked exceptions each time I encounter this problem (my old solution) is tiresome and adds to code-bloat. The code currently looks like this ``` public Iterator getFileItemsIterator() { try{ Scanner sc = new Scanner(this.fileWhichIsKnowToExist); return new specialFileItemsIterator(sc); } catch (FileNotFoundException e){ //can never happen} return null; } ``` How can I do this better, without defining a custom unchecked FileNotFoundException? Is there some way to cast a checkedException to an uncheckException?
The usual pattern to deal with this is [exception chaining](http://en.wikipedia.org/wiki/Exception_chaining). You just wrap the FileNotFoundException in a RuntimeException: ``` catch(FileNotFoundException e) { throw new RuntimeException(e); } ``` This pattern is not only applicable when an Exception cannot occur in the specific situation (such as yours), but also when you have no means or intention to really handle the exception (such as a database link failure). **Edit**: Beware of this similar-looking anti-pattern, which I have seen in the wild far too often: ``` catch(FileNotFoundException e) { throw new RuntimeException(e.getMessage()); } ``` By doing this, you throw away all the important information in the original stacktrace, which will often make problems difficult to track down. **Another edit:** As Thorbjørn Ravn Andersen correctly points out in his response, it doesn't hurt to state why you're chaining the exception, either in a comment or, even better, as the exception message: ``` catch(FileNotFoundException e) { throw new RuntimeException( "This should never happen, I know this file exists", e); } ```
Consider using the form ``` throw new RuntimeException("This should never happen", e); ``` instead. This allows you to convey meaning to the maintainer to follow you, both when reading the code but also SHOULD the exception happen to be thrown in some strange scenario. EDIT: This is also a good way to pass exceptions through a mechanism not expecting those exceptions. E.g. if you have a "get more rows from the database" iterator the Iterator interface does not allow to throw e.g. an FileNotFoundException so you can wrap it like this. In the code USING the iterator, you can then catch the runtimeexception and inspect the original excpetion with getCause(). VERY useful when going through legacy code paths.
How can I handle an IOException which I know can never be thrown, in a safe and readable manner?
[ "", "java", "exception", "ioexception", "" ]
I was recently reading about all the JVM arguments available in JRE 6 [[Java VM Options](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp)] and saw this : > -XX:+StringCache : Enables caching of commonly allocated strings. Now I was always under the impression that Java kept a pool of interned (correct word?) Strings and when doing something like String concatenation with literals it was not creating new objects, but pulling them from this pool. Has anyone ever used this argument, or can explain why it would be needed? **EDIT:** I attempted to run a benchmark, to see if this argument had any effect and was unable to get the Sun JVM to recognize it. This was with: ``` java version "1.6.0_11" Java(TM) SE Runtime Environment (build 1.6.0_11-b03) Java HotSpot(TM) Client VM (build 11.0-b16, mixed mode, sharing) ``` So I'm not sure if this argument works at all.
I have not been able to find a single JVM that even accepts this supposed argument - so I guess there's not much else to say.
I believe when used with `-XX:+AggressiveOpts` it enables the same `String` objects to be returned when creating the `String` with the same text (though not through `new String`, of course). There is a profile phase where a cache is build up, and after a point the cache is switched to read only. It gets higher scores in certain benchmarks.
JVM -XX:+StringCache argument?
[ "", "java", "jvm", "jvm-hotspot", "jvm-arguments", "" ]
I have a wcf serivce I want to consume from a j2me application (blackberry). I have been going crazy since the tools that work fine for the j2SE used for consuming web services do not work all that well for j2me. At least not with my service. I found a useful tutorial at <http://www.netbeans.org/kb/60/mobility/mobile-dilbert.html> While it uses an old asmx service style to explain it. I was able to follow the steps and use my wcf reference and I was able to make the connection. The drawback, this solution uses a j2ee proxy to get the reference to work. Is this the way to solve the incompatibilities between .net and java? I read that a big reason why this happens is that Microsoft generates non-standard wsdl files for services. My question is: is this the solution generally used for consuming .net web services from java, or is there a better way? Any reference pointers will be greatly appreciated.
Thank you to the two people who answered, gave me things to think about when doing additional research. Since there was no definite answer on this question, perhaps I was not clear, and after looking into the subject from other sources. I decided to post what I had discovered. Looking at the most basic WCF service, one that has one method, returns a string. No other methods in place. Got the errors while adding the reference. JSR-172 does not understand guids (the idea of the message not the actual message). Same thing for char and duration. I read about it further and found references on microsoft non standard wsdl files, and that by implementing some interfaces you could remove all non standard schema references from the generated wsdl file. This helped for a simple service not a complex one. I tried an existing service, I decided to use the amazon.com affiliate services to test things. Similar error as with my wcf service, it gave a whole list of types it did not like. In the end I learned. Visual studio spoils you and makes you lazy(not always a bad thing). I wanted a way to use some sort of wizard type tool, input a reference and get lots of generated code that calls my service, gives my objects to deal with and methods to call. Netbeans did this for me for J2SE not for j2me. If you want to use WCF directly for a j2me project, be ready to write all the plumbing code for it. Alternatively you can use the suggested method of using j2ee proxy. As explained in <http://www.netbeans.org/kb/60/mobility/mobile-dilbert.html> With this method you still need to be careful what data types you use. As some cause the service to fail or be unusable. Example, i had a method return a datetime, netbeans would not even let me select that method for stub generation. and calling methods in the service with that one present caused exceptions to be thrown. (method removed and calls succeeded)
Firstly, did you configure the WCF service to use basicHttpBinding? Secondly, use only native data types (strings, int, bool, etc.) in the data contract. Don't use .NET objects like DateTime etc. This is what I did when I had to develop a MIDLet twitter app that calls a WCF service to get friend updates, post tweets etc... Oh and I also used Wireless Toolkit (v 2.5.2) stubgenerator to create the client. It didn't have any problem creating the client even if the WCF's wsdl had external imports (wsdl:import and xsd:import)
Adding a WCF reference to a j2me project
[ "", "java", "wcf", "java-me", "" ]
How can I get output from Java anonymous classes? In .Net I would use closures. ``` executor = Executors.newSingleThreadExecutor(); final Runnable runnable = new Runnable() { public Exception exception; @Override public void run() { try { doSomething(); } catch (Exception exception) { // I'd like to report this exception, but how? // the exception member is not readable from outside the class (without reflection...) this.exception = exception; } } }; executor.submit(runnable); // Here I'd like to check if there was an exception ```
The `Executor` interface offers no way to do this. However, when you call `newSingleThreadExecutor()` you will get an `ExecutorService` which contains functionality for that. Calling `ExecutorService.submit()` returns an instance of [`Future<?>`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/Future.html), which you can use to get the result value of the computation. If the execution resulted in an exception, calling `get` will cause an `ExecutionException` to be thrown.
To obtain an exception from a task run on an executor you want to use [Callable](http://java.sun.com/javase/6/docs/api/java/util/concurrent/Callable.html) instead of Runnable. The call() method of Callable can throw checked exceptions. When you call get() on your [Future](http://java.sun.com/javase/6/docs/api/java/util/concurrent/Future.html) instance it will throw an [ExecutionException](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutionException.html) if your call() method threw a checked exception. You can then access the underlying checked exception by calling getCause() on the ExecutionException.
Output from anonymous classes?
[ "", "java", "exception", "closures", "anonymous-types", "" ]
``` #include <cstring> int main() { char *pName = new char[10]; char dummy[] = "dummy"; strcpy(pName + 0,dummy);//how this is different from -->this works strcpy(pName[0],dummy);//this one...--> error C2664: 'strcpy' : //cannot convert parameter 1 //from 'char' to 'char *' } ```
* pName[0] is the first element in a character array (**one** character) * pName is a shortcut to &pName[0] (a pointer to the first element of your array) The reason you are getting your error is because strcpy expects a pointer to a char (char\*), and not a char value (which is what pName[0] is)
When dealing with pointers and arrays in C or C++ it really helps to recognize them as very distinct constructs (I think one of the best books that explains this distinction is a book called "Deep C Secrets" if i remember correctly). What muddies the waters is the fact that there is a one way silent conversion allowed from array-names to pointers (an inconsistency in the language's handling of variable names) - but it is very important not to interpret the existence of this decay phenomenon as implying equivalence. To help us reason about this, let us introduce the idea of a 'memory cell'. We model a 'memory cell' as having two attributes: ``` a) value b) address ``` We can then model a simple C++ variable as having two attributes (we do not need types at this low level of abstraction): ``` c) name d) memory cell ``` Like most models, it has some deficiencies (does not deal with an array with more than one element, but it is sufficient for our purposes). So for example: ``` // non-array variable: name 'i', and memory cell: value=3, address=0x0A int i = 3; // non-array variable: name 'p', and memory cell: value=0x0A, address=0x0B int *p = &i; // array variable: name 'a', and memory cell: vale=4, address=0x0C int a[1] = { 4 }; // non-array variable: name 'b', and memory cell: value=0x0C, address = 0x0D int (*b)[1] = &a; // non-array variable: name 's', and memory cell: value=0x0C, address = 0x0E int *s = &a[0]; // non-array variable: name 't', and memory cell: value=0x0C, address = 0x0F int *t = a; // Here is the key difference! read on... ``` Now here's the main difference between an array variable and a non-array (pointer) C++ variable: > When a variable name in C++ is evaluated, it always evaluates to the value of its memory cell with one exception: if the variable names an array variable. > If the variable is the name of an array it evaluates to the *address* of the memory cell. > The above two lines are worth reading again. Here are some examples to help clarify the implications (refer to the above variables): ``` int k = i; // the 'i' name evaluates to the value of its cell, so 'k' is set to 3 int *q = p; // 'p' evaluates to the value of its cell, so 'q' is set to 0x0A int *r = a; // 'a' evaluates to the *address* of its cell, so 'r' is set to 0x0C int (*c)[1] = b; // 'c' is set to 0x0D ``` This in no way should imply that an array variable is the *same* as a pointer variable. They have inherently different types and any attempt to treat them as the *same* (i.e. define a variable name as an array in one translation unit, and as a pointer in another) will result in bad things happening. So for e.g. do not do this: ``` // myproj_file1.cpp int array[100] = { 0 }; // here 'array' evaluates to the *address* of the first memory cell // myproj_file2.cpp extern int* array; // here 'array' evaluates to the *value* of the first memory cell // Assuming the linker links the two // what it does if you read the assembly, is something like this: // extern int* array = (int*) array[0]; // but it doesn't have to, it can do anything, since the behavior is undefined ``` I hope this helps. If you still feel that further clarification might help, please ask a followup question, and don't hesitate to get a copy (library?) of that "Deep C Secrets" book :) -- p.s. function types and their names and their decay are irrelevant to most of this post p.s. I have also intentionally left out that the array-to-pointer conversion does not occur when arrays are bound to reference types
What is the difference between pointer and array in the following context?
[ "", "c++", "arrays", "pointers", "strcpy", "" ]
I am trying to insert a record. This code worked but has stopped working I don't know why. Here is the code: ``` using (SAASDataContext dc = new SAASDataContext()) { tblAssessment a2 = new tblAssessment(); a2.AssessmentCentreId = centreId; a2.AttemptNumber = 1; dc.tblAssessments.InsertOnSubmit(a2); dc.SubmitChanges(); CurrentAssessmentId = a2.AssessmentId; } ``` The code compiles but throws the exception below on the `dc.SubmitChanges();` line. **Exception thrown:** > An attempt has been made to Attach or Add an entity that is not new, > perhaps having been loaded from another DataContext. This is not > supported. **Notes:** `AssessmentCentreId` is a foreign key on `tblCentre`, centreId is a valid existing centre id, AssessmentCentreId and AttemptNumber are the only not null fields all other columns allow nulls. I have googled but all the results seem to pertain to people trying to attach entities pulled from other disconnected DataContext's I'm not doing that so I'm stumped. **UPDATE:** Adding ``` dc.DeferredLoadingEnabled = false; ``` at the top of the using block makes it work, but I'd like to know why coz I have no idea at the moment sufficiently advanced technology being indistinguishable from magic right now :)
The issue is that the Centre object doesn't exist in the context. It's in the db, but not "in your hand" with a2. Try this: ``` a2.AssessmentCentre = dc.AssessmentCentres.SingleOrDefault( d=>d.AssessmentCentreId.Equals(centreId)); ``` The AssessmentCentre object will then exist in the context, which means there will be no problem with attaching it to a2.
This was bugging me as well. I did some searching and found a lot of confusion and some sloppy work-arounds regarding detached entities. **I then found a nice solution on codeplex that has solved the immediate issue and has greatly extended linq2sql functionality.** Its a small class thats really easy to implement and forms an EntityBase for your projects dbml's. Here is the offical description and link. LINQ to SQL Entity Base is a simple base class that is primarily designed to support LINQ to SQL in a disconnected way, which is one of the shortcomings of the LINQ to SQL technology at the present time. This is highly useful in an n-Tier, distributed or ASP.NET environment where disconnected functionality is relavent. <http://linq2sqleb.codeplex.com/> Hope this helps anyone who is having similar. Jerome Vernon
LINQ to SQL Basic insert throws: Attach or Add not new entity related exception
[ "", "c#", "asp.net", "linq-to-sql", "" ]
I've been looking around for quite a while and feel that I have a particularly unique situation. I am generating an image from a 3rd party program (which I embedded into my C# app) which is saved to the file system on my web server. Do you know of any efficient ways to dispose of these images after a particular session is completed? For Clarity: Initially I was thinking about a folder (for my images stored by session ID) that has its contents automatically deleted every 24 hours or so. I don't like this idea because it's not really scalable. I also looked at the ASP.NET dynamic image generation from this website. <http://www.sitepoint.com/article/generating-asp-net-images-fly/> however this seems a little overkill because my image needs to be saved to the file system one way or another. If I save the image as a static name then generate a bitmap from it using the aforementioned method I am worried that concurrent usage could break the application. This leaves me with saving the file names with the session ID in the name, however I can't find any efficient way of cleaning up the images after the session ends. Thanks! -Dave Update: I like pretty much all the solutions presented so far (I don't think the database one will work because of the way I am exporting images) I appreciate all of your help... I will start working on implementing these and will report back which seems to work best! Update2: I ended up randomly generating image names, storing them, then removing them at the end of the session, thanks for all your help. All the methods presented were excellent suggestions though. For this particular situation though this method works the best.
Track the temporary file names in a list and remove them in the Session\_End event or in the load or init event of every page check for session timeout programmatically and remove the files. Something like: ``` if (Context.Session != null) { if (Session.IsNewSession) { // delete temporary files } } ```
How about adding a Global.asax file to your website, and in the Session\_End event, you remove the file. ``` protected void Session_End(Object sender, EventArgs e) { // Remove file } ```
How to "temporarily" store images on web server per session in ASP.NET and C#
[ "", "c#", "asp.net", "image", "session", "" ]
I have a Win32 application and i want to Add a DateTimePicker Control, like the one in .NET. I though don't want to include the whole Framework in my application, nor MFC or whatever. How can I add the native control in a Way with the least amount of dependencies?
Start [Here](http://msdn.microsoft.com/en-us/library/bb761815(VS.85).aspx "Here")
You can use [CreateWindow](http://msdn.microsoft.com/en-us/library/ms632679(VS.85).aspx) and "SysDateTimePick32" as the class name.
How can I add Windows DateTimePicker to a win32 Application in c++
[ "", ".net", "c++", "winapi", "" ]
To anyone who can help, Thanks Okay, so I have a database holding a customer list. The problem that I am having is that I have found that all the entries for the customers First and Last names are stored in all Uppercase letters. And I wanted to know if anyone knows of some utility that I could use to convert the names to their correct casing. I thought about just making everything lowercase and the making the first letter uppercase, but this will not always be correct in all instances. I would also like to be able to do this in Java if at all possible.
A quick [Google search](http://www.google.com/search?q=capitalize+names+java) turned up <http://freejava.info/capitalize-english-names/>: > There are names in the English language like Sam O'Neil, Jenny McCarthy, Beverly d'Angelo, Leonardo di Caprio, Don Alejandro de la Vega, Wernher von Braun, etc. that give us trouble when we try to properly capitalize them in software applications. The following java code helps in situation where capitalization of names is required. The code there capitalizes the letter after "d'", "Mc", or "Mac", or after any punctuation, and has an exception list for "Macintosh", "von", "van", "de", "la", "da", and "di".
Since names nowadays can be artbirarily capitalized there is no general algorithm for capitilization that you can use. Some are culture dependent -- I capitalize *Van* in my name because my family has been in America for a long time, but it would be *van* in Dutch (but only when following my given name according to [this article](http://en.wikipedia.org/wiki/Capitalization#Compound_names)). The easiest algorithm to use would probably to capitalize the first letter of each word in the name and keep a table of exceptions. If the table gets large you can look at it and derive other rules. The article above lists some standard American rules if you want to start with that (such as don't captialize "de").
Given Name Formatting
[ "", "java", "" ]
Lets say I have one table called "REVIEWS" This table has Reviews that customers have written for various products. I would like to be able to get a "count" for all the reviews that each customer has written, so I write: ``` SELECT count(*) AS counter FROM reviews WHERE customers_id = 12345 ``` Now, my problem is that I wish to have a count like above BUT only for customers who have written a SPECIFIC product review For instance, ``` SELECT customers_review FROM reviews WHERE products_id = '170' ``` In summary, I wish to be able to get the customers TOTAL COUNT for every review they have written, but ONLY for customers who have written a review for a specific product.
``` select customers_id, count(*) from reviews where customers_id in (select customers_id from reviews where products_id = '170') group by customers_id; ```
``` SELECT customers_id, COUNT(*) AS counter FROM reviews WHERE customers_id IN( SELECT customers_id FROM reviews WHERE products_id = '170' ) GROUP BY customers_id ``` This will pull any customer who wrote about product X, and then count up total number of reviews they posted.
SQL query: count for all the reviews that each customer has written
[ "", "sql", "" ]
This is a long shot, I know... Let's say I have a collection ``` List<MyClass> objects; ``` and I want to run the same method on every object in the collection, with or without a return value. Before Linq I would have said: ``` List<ReturnType> results = new List<ReturnType>(); List<int> FormulaResults = new List<int>(); foreach (MyClass obj in objects) { results.Add(obj.MyMethod()); FormulaResults.Add(ApplyFormula(obj)); } ``` I would **love** to be able to do something like this: ``` List<ReturnType> results = new List<ReturnType>(); results.AddRange(objects.Execute(obj => obj.MyMethod())); // obviously .Execute() above is fictitious List<int> FormulaResults = new List<int>(); FormulaResults.AddRange(objects.Execute(obj => ApplyFormula(obj))); ``` I haven't found anything that will do this. Is there such a thing? If there's nothing generic like I've posited above, at least maybe there's a way of doing it for the purposes I'm working on now: I have a collection of one object that has a wrapper class: ``` class WrapperClass { private WrappedClass wrapped; public WrapperClass(WrappedClass wc) { this.wrapped = wc; } } ``` My code has a collection `List<WrappedClass> objects` and I want to convert that to a `List<WrapperClass>`. Is there some clever Linq way of doing this, without doing the tedious ``` List<WrapperClass> result = new List<WrapperClass>(); foreach (WrappedClass obj in objects) results.Add(new WrapperClass(obj)); ``` Thanks...
Would: ``` results.AddRange(objects.Select(obj => ApplyFormula(obj))); ``` do? or (simpler) ``` var results = objects.Select(obj => ApplyFormula(obj)).ToList(); ```
I think that the Select() extension method can do what you're looking for: ``` objects.Select( obj => obj.MyMethod() ).ToList(); // produces List<Result> objects.Select( obj => ApplyFormula(obj) ).ToList(); // produces List<int> ``` Same thing for the last case: ``` objects.Select( obj => new WrapperClass( obj ) ).ToList(); ``` If you have a `void` method which you want to call, here's a trick you can use with IEnumerable, which doesn't have a ForEach() extension, to create a similar behavior without a lot of effort. ``` objects.Select( obj => { obj.SomeVoidMethod(); false; } ).Count(); ``` The `Select()` will produce a sequence of `[false]` values after invoking `SomeVoidMethod()` on each `[obj]` in the objects sequence. Since `Select()` uses deferred execution, we call the `Count()` extension to force each element in the sequence to be evaluated. It works quite well when you want something like a `ForEach()` behavior.
Using Linq to run a method on a collection of objects?
[ "", "c#", "linq", "" ]
I need to populate XFA form fields in a PDF (created with Adobe LiveCycle Designer). We're attempting to use iText (actually iTextSharp with C#) to parse the PDF, populate the XFA fields and then save the modified PDF back out. All the examples I can find with iText (very few iTextSharp examples) talk about modifying AcroForm fields. This PDF does NOT have AcroForm fields and uses XFA only. Pointers to any non-standard resources would be helpful (I've already done the requisite Googling on the topic and haven't found anything useful). Code examples here would be awesome from anyone who has actually done what I'm trying to do.
If you can get a data packet into the PDF, the XFA runtime in Acrobat would populate those fields with the data in the data packet. If you want to see what one of these looks like, create a form in LiveCycle Designer (comes with Acrobat Pro), add some fields to it, and save it as a dynamic PDF. Open the form in Acrobat and type some values into the fields and save it. Open the PDF with a tool that lets you peer at the PDF data and you'll find /Catalog/AcroForm/XFA a stream that has an <xfa:datasets> packet with the values you typed. That's what you'll need to create yourself and insert into the PDF. The XDP spec includes a description of the data packet and the merge algorithm. You can find it here: <http://partners.adobe.com/public/developer/xml/index_arch.html> Alternately, you buy the LiveCycle server from Adobe which lets you do all this programmatically in a number of ways including through web service calls.
iTextSharp can work with XFA. To remove all doubts, please take a look at sample on iText website: <http://itextpdf.com/examples/iia.php?id=165>
Using iText (iTextSharp) to populate XFA form fields in PDF?
[ "", "c#", "pdf", "itext", "xfa", "" ]
I wish to be able to generate URL variables like this: ``` http://example.com/195yq http://example.com/195yp http://example.com/195yg http://example.com/195yf ``` The variables will match to a MySQL record set so that I can pull it out. At the time of creation of that record set, I wish to create this key for it. How can I do this? What is the best way to do this? Are there any existing classes that I can make use of? Thanks all
Basically, you need a hash function of some sort. This can be SHA-1 function, an MD5 function (as altCogito), or using other data you have in the record and encoding it. How many records do you think you will have? Be careful on selecting the solution as a hash function has to be big enough to cover you well, but too big and you create a larger database than you need. I've used SHA-1 and truncate to 64 or 32 bits, depending on need. Also, look at REST. Consider that the URL may not have to be so mysterious...
This can be done pretty straightforward in a couple of ways: * Use a hash, such as [MD5](http://www.twmacinta.com/myjava/fast_md5.php). (would be long) * [Base-64](http://www.source-code.biz/snippets/java/2.htm) encode a particular ID or piece of data If you're asking whether or not there is anything that does this already with MySQL records, I'm not sure that you'll find something as design-wise, data is really, really conceptually far away from the URLs in your website, even in frameworks like Grails. Most don't even attempt to wrap up front-end and data-access functionality into a single piece.
How to generate unique URL variables that match to a db record?
[ "", "php", "mysql", "url", "uniqueidentifier", "" ]
I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary. I will clarify with an example. Say my input is dictionary a, constructed as follows: ``` a = dict() a['cat'] = 1 a['fish'] = 1 a['dog'] = 2 # <-- unique a['bat'] = 3 a['aardvark'] = 3 a['snake'] = 4 # <-- unique a['wallaby'] = 5 a['badger'] = 5 ``` The result I expect is `['dog', 'snake']`. There are obvious brute force ways to achieve this, however I wondered if there's a neat Pythonian way to get the job done.
I think efficient way if dict is too large would be ``` countMap = {} for v in a.itervalues(): countMap[v] = countMap.get(v,0) + 1 uni = [ k for k, v in a.iteritems() if countMap[v] == 1] ```
Note that this actually is a bruteforce: ``` l = a.values() b = [x for x in a if l.count(a[x]) == 1] ```
Python: finding keys with unique values in a dictionary?
[ "", "python", "dictionary", "" ]
Simple query, possibly impossible but I know there are some clever people out there :) Given a boolean parameter, I wish to define my where clause to either limit a certain column's output - or do nothing. So, given parameter @bit = 1 this would be the result: where column = 1 given parameter @bit = 0 this would be the result: where column = 1 or 0 i.e. have no effect/show all results (column is a bit field) I'm not wanting dynamic sql - I can settle for fixing this in code but I just wondered if there's some clever magic that would make the above neat and simple. Is there? I'm using sql server. cheers :D
The answer `column = 1 or @bit = 0` works if column may only be 0 or 1. If column may be any value you want: `column = 1 or @bit = 0 and column = 0`.
``` SELECT * FROM mytable WHERE column = 1 OR @bit = 0 ``` If you have an index on `column1`, this one will be more efficient: ``` SELECT * FROM mytable WHERE column = 1 AND @bit = 1 UNION ALL SELECT * FROM mytable WHERE @bit = 0 ``` See this article in my blog for performance comparison of a single `WHERE` condition vs. `UNION ALL`: * [**IN with a comma separated list: SQL Server**](http://explainextended.com/2009/06/23/in-with-a-comma-separated-list-sql-server/)
sql query - true => true, false => true or false
[ "", "sql", "sql-server", "t-sql", "boolean-logic", "bit", "" ]
At home, on Linux, I've experimented with pyUNO to control OpenOffice.org using Python. I've been using Python 2.6. It all seems to work nicely. Now I thought I would try one of my scripts ([run a graphical diff for ODF doc](http://craig.mcqueen.id.au/OpenOfficeGraphicalDiff.html)) on Windows. But when I tried to run it, I got: ``` ImportError: No module named uno ``` According to [udk: Python UNO Bridge](http://udk.openoffice.org/python/python-bridge.html) and [OpenOffice.org Running Python on Windows](http://wiki.services.openoffice.org/wiki/Using_Python_on_Windows), I have to run the Python interpretter that's installed with OpenOffice.org. **Q1: Is Python 2.6 available for OpenOffice.org?** However, that interpreter is **Python 2.3**, which is getting a little old! and my script uses a feature not supported by 2.3 (`subprocess` module). **Q2: Can pyUNO programming on Windows be done with a pyUNO add-on to the standard Python distribution, not the Python that is bundled with OpenOffice.org?** In my searching so far, I haven't been able to find any indication that there is a pyUNO module available to be installed into the standard Python Windows distribution... which is a surprise because on Ubuntu Linux, UNO is supported just fine in Python just by: ``` apt-get install python-uno ``` Another problem with this is: what if I want to make a program that uses both pyUNO and other 3rd party libraries? I can't install pyUNO into my Python installation on Windows, so am I forced to somehow install my other 3rd party libraries into OpenOffice.org's bundled Python? It makes it difficult to create larger, more full-featured programs. Am I missing something, or are we stuck with this situation for now?
You can import uno into your system's python on Win32 systems. (Not Python 3 yet). Tutorial at <http://user.services.openoffice.org/en/forum/viewtopic.php?f=45&t=36370&p=166783> It's not difficult - import three environment variables, and append one item to your pythonpath. For additional flexibility, you can use the COM-UNO bridge instead of the Python-UNO bridge. The syntax is generally quite similar, and you can use any version of Python (including Python3). Info at <http://user.services.openoffice.org/en/forum/viewtopic.php?f=45&t=36608&p=167909>
Per [openoffice's docs](http://wiki.services.openoffice.org/wiki/Python), the Python version supported is WAY behind -- "Efforts on moving PyUNO to Python 2.5 continue", 2.6 not even on the map. So "stuck with this situation for now" is a fair assessment!-)
OpenOffice.org development with pyUno for Windows—which Python?
[ "", "python", "windows", "openoffice.org", "uno", "pyuno", "" ]
I am trying to verify whether an object is `null` or not, using this syntax: ``` void renderSearch(Customer c) { System.out.println("search customer rendering>..."); try { if (!c.equals(null)) { System.out.println("search customer found..."); } else { System.out.println("search customer not found..."); } } catch (Exception e) { System.err.println("search customer rendering error: " + e.getMessage() + "-" + e.getClass()); } } ``` I get the following exception: > search customer rendering error: null > class java.lang.NullPointerException I thought that I was considering this possibility with my **if** and **else** statement.
You're not comparing the objects themselves, you're comparing their references. Try ``` c != null ``` in your **if** statement.
``` !c.equals(null) ``` That line is calling the equals method on c, and if c is null then you'll get that error because you can't call any methods on null. Instead you should be using ``` c != null ```
Compare an object to null in Java
[ "", "java", "object", "null", "compare", "" ]
Given an Youtube video id how can I determine from JavaScript whether the video has embedding disabled?
[yt:noembed](http://code.google.com/apis/youtube/2.0/reference.html#youtube_data_api_tag_yt:noembed) > The tag specifies that a video may not be embedded on other websites. This tag may be included in a request to upload or update a video's metadata. By default, videos can be embedded on other sites unless they are private videos. If a request does not include either the tag or the tag, a video will be embeddable on other websites. Possibly of Interest: * [Dealing with YouTube Videos that You can't Embed](http://gdatatips.blogspot.com/2008/11/dealing-with-youtube-videos-that-you.html)
You'd have to use a server-side script for this, and use some AJAX to call it.
Detecting Disabled Youtube Video
[ "", "javascript", "youtube", "" ]
At some point "Find All References" feature got broken for a single solution that I have. It works in all other solutions. For this one, it always returns "Search found no results" What could be the problem?
In the old days (VC6 :) ) this type of problem was often fixed by deleting the .ncb file and letting it be rebuilt automatically. Not sure if this is still true in VS2005/8.
I would kill all instances of Visual Studio and try again. If this doesn't work, I would imagine that there really *are* no references to the type or member you are looking for. Since this feature is working for other solutions I find it hard to believe that this is an issue with the IDE itself. I think the most likely explanation is that the IDE is correct and you actually have no references. Do you have two types that are similarly named but not actually the same type? Can you find the references by text search?
"Find All References" broken in one solution
[ "", "c#", "visual-studio", "ide", "visual-studio-2005", "find-all-references", "" ]
Scenario: I have a container object which holds a mixed bag of objects all inheriting from the MyContainedObject class. Consumers of the container class do not have direct access to contained objects, but my be interested in knowing when they change. Design Decision: What's the best way to listen for ChangeEvents on a specific class type? My initial thought is to do something with Generics. For example, ``` private TreeMap<Class, ChangeListener> listeners; public <T extends MyContainedObject> addChangeListenerForObjectsOfType(Class<T> className, ChangeListener listener) { listeners.put(className, listener); } ``` When a change is detected the container class would iterate through the list and notify only listeners registered for that class type. Other suggestions? Thanks.
I'm assuming the key type on your TreeMap was meant to be a Class, not a MyContainedObject. If you actually need to listen for ChangeEvents on specific class types, and you want to be able to add elements to your collection even after setting listeners, this seems pretty reasonable. You'll probably want to support multiple listeners for the same type, so you should either use a Multimap class ([Google Collections](http://code.google.com/p/google-collections/) has some) or use a collection (probably an IdentityHashSet) for the values in your Map. You may also want to add a type parameter to ChangeListener so that the listener can get the object the event fired on already casted to the appropriate type. ``` interface ChangeListener<T> { void changed(T obj, /* whatever */); } ``` You'll have to do an unchecked cast inside of your container for this to work, but it should be safe as long as your listener adding method does the right thing. eg: ``` public <T extends MyContainedObject> addChangeListener(Class<T> klass, ChangeListener<? super T> listener) { ... } private <T extends MyContainedObject> Set<ChangeListener<? super T>> getChangeListeners(T obj) { Set<ChangeListener<? super T>> result = new IdentityHashSet<ChangeListener<? super T>>(); for (Map.Entry<Class<? extends MyContainedObject>, Set<ChangeListener<?>>> entry : listeners.entrySet()) { if (entry.getKey().isInstance(obj)) { // safe because signature of addChangeListener guarantees type match @SuppressWarnings("unchecked") Set<ChangeListener<? super T>> listeners = (Set<ChangeListener<? super T>>) entry.getValue(); result.addAll(listeners); } } return result; } ``` One minor nit: I'd avoid using "className" as the name of a variable that holds a Class object. A class name is a String, typically the result of Class.getName(), etc.. It's a bit annoying, but the convention I've usually seen to avoid get around the fact that "class" is a reserved word is to misspell it as either "klass" or "cls". Also, if you don't need the ability to update your collection after adding listeners then I'd go with what akf suggested, as it's simpler.
You could also simply have your container proxy the `addChangeListener` call to the contained objects in question. This will allow them to maintain their listener list and fire the calls as needed, without the added complexity of another level in the listener heirarchy.
Java - Generic ChangeListener
[ "", "java", "" ]
I've a class which extends `JPanel`. I overwrote `protected void paintComponent(Graphics g)`. There is a variable which has to be recalculated when the panel's dimensions change. How do I do that in a proper way?
If I understand the question correctly then you should read the section from the Swing tutorial on [How to Write a Component Listener](http://docs.oracle.com/javase/tutorial/uiswing/events/componentlistener.html) which shows you how to listen for a change in a components size.
Like Adam Paynter suggested, you can also add an inner class to your code, like this: ``` class ResizeListener extends ComponentAdapter { public void componentResized(ComponentEvent e) { // Recalculate the variable you mentioned } } ``` The code you have entered between the innermost brackets will be executed everytime the component get resized. Then you add this listener to your component with ``` myJPanel.addComponentListener(new ResizeListener()); ``` You can get your component by using `e.getComponent()`. This way you can call any method of your component from inside the inner class like ``` e.getComponent().getWeight(); ```
How to "do something" on Swing component resizing?
[ "", "java", "swing", "" ]
We have a partitioned view with 12 member tables. The partitioning column is a date, we have one table for each month. Data are continually being inserted into the table of the current month. Older tables are constant. At the beginning of each next month a new table is going to be created and added to the view. At the same time we are going to remove the oldest table from the database but we have to preserve the data somehow because in the future we might have to reinsert those data into the database temporarily for analysis and comparison. For example in june 2011 when the partitioned view will have member tables from july 2010 to june 2011 we might have to reinsert the data of june 2009 and june 2010 temporarily. My question is: How would you do this 'preserve' and then the 'reinsert' operation? Is there a recommended way or a well-known pattern for this? We are using SQL Server 2005 Standard Edition. I'm a novice in database administration. (EDIT: Why might someone use partitioning and a new table for each month? See [SQL Server 2000 Partitioned Views](http://www.fotia.co.uk/FA.02.Sql2KPartitionedViews.01.aspx) and [SQL Server 2005 Partitioned Tables and Indexes](http://www.sqlskills.com/resources/Whitepapers/Partitioning%20in%20SQL%20Server%202005%20Beta%20II.htm#_Toc79339942))
Why not use the bulk copy tool (bcp) to export the contents of your table to a file. You can then zip it up and keep it somewhere safe until you need to use the bcp tool again to recreate the table. To export ``` bcp yourdb..Stuff200901 OUT Stuff200901.bcp -T -S yourdbsvr -r "\n" -t "|" -c ``` To import (note you'll need to create the table) ``` bcp yourdb..Stuff200901 in Stuff200901.bcp -c -S yourdbsvr -T -t "|" -k -e err.txt ``` Type bcp to get a full list of options at the command prompt.
Probably not the answer you want, but I'll say it anyways - this is typically what you would use a data warehouse for. Shuffle those old months off to the data warehouse and do your reporting & analysis there.
How to preserve old data that might have to be reinserted into the database?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I'm new to Eclipse-CDT, setting up a new project for the first time. I'm trying to reference Boost *without* hardcoding an absolute path. I've put boost in my workspace folder, e.g. /home/user/workspace/boost\_1\_39\_0 I was then hoping to add an include directory pointing to that folder relative to the workspace, but Eclipse won't do that, it seems to only want to point to thinks in /home/user/workspace/[MyProjectNameHere] Any tips? It doesn't seem to make sense to copy Boost into my project folder, because then it shows up in Eclipse and Eclipse wants to build it (sure, I *could* exclude it). * Alex
When adding an include file path in the CDT project (Project Properties/C/C++ General/Paths and Symbols), there are 3 buttons to browse for a location: * Variables... * Workspace... * File system... If you press the Workspace... button, the path will be relative to the workspace/project. If you select the Variables... button, you'll get to incorporate variables such as `${WorkspaceDirPath}`. The variables can also reference environment variables, which might be handy if you want a single install of boost to be referenced from projects that might reside anywhere on your machine. If you incorporate variables into the path, make sure the "Is a workspace path" option is checked - otherwise the variable seems to get evaluated when you press "OK" instead of staying a variable to be evaluated at build time.
I got this working doing roughly what Michael Burr suggested above: Under Project Properties/C/C++ General/Paths and Symbols, I added paths like this: ${ProjDirPath}/../boost\_1\_39\_0 * Alex
Eclipse CDT: How to reference 3rd party includes via a Relative path
[ "", "c++", "eclipse", "boost", "eclipse-cdt", "" ]
I am sorry if this is a duplicate but I was not able to find a definitive answer to what is the best practice for each type. I would like to know what the appropriate conditions are that define when to use BufferedReader vs FileReader or BufferedInput/OutputStream vs FileInput/OutputStream? Is there a formula of sorts that will always tell you what is appropriate? Should I just always used buffered? Thanks
Use a buffer if the stream is going to have lots of small access. Use unbuffered if you are going to have relatively few, relatively large accesses.
The only time you should use unbuffered I/O is when the delay and aggregation imposed by buffering is inappropriate to your application.
Buffered vs non buffered, which one to use?
[ "", "java", "file", "buffered", "" ]
I am using IText library to facilitate pdf export in an applet. During the export call it fails with following error: ``` java.lang.NoSuchMethodError: com.lowagie.text.pdf.PdfPTable.completeRow()V ``` I opened the Itext jar/PdfPtable.class in JD Decompiler and confirmed that the class has completeRow as a public method. Can somebody explain the possible scenarios when a `java.lang.NoSuchMethodError` is thrown even when jar/class has it? Here is the stack trace; may not be very helpful as most of the calls are our application specific. > Error while exporting to the CSV file - java.lang.NoSuchMethodError: com.lowagie.text.pdf.PdfPTable.completeRow()V > com.blox.table.action.ExportToCSVAction.actionPerformed(ExportToCSVAction.java:193) > javax.swing.AbstractButton.fireActionPerformed(Unknown Source) > javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) > javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) > javax.swing.DefaultButtonModel.setPressed(Unknown Source) > javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) > java.awt.Component.processMouseEvent(Unknown Source) > javax.swing.JComponent.processMouseEvent(Unknown Source) > java.awt.Component.processEvent(Unknown Source) > java.awt.Container.processEvent(Unknown Source) > java.awt.Component.dispatchEventImpl(Unknown Source) > java.awt.Container.dispatchEventImpl(Unknown Source) > java.awt.Component.dispatchEvent(Unknown Source) > java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) > java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) > java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) > java.awt.Container.dispatchEventImpl(Unknown Source) > java.awt.Window.dispatchEventImpl(Unknown Source) > java.awt.Component.dispatchEvent(Unknown Source) > java.awt.EventQueue.dispatchEvent(Unknown Source) > java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) > java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) > java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) > java.awt.EventDispatchThread.pumpEvents(Unknown Source) > java.awt.EventDispatchThread.pumpEvents(Unknown Source) > java.awt.EventDispatchThread.run(Unknown Source) > com.lowagie.text.pdf.PdfPTable.completeRow()V > com.blox.table.view.GridTableModel$PdfExportWriter.writeNewLine(GridTableModel.java:7259) > com.blox.table.view.GridTableModel.buildExportData(GridTableModel.java:3111) > com.blox.table.view.GridTableModel.export(GridTableModel.java:2541) > com.blox.table.view.GridTable.export(GridTable.java:1318) > com.blox.table.action.ExportToCSVAction.exportToFile(ExportToCSVAction.java:248) > com.blox.table.action.ExportToCSVAction.access$1(ExportToCSVAction.java:245) > com.blox.table.action.ExportToCSVAction$Worker.exportToCSVFile(ExportToCSVAction.java:111) > sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) > sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) > sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) > java.lang.reflect.Method.invoke(Unknown Source) > spin.Invocation.evaluate(Invocation.java:175) > spin.off.SpinOffEvaluator$1.run(SpinOffEvaluator.java:108) > java.lang.Thread.run(Unknown Source)
I found out that one of the third party jar was bundling a older version of iText library
It could be that a different version appears in your classpath or that the signature of that particular method has changed since your compiled your class
When do we get java.lang.NoSuchMethodError even when the jar/class has the particualar method
[ "", "java", "applet", "nosuchmethoderror", "" ]
I am aware of the Eclipse snippet "sysout" which is neatly replaced with System.out.println(); when tab-completed. This is very useful but sometimes, I need to wrap some existing code in a System.out.println(); In Eclipse internals, the template is defined as being able to wrap a "selected word". But how can I use the snippet with selected text since typing "sysout" obviously removes the selected text. Any idea?
The sysout template acts upon entire Java statements. 1. Highlight a statement in the editor. 2. Hit CTRL-SPACE (or whatever you have set up for content assist.) 3. Type sysout then hit enter. Note that when you're typing sysout it **will** temporarily overwrite your statement (but it will come back wrapped by `System.out.println` when you hit enter.)
Eclipse has "Surround Width" Option which can do this for you. SHIFT + ALT + Z should get you that to see how that templates meta-data layout.
How to use the "sysout" snippet in Eclipse with selected text?
[ "", "java", "eclipse", "code-snippets", "" ]
If I have a simple class setup like this: ``` class MyClass { private string _myName = string.Empty; public string MyName { get { return _myName; } } public void DoSomething() { // Get the name... string name = string.Empty; name = _myName; // OR name = MyName; // ...and do something with it... } } ``` Which should I use, the public property, or the data member? Obviously, in this example it doesn't make a difference, since they both just reference the same variable. But what about real world uses of Public Properties? In general, do Public Properties perform very little, in which case it is OK to call them? Or do people put a lot of functionality into their Public Properties that should not be called by internal class references? I saw something in another post about NOT putting lots of functionality into Properties, since examining them in the Debugger can perform unexpected results. Is that true?
Use the property - any logic that may be encapsulated within the setters and getters ought to apply, even within the class itself. If there is no logic within the getters and setters it is still not safe to use the fields themselves because if at any point you wish to add logic around the access to those fields you will have to refactor much more.
I believe that you should reference the property as a general practice. While in this particular example it really doesn't make much of a difference, the get/set accessors offer the ability to do a bit more work when grabbing a property. For example, many of our property "get" accessors perform some lookup within a more complex data structure or set default values if nothing has been defined. So that the rest of the class can take advantage of this logic, we make a habit of using the properties. Just so we don't have to think too hard about it, we try to generalize the practice. There may be instances in which we want to directly access the underlying data member, but then that is a conscious decision with a specific reason and it tends to be the exception.
Do you use Data Members or Public Properties from within the Class itself?
[ "", "c#", "asp.net", "properties", "data-members", "" ]
Is okay to break all dependencies using interfaces just to make a class testable? It involves significant overhead at runtime because of many virtual calls instead of plain method invocations. How does test driven development work in real world C++ applications? I read Working Effectively With Legacy Code and fond it quite useful but do not get up to speed practising TDD. If I do a refactoring it occurs very often that I have to completely rewite unit test because of massive logic changes. My code changes very often change the fundamental logic of the processing of data. I do not see a way to write unit tests which do not have to change in a large refactoring. May be someone can point me to an open source c++ application wich is using TDD to learn by example.
**Update**: See [this question too.](https://stackoverflow.com/questions/522334/practical-refactoring-using-unit-tests) I can only answer some parts here: *Is okay to break all dependencies using interfaces just to make a class testable? It involves significant overhead at runtime because of many virtual calls instead of plain method invocations.* If your performance will suffer too much because of it, no (benchmark!). If your development suffers too much, no (estimate extra effort). If it seems like it won't matter much and help in the long run and helps you with quality, yes. You could always 'friend' your test classes, or a TestAccessor object through which your tests could investigate stuff within it. That avoids making everything dynamically dispatchable just for testing. (it does sound like quite a bit of work.) Designing testable interfaces isn't easy. Sometimes you have to add some extra methods that access the innards just for testing. It makes you cringe a bit but it's good to have and more often than not those functions are useful in the actual application as well, sooner or later. *If I do a refactoring it occurs very often that I have to completely rewite unit test because of massive logic changes. My code changes very often change the fundamental logic of the processing of data. I do not see a way to write unit tests which do not have to change in a large refactoring.* Large refactorings by defintion change a lot, including the tests. Be happy you have them as they will test stuff after refactoring too. If you spend more time refactoring than making new features, perhaps you should consider thinking a bit more before coding to find better interfaces that can withstand more changes. Also, writing unit-tests before interfaces are stable is a pain, no matter what you do. The more code you have against an interface that changes much, the more code you will have to change each time. I think your problem lies there. I've managed to have sufficiently stable interfaces in most places, and refactor only parts now and then. Hope it helps.
I've routinely used macros, `#if` and other preprocessor tricks to "mock-out" dependencies for the purpose of unit testing in C and C++, exactly because with such macros I don't have to pay any run-time cost when the code is compiled for production rather than testing. Not elegant, but reasonably effective. As for refactorings, they may well require changing the tests when they are so overwhelmingly large and intrustive as you describe. I don't find myself refactoring so drastically all that often, though.
unit tests in C++
[ "", "c++", "unit-testing", "refactoring", "" ]
I'm building a tree-based data structure and overloaded [ ] so that I can say ``` node["key1", "key2", "key3"] ``` which returns the node whose parents 1, 2, and 3 levels above are the nodes with those keys. the nodes conceptually map to an array of data, so what I have now is this function: ``` node[keys...].SetValue(i, value) ``` which sets the i-th value in the node's data. what would be nice is if I could do this: ``` node[keys][i] = value ``` problem is, node[keys] returns a node, so the [i] indexing tries to get at another node. basically what I want to be able to do is overload "[ ][ ]" as an operator, which I can't. is there any way to get at what I'm trying to do?
Note: **This answer talks about implementing something like `obj[a][b][c]...` that could work with variable number of brackets. It seems it's not exactly what the OP wanted**. You can't overload that directly. You should return an object with an indexer from the first indexer so that you could simulate this functionality. It's a bit harder to simulate `set` but it's possible to do something like: ``` public class Node<T> { public Node<T> this[string key] { get { return GetChildNode(key); } set { if (value is DummyNode<T>) { GetChildNode(key).Value = value.Value; } else { // do something, ignore, throw exception, depending on the problem } } } public static implicit operator T(Node<T> value) { return value.Value; } private class DummyNode<T> : Node<T> { } public static implicit operator Node<T>(T value) { return new DummyNode<T> { Value = value }; } public T Value { get; set; } } ```
seems I just needed to tinker a bit more to figure it out...I created a second overload: ``` public object this[int index] { set { ... } } ``` which now lets me do ``` node["child1", "child1's child1"][i] = value ``` :)
overloading [][] in c#
[ "", "c#", "operator-overloading", "" ]
I'm trying to use a timer to schedule a recurring event in an application. However, I want to be able to adjust the period at which the event fires in real time (according to the users input). For example: ``` public class HelperTimer extends TimerTask { private Timer timer; //Default of 15 second between updates private int secondsToDelay = 15; public void setPeriod(int seconds) { this.secondsToDelay = seconds; long delay = 1000; // 1 second long period = 1000*secondsToDelay; // seconds if (timer != null) { timer.cancel(); } System.out.println(timer); timer = new Timer(); System.out.println(timer); timer.schedule(this, delay, period); } public int getPeriod() { return this.secondsToDelay; } } ``` I then start a new instance of this class and call its set period function. However, when I do that, I get an Illegal state exception. You can see the System.out.println(timer); in there because I'm checking, and yep sure enough, they are two different timers... so why am I getting an IllegalStateException when I try to run a schedule call on a brand new Timer instance!?!?!?! ``` java.util.Timer@c55e36 java.util.Timer@9664a1 Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Task already scheduled or cancelled at java.util.Timer.sched(Unknown Source) at java.util.Timer.schedule(Unknown Source) at HelperTimer.setPeriod(HelperTimer.java:38) ```
You can't reuse a TimerTask as you're doing here. Relevant porition of [Timer](http://www.docjar.com/html/api/java/util/Timer.java.html): ``` private void sched(TimerTask task, long time, long period) { if (time < 0) throw new IllegalArgumentException("Illegal execution time."); synchronized(queue) { if (!thread.newTasksMayBeScheduled) throw new IllegalStateException("Timer already cancelled."); synchronized(task.lock) { //Right here's your problem. // state is package-private, declared in TimerTask if (task.state != TimerTask.VIRGIN) throw new IllegalStateException( "Task already scheduled or cancelled"); task.nextExecutionTime = time; task.period = period; task.state = TimerTask.SCHEDULED; } queue.add(task); if (queue.getMin() == task) queue.notify(); } } ``` You'll need to refactor your code so that you create a new TimerTask, rather than re-using one.
It seems odd to me to have a TimerTask with its own Timer inside it. Bad design. I'd totally separate the two and have the TimerTask implementation be handed off to a Timer, and put all that logic about fiddling with the period inside another class that provides an interface for doing so. Let that class instantiate the Timer and TimerTask and send them off to do their work.
Java Timer
[ "", "java", "timer", "" ]
I've been trying to think of a way to traverse a hierarchical structure, like a linked list, using a list expression, but haven't come up with anything that seems to work. Basically, I want to convert this code: ``` p = self.parent names = [] while p: names.append(p.name) p = p.parent print ".".join(names) ``` into a one-liner like: ``` print ".".join( [o.name for o in <???>] ) ``` I'm not sure how to do the traversal in the `???` part, though, *in a generic way* (if its even possible). I have several structures with similar `.parent` type attributes, and don't want to have write a yielding function for each. Edit: I can't use the `__iter__` methods of the object itself because its already used for iterating over the values contained within the object itself. Most other answers, except for liori's, hardcode the attribute name, which is what I want to avoid. Here's my adaptation based upon liori's answer: ``` import operator def walk(attr, start): if callable(attr): getter = attr else: getter = operator.attrgetter(attr) o = getter(start) while o: yield o o = getter(o) ```
If you want your solution to be general, use a general techique. This is a fixed-point like generator: ``` def fixedpoint(f, start, stop): while start != stop: yield start start = f(start) ``` It will return a generator yielding start, f(start), f(f(start)), f(f(f(start))), ..., as long as neither of these values are equal to stop. Usage: ``` print ".".join(x.name for x in fixedpoint(lambda p:p.parent, self, None)) ``` My personal helpers library has similar fixedpoint-like function for years... it is pretty useful for quick hacks.
The closest thing I can think of is to create a parent generator: ``` # Generate a node's parents, heading towards ancestors def gen_parents(node): node = node.parent while node: yield node node = node.parent # Now you can do this parents = [x.name for x in gen_parents(node)] print '.'.join(parents) ```
How to walk up a linked-list using a list comprehension?
[ "", "python", "list-comprehension", "" ]
I am trying to setup emacs for python development. From what I read, it is recommended to use python-mode.el rather than the default python.el from Emacs 22.3. So I embark on the new adventure. From what I understand, python-mode has the several dependencies, so I need to install rope, ropemode and ropemacs. Then on top of that I need to install pymacs. **Q: is it correct?** This is my new .emacs now: ``` (custom-set-variables ;; custom-set-variables was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. '(inhibit-startup-screen t) '(tab-width 4)) (custom-set-faces ;; custom-set-faces was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. ) (setq emacs-config-path "~/.emacs.d/") (setq base-lisp-path "~/.emacs.d/site-lisp/") (setq site-lisp-path (concat emacs-config-path "/site-lisp")) (defun add-path (p) (add-to-list 'load-path (concat base-lisp-path p))) (add-path "") (add-to-list 'load-path "~/.emacs.d") (require 'psvn) ;; python-mode ;; (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist)) (setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist)) (autoload 'python-mode "python-mode" "Python editing mode." t) (setq pymacs-load-path '( "~/.emacs.d/site-lisp/rope" "~/.emacs.d/site-lisp/ropemode" "~/.emacs.d/site-lisp/ropemacs")) (setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist) python-mode-hook '(lambda () (progn (set-variable 'py-indent-offset 4) (set-variable 'py-smart-indentation nil) (set-variable 'indent-tabs-mode nil) ;;(highlight-beyond-fill-column) (define-key python-mode-map "\C-m" 'newline-and-indent) (pabbrev-mode) (abbrev-mode) ) ) ) ;; pymacs (autoload 'pymacs-apply "pymacs") (autoload 'pymacs-call "pymacs") (autoload 'pymacs-eval "pymacs" nil t) (autoload 'pymacs-exec "pymacs" nil t) (autoload 'pymacs-load "pymacs" nil t) ;; Search local path for emacs rope ;; ;; enable pymacs ;; (require 'pymacs) (pymacs-load "ropemacs" "rope-") ``` Now, when i start emacs, I got this error message: ``` ("C:\\opt\\emacs-22.3\\bin\\emacs.exe") Loading encoded-kb...done Loading regexp-opt...done Loading easy-mmode...done Loading wid-edit...done Loading edmacro...done Loading derived...done Loading advice...done Loading cl-macs...done Loading byte-opt...done An error has occurred while loading `c:/opt/cygwin/home/akong/.emacs': File error: Cannot open load file, pymacs To ensure normal operation, you should investigate and remove the cause of the error in your initialization file. Start Emacs with the `--debug-init' option to view a complete error backtrace. For information about GNU Emacs and the GNU system, type C-h C-a. [2 times] ``` To make it slightly more complicated: For work reason I have to use python 2.4, but I have python 2.6 installed on my PC. But obviously rope does not like 2.4 so I did not run setup.py. I untar/unzip these packages and put these files under ~/.emacs.d/site-lisp. By default if python is invoked in command prompt, it is the python 2.4 executable. **Q: How can I successfully load 'pymacs'?**
It turns out I missed these two: ``` (add-to-list 'load-path "~/.emacs.d/site-lisp/Pymacs-0.23") ``` Obviously I need to load the pymac script. And I have set the env var PYMACS\_PYTHON to python 2.6 because I am using python 2.4 as default python interpreter, for work reason.
I have never used pymacs so far, but one thing which catches my eye when I look at your `.emacs` is that you apparently didn't add the pymacs directory to the *emacs* `load-path` but only to the `pymacs` one: ``` (setq pymacs-load-path '( "~/.emacs.d/site-lisp/rope" "~/.emacs.d/site-lisp/ropemode" "~/.emacs.d/site-lisp/ropemacs")) ``` You will probably need also something like: ``` (add-to-list 'load-path "~/.emacs.d/site-lisp/rope") (add-to-list 'load-path "~/.emacs.d/site-lisp/ropemode") (add-to-list 'load-path "~/.emacs.d/site-lisp/ropemacs") ``` (or whereever you have `pymacs.el`) so that emacs can find the lisp files. Also mentioned in the [pymacs documentation](http://pymacs.progiciels-bpi.ca/pymacs.html#check-the-search-paths) > 2.4 Install the Pymacs proper ... for the Emacs part ... > > This is usually done by hand now. > First select some directory along the > list kept in your Emacs *load-path*, for > which you have write access, and copy > file pymacs.el in that directory.
pymacs: General question and Installation problem
[ "", "python", "emacs", "rope", "pymacs", "" ]
Is there a builtin function in PHP to intelligently join path strings? The function, given `abc/de/` and `/fg/x.php` as arguments, should return `abc/de/fg/x.php`; the same result should be given using `abc/de` and `fg/x.php` as arguments for that function. If not, is there an available class? It could also be valuable for splitting paths or removing parts of them. If you have written something, may you share your code here? It is ok to always use `/`, I am coding for Linux only. In Python there is `os.path.join`, which is great.
> Since this seems to be a popular question and the comments are filling with "features suggestions" or "bug reports"... All this code snippet does is join two strings with a slash without duplicating slashes between them. That's all. No more, no less. It does not evaluate actual paths on the hard disk nor does it actually keep the beginning slash (add that back in if needed, at least you can be sure this code always returns a string *without* starting slash). ``` join('/', array(trim("abc/de/", '/'), trim("/fg/x.php", '/'))); ``` The end result will always be a path with no slashes at the beginning or end and no double slashes within. Feel free to make a function out of that. EDIT: Here's a nice flexible function wrapper for above snippet. You can pass as many path snippets as you want, either as array or separate arguments: ``` function joinPaths() { $args = func_get_args(); $paths = array(); foreach ($args as $arg) { $paths = array_merge($paths, (array)$arg); } $paths = array_map(create_function('$p', 'return trim($p, "/");'), $paths); $paths = array_filter($paths); return join('/', $paths); } echo joinPaths(array('my/path', 'is', '/an/array')); //or echo joinPaths('my/paths/', '/are/', 'a/r/g/u/m/e/n/t/s/'); ``` :o)
``` function join_paths() { $paths = array(); foreach (func_get_args() as $arg) { if ($arg !== '') { $paths[] = $arg; } } return preg_replace('#/+#','/',join('/', $paths)); } ``` My solution is simpler and more similar to the way Python os.path.join works Consider these test cases ``` array my version @deceze @david_miller @mark ['',''] '' '' '/' '/' ['','/'] '/' '' '/' '/' ['/','a'] '/a' 'a' '//a' '/a' ['/','/a'] '/a' 'a' '//a' '//a' ['abc','def'] 'abc/def' 'abc/def' 'abc/def' 'abc/def' ['abc','/def'] 'abc/def' 'abc/def' 'abc/def' 'abc//def' ['/abc','def'] '/abc/def' 'abc/def' '/abc/def' '/abc/def' ['','foo.jpg'] 'foo.jpg' 'foo.jpg' '/foo.jpg' '/foo.jpg' ['dir','0','a.jpg'] 'dir/0/a.jpg' 'dir/a.jpg' 'dir/0/a.jpg' 'dir/0/a.txt' ```
How to join filesystem path strings in PHP?
[ "", "php", "string", "file", "" ]
Are there any good alternatives for [Lucene .NET](http://incubator.apache.org/lucene.net) to use in a ASP.NET website? I want to index XML-, TXT-, PDF- and DOC-files. Thanks!
This is late, but i think that Lucene.Net is now compatible with Medium Trust see about midway in this post : <http://blogs.taiga.nl/martijn/2009/06/24/new-adventures-under-medium-trust/> **Update** Adding this note for anyone else who finds this : The final resolution of the issue is noted below. Short version : Lucene.Net officially runs under Medium Trust. <http://issues.apache.org/jira/browse/LUCENENET-169>
I couldn't say if this is better than Lucene.NET but you might want to look at <https://searcharoo.codeplex.com/>.
Good Lucene .NET alternative for ASP.NET website
[ "", "c#", "asp.net", "lucene.net", "" ]
Trying to write a Java program capable of running a UNIX command as a different UNIX user. I have the user's password, and I know the command I want to run, but the command has to be run as that user - so I have to login as that user first. For example: say we have a user, jim, who wants to see what's in bob's home directory, and (for whatever reason) jim has access to execute ls whereas bob does not. **We are currently logged in as bob**. Here is what we (could) do: ``` bob@host$ su jim && ls ~bob ``` Problem is, we get prompted for jim's password. Since this is run from a Java program, i.e. ``` Process p = Runtime.getRuntime().exec("su jim && ls ~bob"); ``` we get prompted for jim's password and hung up. *We know jim's password*. However, I can't enter it. Additionally, we can't use an Expect script (don't have it installed) and we can't become the superuser. I also looked into using SSH to try this, since we could technically do ``` bob@host$ ssh jim@host "ls ~bob" ``` but this also doesn't work since I don't have permission to setup passwordless SSH. My last-ditch effort is to try and use an SSH library for Java, since the password is available to the Java program and I would be able to login with that (and execute the proper command). But since I'm going to be running on the same host, it seems like overkill. Any suggestions? P.S: Java version 1.4.2, can't upgrade; AIX UNIX 5.3.
Problem solved. Used JSch (<http://www.jcraft.com/jsch/>) to SSH into the server with known username and password, and execute command. Thanks all for your suggestions!
Have sudo installed, have the user running the Java program entered in /etc/sudoers for the commands in question, and use `sudo -u jim ls ~bob`.
Running UNIX commands as different user, from Java
[ "", "java", "unix", "ssh", "passwords", "aix", "" ]
Is it possible in C# to something like the following ``` foreach (ref string var in arr) { var = "new value"; } ``` so that var variable was treated as reference and assigning to var would change an array element?
There is no such construct for **updating** a loop; an iterator is read-only. For example, the following provides a perfectly valid iterator: ``` public IEnumerable<int> Get1Thru5() { yield return 1; yield return 2; yield return 3; yield return 4; yield return 5; } ``` How would it update? **What** would it update? If the data is an array/list/etc, then something like: ``` for(int i = 0 ; i < arr.Length ; i++) { arr[i] = "new value"; } ``` Or other options depending on the specific container. --- Update; at a **push**, an extension method: ``` public static void UpdateAll<T>(this IList<T> list, Func<T, T> operation) { for (int i = 0; i < list.Count; i++) { list[i] = operation(list[i]); } } static void Main() { string[] arr = { "abc", "def", "ghi" }; arr.UpdateAll(s => "new value"); foreach (string s in arr) Console.WriteLine(s); } ```
No. The `foreach` statement is simply syntax sugar on top of the [`IEnumerable`](http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx) interface. This interface defines a method to get en [`IEnumerator`](http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx) which in turn has methods to do *read-only* enumeration: * Current : object * MoveNext() : bool * Reset() : void
C# reference to loop variable
[ "", "c#", "reference", "" ]
I want to port an small open source AES encryption class to Android, and it would cut my work down a lot if the API of Android is as close as possible to the Java 6 API. How much is implemented (or referenceable), as I have tried searching about this on google, and i have not yet come up with anything useful?
IMHO In general Java 6 works. The compiler does the work for you. Re self implementing encryption: Please try using [Bouncy Castle](http://www.bouncycastle.org/). In general, self implementation of any known crypto algorithm isn't a good idea.
Have you checked the Java library reference on <http://developer.android.com/reference/> ?
How much of the Java 6 API is implemented by Android?
[ "", "java", "android", "" ]
I am trying to achieve an LDAP query to gather all properties we have about our users without specifying the properties before hand, I would like to display this in a table so used the below code. This works if I uncomment the search.PropertiesToLoad.Add("cn"); line and will display any other properties I add in the same way but not when I do a full search for all properties. ``` DirectoryEntry myLdapConnection = createDirectoryEntry(); DirectorySearcher search = new DirectorySearcher(myLdapConnection); search.CacheResults = true; //search.PropertiesToLoad.Add("cn"); SearchResultCollection allResults = search.FindAll(); DataTable resultsTable = new DataTable("Results"); //add columns for each property in results foreach (string colName in allResults.PropertiesLoaded) resultsTable.Columns.Add(colName, colName.GetType()); //loop to add records to DataTable foreach (SearchResult result in allResults) { int tmp = result.Properties.Count; DataRow row = resultsTable.NewRow(); foreach (string columnName in search.PropertiesToLoad) { if (columnName.Equals("lastlogon")) { if (result.Properties.Contains(columnName)) row[columnName] = ConvertDate(result.Properties[columnName].ToString()); else row[columnName] = ""; } else { if (result.Properties.Contains(columnName)) row[columnName] = result.Properties[columnName][0].ToString(); else row[columnName] = ""; } } resultsTable.Rows.Add(row); } gridResults.DataSource = resultsTable; ``` The problem seems to be with ``` foreach (string colName in allResults.PropertiesLoaded) resultsTable.Columns.Add(colName, colName.GetType()); ``` I expected this to loop all properties when no PropertiesToLoad had been specified but it doesn't is their a way to achieve what I want to. I know I need a few try catches and other bits in the code as of yet, it's a rough draft.
This can be done using `DirectoryEntry`, but I don't think the `SearchResultCollection` has all fields. Try to create a `DirectoryEntry` for every search result, it should have all active directory properties: ``` DirectoryEntry entry = result.GetDirectoryEntry(); ``` Also, note that in the active directory every property can have multiple values (like the MemberOf field), so you'll have to iterate them as well. I've wrote a similar method, but I chose a `List` with keys/values (it seemed more manageable over WCF. `ILookup` would be optimal, but I couldn't get it to work here). Here it is, stripped from try/catch/using ``` var list = new List<KeyValuePair<string, string>>(); foreach (PropertyValueCollection property in entry.Properties) foreach (object o in property) { string value = o.ToString(); list.Add(new KeyValuePair<string, string>(property.PropertyName, value)); } ```
You can iterate through all properties this way: ``` foreach (SearchResult searchResult in allResults) { foreach (string propName in searchResult.Properties.PropertyNames) { ResultPropertyValueCollection valueCollection = searchResult.Properties[propName]; foreach (Object propertyValue in valueCollection) { Console.WriteLine("Property: " + propName + ": " + propertyValue.ToString()); } } } ``` Is that what you need?
Active Directory Display all properties in a table
[ "", "c#", "active-directory", "" ]
I wonder if there are any game engine written in Scala or easily accesible from Scala?
All the Java gaming engines are easily accessible due to easy Java integration. There are several (not sorted in any way): * <http://www.jmonkeyengine.com/> * <http://www.13thmonkey.org/~boris/jgame/> * <https://jge.dev.java.net/> * <http://www.lwjgl.org/> * <https://sourceforge.net/projects/tjger/> A good presentation how to start coding a game in Java is [Write a 3-D Game in the Java Programming Language in Less Than 50 Minutes](http://web.archive.org/web/20100813121923/http://jsolutions.se/DukeBeanEm/) that applies as well. As [Scala has a nice Java integration](http://www.codecommit.com/blog/java/interop-between-java-and-scala) the ointerop should be easy. As mcherm pointed out, for [lwjgl this has already been done](http://oblong-code.blogspot.com/2008/01/so-wending-slowly-through-scala-has.html). To have the nice Scala feel you could add some [implicit conversions](http://www.artima.com/weblogs/viewpost.jsp?thread=179766).
I am currently working on a 3d engine in Scala: <http://www.sgine.org> It still has a long way to go before it's a competitor to the major Java engines out there, but good progress is being made and more help is always appreciated. :)
Is there any game engine in Scala?
[ "", "java", "scala", "game-engine", "" ]
I just cannot imaginate a way to do a call to a function with genericity. I have a code which a have to call a function in two different classes in different moments. I have A and B classes which I can access one time or other time. Or I access A or I access B. Not both in the same type. I have code this program but I just cannot imagine how to do this. Or if this is good for performance or codding. I just want to eliminate the C class but I don't know how. Any idea? ``` class MyClass { public: MyClass() {} //contructor padrão, não deve ser utilizado isoladamente virtual int a() = 0; virtual int b() = 0; int c() { return b(); } }; class A : public MyClass { public: int a() { return 1; } int b() { return 1; } int d() { return 1; } }; class B : public MyClass { public: int a() { return 1; } int b() { return 1; } int e() { return 1; } }; class C { public: A ca; B cb; enum TIPO { A, B }; TIPO Tipo; C(TIPO tipo) { Tipo = tipo; } int a() { switch(Tipo) { case A: return ca.a(); break; case B: return cb.b(); break; default: break; } } }; void main() { C c(C::B); c.a(); return; } ```
As you've written 'A' and 'B', you don't actually need the C class. By declaring your member functions "virtual" you are using run time polymorphism and this will result in the "correct" functions being called: ``` void foo (MyClass & mc) { mc.a (); } int main () { A a; B b; foo (a); // 'mc.a()' will call 'A::a' foo (b); // 'mc.a()' will call 'B::a' } ``` Is there some other reason that you need to inherit from C?
If I understand you correctly, you are trying to eliminate the members (ca,cb), and just call the appropriate base class method. If that's the case, it can be done by using: ``` switch(Tipo) { case A: return A::a(); case B: return B::a(); } ``` However, I would recommend revisiting your design. Typically, situations like this can often be handled by rethinking/reworking the class design so that there is a single base class or interface which defines a(), and instead of creating one concrete class with 2 base classes, create one of two specific, concrete classes derived from a single base class. There is no need for multiple inheritance here. (This is especially true since you know the type at construction time.)
Call different classes in different time in same function
[ "", "c++", "class", "" ]
How can I get the title of an HTML page with JavaScript?
Use `document.title`: ``` console.log(document.title) ``` ``` <title>Title test</title> ``` [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Document/title)
Put in the URL bar and then click enter: ``` javascript:alert(document.title); ``` You can select and copy the text from the alert depending on the website and the web browser you are using.
How to get the title of HTML page with JavaScript?
[ "", "javascript", "html", "dom", "title", "" ]
I was just wondering when you have for example: ``` var dir = new DirectoryInfo(@"C:\Temp"); ``` Is there an easier/clearer way to add a new file to that directory than this? ``` var file = new FileInfo(Path.Combine(dir.FullName, "file.ext")); ``` I'm thinking I can probably just make an extension method or something, but curious if something already exists that can't see here... I mean the `DirectoryInfo` does have `GetFiles()` method for example.
What is it that you want to do? The title says "Creating a new file". A FileInfo object is not a file; it's an object holding information about a file (that may or may not exist). If you actually want to *create* the file, there are a number of ways of doing so. One of the simplest ways would be this: ``` File.WriteAllText(Path.Combine(dir.FullName, "file.ext"), "some text"); ``` If you want to create the file based on the `FileInfo` object instead, you can use the following approach: ``` var dir = new DirectoryInfo(@"C:\Temp"); var file = new FileInfo(Path.Combine(dir.FullName, "file.ext")); if (!file.Exists) // you may not want to overwrite existing files { using (Stream stream = file.OpenWrite()) using (StreamWriter writer = new StreamWriter(stream)) { writer.Write("some text"); } } ``` As a side note: it is `dir.FullName`, not `dir.FullPath`.
Why don't you use: ``` File.Create(@"C:\Temp\file.ext"); ``` or ``` var dir = new DirectoryInfo(@"C:\Temp"); File.Create(dir.FullName + "\\file.ext"); ```
C#: Creating a new FileInfo in a directory that you have the DirectoryInfo of
[ "", "c#", "file", "directory", "" ]
I have the following JSON structure: ``` [{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }] ``` How do I iterate over it using JavaScript?
Taken from [jQuery docs](http://docs.jquery.com/Utilities/jQuery.each): ``` var arr = [ "one", "two", "three", "four", "five" ]; var obj = { one:1, two:2, three:3, four:4, five:5 }; jQuery.each(arr, function() { $("#" + this).text("My id is " + this + "."); return (this != "four"); // will stop running to skip "five" }); jQuery.each(obj, function(i, val) { $("#" + i).append(document.createTextNode(" - " + val)); }); ```
``` var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}]; for (var i = 0; i < arr.length; i++){ document.write("<br><br>array index: " + i); var obj = arr[i]; for (var key in obj){ var value = obj[key]; document.write("<br> - " + key + ": " + value); } } ``` note: the for-in method is cool for simple objects. Not very smart to use with DOM object.
How do I iterate over a JSON structure?
[ "", "javascript", "json", "loops", "" ]
I know following is the way to use unicode in C# ``` string unicodeString = "\u0D15"; ``` In my situation, I will not get the character code (*0D15*) at compile time. I get this from a XML file at runtime. I wonder how do I convert this code to unicode string? I tried the following ``` // will not compile as unrecognized escape sequence string unicodeString = "\u" + codeFromXML; // will compile, but just concatenates u with the string got from XML file. string unicodeString = "\\u" + codeFromXML; ``` How do I handle this situation? Any help would be great!
You want to use the [char.ConvertFromUtf32](http://msdn.microsoft.com/en-us/library/system.char.convertfromutf32.aspx) function. ``` string codePoint = "0D15"; int code = int.Parse(codePoint, System.Globalization.NumberStyles.HexNumber); string unicodeString = char.ConvertFromUtf32(code); // unicodeString = "ക" ```
Here's an NUnit test showing arul and Adrian's solution - note that one solution starts with input in a string, while with the other solution the input starts in just a char. ``` [Test] public void testConvertFromUnicode() { char myValue = Char.Parse("\u0D15"); Assert.AreEqual(3349, myValue); char unicodeChar = '\u0D15'; string unicodeString = Char.ConvertFromUtf32(unicodeChar); Assert.AreEqual(1, unicodeString.Length); char[] charsInString = unicodeString.ToCharArray(); Assert.AreEqual(1, charsInString.Count()); Assert.AreEqual((int) '\u0D15', charsInString[0]); } ```
Getting unicode string from its code - C#
[ "", "c#", "unicode", "string-concatenation", "" ]
What is java's equivalent of [ManualResetEvent](http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx)?
The closest I know of is the [Semaphore](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Semaphore.html). Just use it with a "permit" count of 1, and acquire/release will be pretty much the same as what you know from the `ManualResetEvent`. > A semaphore initialized to one, and > which is used such that it only has at > most one permit available, can serve > as a mutual exclusion lock. This is > more commonly known as a binary > semaphore, because it only has two > states: one permit available, or zero > permits available. When used in this > way, the binary semaphore has the > property (unlike many Lock > implementations), that the "lock" can > be released by a thread other than the > owner (as semaphores have no notion of > ownership). This can be useful in some > specialized contexts, such as deadlock > recovery.
``` class ManualResetEvent { private final Object monitor = new Object(); private volatile boolean open = false; public ManualResetEvent(boolean open) { this.open = open; } public void waitOne() throws InterruptedException { synchronized (monitor) { while (open==false) { monitor.wait(); } } } public boolean waitOne(long milliseconds) throws InterruptedException { synchronized (monitor) { if (open) return true; monitor.wait(milliseconds); return open; } } public void set() {//open start synchronized (monitor) { open = true; monitor.notifyAll(); } } public void reset() {//close stop open = false; } } ```
What is java's equivalent of ManualResetEvent?
[ "", "java", ".net", "multithreading", "synchronization", "" ]
I've never done a Java Web start application before. I wrote my app's JNLP files and published them along with all the JARs to my Web server. However, after getting the initial splash screen where JWS loads the libraries, nothing happens. Do you have any suggestions on how to debug this, perhaps get some console output? I've tried cleaning the cache through "javaws -uninstall" but it doesn't help. Any suggestion is appreciated.
In the Java Console you should enable full tracing and logging. This will tell you a lot about what happens under the covers when Web Start doesn't work. See <http://java.sun.com/javase/6/docs/technotes/guides/deployment/deployment-guide/tracing_logging.html> Hopefully this can get you started.
In the Java Control Panel, select Advanced > Java console > Show console. You will probably see some exception output. If the process is still running, you should be able to find it with `jps` from the command line.
Nothing happens after starting a Java Web start app
[ "", "java", "" ]
In my application I build an XML file with this code using **StringBuilder**: ``` StringBuilder sb = new StringBuilder(); sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine); sb.Append(String.Format("<{0}>{1}", _pluralCamelNotation, Environment.NewLine)); for (int index = 0; index < 3; index++) { sb.Append(String.Format("\t<{0}>{1}", _singularCamelNotation, Environment.NewLine)); foreach (DataType dataType in _allDataTypes) { sb.Append(String.Format("\t\t<{0}>{2}</{0}>{1}", dataType.CamelCaseNotation, Environment.NewLine, dataType.GetDummyData())); } sb.Append(String.Format("\t</{0}>{1}", _singularCamelNotation, Environment.NewLine)); } sb.Append(String.Format("</{0}>{1}", _pluralCamelNotation, Environment.NewLine)); return sb.ToString(); ``` How can I do the same thing with **LINQ**, something like this: ``` PSEUDO-CODE: var xdoc = new XDocument( new XDeclaration("1.0", "utf-8", null), for (int index = 0; index < 3; index++) { new XElement(_pluralCamelNotation, _allDataTypes.Select(datatype => new XElement(_singularCamelNotation, new XElement(datatype.CamelCaseNotation, datatype.GetDummyData()) )) ) } ); ```
Even without LINQ, you shouldn't write xml via concatenation... `XmlWriter` would be a good fit: ``` XmlWriterSettings settings = new XmlWriterSettings(); settings.NewLineHandling = NewLineHandling.Entitize; settings.Indent = true; settings.IndentChars = "\t"; StringBuilder sb = new StringBuilder(); using (XmlWriter xw = XmlWriter.Create(sb, settings)) { xw.WriteStartDocument(); xw.WriteStartElement(_pluralCamelNotation); for (int i = 0; i < 3; i++) { xw.WriteStartElement(_singularCamelNotation); foreach (DataType dataType in _allDataTypes) { xw.WriteElementString(dataType.ToString(), dataType.GetDummyData()); } xw.WriteEndElement(); } xw.WriteEndElement(); xw.WriteEndDocument(); xw.Close(); } ``` You can use `XmlWriterSettings` to control things like line spacing. Alternatively, with LINQ-to-XML: ``` XDocument doc = new XDocument( new XDeclaration("1.0", null, null), new XElement(_pluralCamelNotation, Enumerable.Range(1,3).Select( i => new XElement(_singularCamelNotation, _allDataTypes.Select( dataType => new XElement( dataType.ToString(), dataType.GetDummyData()) ) )))); string t = doc.ToString(); ```
This is one area that VB.Net wins over C# with it use of XML literals. Look at this code taken from <http://blogs.msdn.com/jimoneil/archive/2009/06/15/x-is-for-xml-literal.aspx>. Ain't that beautiful? ``` Dim xml = <?xml version="1.0"?> <menu> <course name="appetizer"> <%= From m In menu _ Where m.Course = "appetizer" _ Select <dish><%= m.Food %></dish> _ %> </course> <course name="main"> <%= From m In menu _ Where m.Course = "main" _ Select <dish><%= m.Food %></dish> _ %> </course> <course name="dessert"> <%= From m In menu _ Where m.Course = "dessert" _ Select <dish><%= m.Food %></dish> _ %> </course> </menu> ```
How can I change this StringBuilder-to-XML code to LINQ-to-XML?
[ "", "c#", "linq", "stringbuilder", "" ]
I am having trouble drawing a line within a group box in a simple windows form. here is my code: ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); DrawLShapeLine(groupBox1.CreateGraphics(), 10, 10, 20, 40); } public void DrawLShapeLine(System.Drawing.Graphics g, int intMarginLeft, int intMarginTop, int intWidth, int intHeight) { Pen myPen = new Pen(Color.Black); myPen.Width = 2; // Create array of points that define lines to draw. int marginleft = intMarginLeft; int marginTop = intMarginTop; int width = intWidth; int height = intHeight; int arrowSize = 3; Point[] points = { new Point(marginleft, marginTop), new Point(marginleft, height + marginTop), new Point(marginleft + width, marginTop + height), // Arrow new Point(marginleft + width - arrowSize, marginTop + height - arrowSize), new Point(marginleft + width - arrowSize, marginTop + height + arrowSize), new Point(marginleft + width, marginTop + height) }; g.DrawLines(myPen, points); } } ``` If I attach the DrawLShapeLine method to a button click event, it draws fine, but it does not draw on load of the form. Please advice.
Hook up an event handler for the `Paint` event of the `GroupBox` and call `DrawLShapeLine` from within that event handler instead. You should then use the `Graphics` object supplied by in event arguments: ``` private void groupBox1_Paint(object sender, PaintEventArgs e) { DrawLShapeLine(e.Graphics, 10, 10, 20, 40); } ``` As your code looks now it will attempt to paint in the `GroupBox` when the form requires painting. The group box may be painted at any other occasion, which will the line you paint disappear.
Quick & dirty: How about creating a panel with the width of 1 pixel and give it a backgroundcolor?
Drawing a line in Winforms
[ "", "c#", ".net", "winforms", "system.drawing", "" ]
I have an application written in .NET. I would like to add the ability for users to control my application by using a mouse, e.g. a high end gaming mouse, with 10-15 buttons on it. Is this going to be easy to do, or will I need a mouse vendor with a .NET SDK that I can use - can you recommend any? I would like all control to be within my application and just use the mouse vendors driver.
Correct me if I am wrong, but don't all these extra buttons on mice normally map to some sort of keyboard combination (often there is a control pannel app that lets you specify which button mapps to what). If this is the case you should be able to capture button four and above using the KeyDown, and KeyUp events.
In windows, whenever you press *something*, it gets through the win32 message queue. [Here is some code to check how to retrieve those messages](http://blogs.msdn.com/csharpfaq/archive/2004/10/20/245412.aspx) Now (you will of course need a 15 buttons mouse), brake point or Console::writeline or whatever inside that code, press a mouse button and bang, you can get the message number which was just pressed. Afterwards, you could check if you can bind those keypress on normal events handlers. Note that the solution about controling vendor hardware is not very portable. Suppose that everyone has microsoft mice, but I decide to buy a 20 buttons mouse from lets say Hong-Kong, you'll have to write new code to support that. I think you should aim at very generic solutions
Mouse control in C#
[ "", "c#", ".net", "mouse", "game-development", "" ]
I have 2 StringCollections: ``` StringCollection ParameterIDs StringCollection ParameterValues ``` Is it able to map these both StringCollections as DataSource, something like: ``` repeater.DataSource = ParameterIDs (as row1) + ParameterValues (as row2); repeater.DataBind(); ``` and use them in repeater like: ``` <asp:Repeater ID="repeatParameters" runat="server"> <HeaderTemplate> <table> </HeaderTemplate> <ItemTemplate> <tr> <td class="formLabel"> <asp:Label ID="lblParameterID" Text="<% #DataBinder.Eval(Container.DataItem,"ParameterIDs") %>" runat="server" MaxLength="50"></asp:Label><br /> </td> <td class="formInputText"> <asp:Label ID="lblParameterValue" Text="<%#DataBinder.Eval(Container.DataItem,"ParameterValues") %>" runat="server" MaxLength="50"></asp:Label><br /> </td> </tr> <tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> ```
This will do exactly what you want, providing you are using .NET 3.5: ``` StringCollection parameterIds = new StringCollection(); StringCollection parameterValues = new StringCollection(); parameterIds.Add("someID"); parameterValues.Add("someValue"); var dataSource = parameterIds.Cast<string>() .SelectMany(itemOne => parameterValues .Cast<string>(), (itemOne, item2) => new { Row1 = itemOne, Row2 = item2 }); repeater.DataSource = dataSource; repeater.DataBind(); ``` Like Bogdan\_Ch has said, I recommend you move away from `StringCollection` to `List<string>` if you are using .NET 2.0 and above. Doing that has the added advantage that you don't need to use the `Cast` extension method.
First thought: Mash them up in a [Dictionary](http://msdn.microsoft.com/en-us/library/xfhwa508.aspx) and use that as a datasource. Second thought: Create a [DataSet](http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx) with the values you need. Third thought: Use [KeyValuePair](http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx). As you see there are a lot of different ways of doing this but all of them share a common element: Create a single object which stores and maps the corresponding values.
C# Repeater.DataSource from 2 StringCollections
[ "", "c#", "repeater", "datasource", "" ]
What I would like to get some input on is how to remove certain characters from a textbox (or textarea) with JQuery. I have the code in C# but I can´t seem to translate that to JQuery javascript. My problem is that I don´t know how to get the value from a textbox as a character array which I then can loop through and compare against a given set of unwanted characters. This is how "far" I have come in JQuery: ``` $("input[type=text], textarea").change(function() { // code here }); ``` This is my code in C#: ``` for (int i = 0; i < charArray.Length; i++) { current = charArray[i]; if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF)) || ((current >= 0xE000) && (current <= 0xFFFD))) _validXML.Append(current); } return _validXML.ToString().TrimEnd((char)32, (char)160) ; ``` **UPDATE:** I went with a combination of some answers below (I will upvote them) and my final JQuery looks like this and works: ``` $(document).ready(function() { $(":text, textarea").change(function() { var text = ""; var arr = $(this).val() $.each(arr, function(i) { var c = arr.charCodeAt(i); if ((c == 0x9) || (c == 0xA) || (c == 0xD) || (c >= 0x20 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD)) { text += arr.charAt(i); } }); $(this).val(text); }); }); ``` Thanks all!
Textarea: ``` <textarea id="item" name="item" rows="5" cols="80">Some text in here</textarea> ``` jQuery code: ``` var text = $('#item').val(); var newtext = ""; for (var i = 0; i < text.length; i++) { var c = text.charCodeAt(i); if ((c == 0x9) || (c == 0xA) || (c == 0xD) || (c >= 0x20 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD)) { newtext += text[i]; } } $('#item').val(newtext); ``` This has actually very little to do with jQuery, methinks, except to access the text data and set it again.
Would't this be the case for regular expressions, like: ``` $("input[@type='text'], textarea").change(function() { this.value = this.value.replace(/[^\w\d]+/gim,""); }); ```
Removing unwanted characters from textbox with JQuery
[ "", "javascript", "jquery", "" ]
Should you place the `@Transactional` in the `DAO` classes and/or their methods or is it better to annotate the Service classes that are using the DAO objects? Or does it make sense to annotate both layers?
I think transactions belong on the service layer. It's the one that knows about units of work and use cases. It's the right answer if you have several DAOs injected into a service that need to work together in a single transaction.
In general I agree with the others stating that transactions are usually started on the service level (depending on the granularity that you require of course). However, in the mean time I also started adding `@Transactional(propagation = Propagation.MANDATORY)` to my DAO layer (and other layers that are not allowed to start transactions but require existing ones) because it is much easier to detect errors where you have forgotten to start a transaction in the caller (e.g. the service). If your DAO is annotated with mandatory propagation you will get an exception stating that there is no active transaction when the method is invoked. I also have an integration test where I check all beans (bean post processor) for this annotation and fail if there is a `@Transactional` annotation with propagation other than Mandatory in a bean that does not belong to the services layer. This way I make sure we do not start transactions on the wrong layer.
Where does the @Transactional annotation belong?
[ "", "java", "spring", "annotations", "transactions", "dao", "" ]
i need to understand html + css files and convert it to somthing like rtf layot in java now i understand i need somekind of html parser but what i need to do from there ? how can i implement html-css convertor ? is there somekind of patern or method for such jobs?
I'd do the following: 1. At first use JTidy to convert HTML to valid XHTML 2. Apply an XSLT to convert to RTF using an XML library like Saxon or Xerces Note: although I didn't find an xsl file for that conversion directly I'm sure there is one anywhere
You should check out HTMLEditorKit. It provides some support for CSS rendering. There is also an RTFEditorKit for writing, although it is not entirely reliable (last I checked, several years ago). Is there a reason you need to use Java instead of just loading the HTML in Word (or some other editor) and saving it as RTF? Also check [this W3C link](http://www.w3.org/Tools/html2things.html).
java parse html + css and convert the output to different lang
[ "", "java", "html-parsing", "converters", "" ]
Given two identical `boost::variant` instances **`a`** and **`b`**, the expression **`( a == b )`** is permitted. However **`( a != b )`** seems to be undefined. Why is this?
I think it's just not added to the library. The Boost.Operators won't really help, because either variant would have been derived from boost::operator::equality\_comparable. David Pierre is right to say you can use that, but your response is correct too, that the new operator!= won't be found by ADL, so you'll need a using operator. I'd ask this on the boost-users mailing list. **Edit from @AFoglia's comment:** Seven months later, and I'm studying Boost.Variant, and I stumble over this better explanation of the omission lists. <http://boost.org/Archives/boost/2006/06/105895.php> `operator==` calls `operator==` for the actual class currently in the variant. Likewise calling `operator!=` should also call `operator!=` of the class. (Because, theoretically, a class can be defined so `a!=b` is not the same as `!(a==b)`.) So that would add another requirement that the classes in the variant have an `operator!=`. (There is a debate over whether you can make this assumption in the mailing list thread.)
This is [a link to the answer from the author himself](http://lists.boost.org/Archives/boost/2006/06/105895.php) when this question was formulated on boost mailing list Summarizing it, in the author opinion, implementing comparison operators (!= and <) would add more requirements on the types used to create the variant type. I don't agree with his point of view though, since != can be implemented in the same way as ==, without necessarily hiding the possible implementations of these operators for each of the types making up the variant
Why does boost::variant not provide operator !=
[ "", "c++", "boost-variant", "" ]
I want to do this in C#, but I don't know how: I have a string with a class name -e.g: `FooClass` and I want to invoke a (static) method on this class: ``` FooClass.MyMethod(); ``` Obviously, I need to find a reference to the class via reflection, but how?
You will want to use the [`Type.GetType`](http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx) method. Here is a very simple example: ``` using System; using System.Reflection; class Program { static void Main() { Type t = Type.GetType("Foo"); MethodInfo method = t.GetMethod("Bar", BindingFlags.Static | BindingFlags.Public); method.Invoke(null, null); } } class Foo { public static void Bar() { Console.WriteLine("Bar"); } } ``` I say *simple* because it is very easy to find a type this way that is internal to the same assembly. Please see [Jon's answer](https://stackoverflow.com/questions/1044455/c-reflection-how-to-get-class-reference-from-string/1044472#1044472) for a more thorough explanation as to what you will need to know about that. Once you have retrieved the type my example shows you how to invoke the method.
You can use [`Type.GetType(string)`](http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx), but you'll need to know the *full* class name including namespace, and if it's not in the current assembly or mscorlib you'll need the assembly name instead. (Ideally, use [`Assembly.GetType(typeName)`](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.gettype) instead - I find that easier in terms of getting the assembly reference right!) For instance: ``` // "I know String is in the same assembly as Int32..." Type stringType = typeof(int).Assembly.GetType("System.String"); // "It's in the current assembly" Type myType = Type.GetType("MyNamespace.MyType"); // "It's in System.Windows.Forms.dll..." Type formType = Type.GetType ("System.Windows.Forms.Form, " + "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, " + "PublicKeyToken=b77a5c561934e089"); ```
C# Reflection: How to get class reference from string?
[ "", "c#", "reflection", "" ]
I want to implement a function in the base class but I also want it to be overridden in the derived classes *every time*. So it is more like "abstract function but with a body". What am I looking for? Am I looking for the right thing?
If the base-class has something to say, but you want it overridden "every time", then I would have a pair of methods: ``` public void DoSomething() { //things to do before DoSomethingCore(); //things to do after } protected abstract void DoSomethingCore(); ```
If your base class does *something* in the method, but you want to make sure that every subclass is forced to implement some part of the method, then you want the [Template Method pattern](http://en.wikipedia.org/wiki/Template_method_pattern), as described in Marc Gravell's answer. There's no way to provide a default implementation in your base class and still force subclasses to provide their own implementation. You could however create an abstract base class and inherit from it to provide the default implementation, but make that concrete class sealed. ``` public abstract class FooBase { public abstract void DoStuff(); } public sealed class FooImpl : FooBase { public override void DoStuff { //default widget-munging code } } ``` Now any classes which inherit from FooBase have to implement DoStuff(), but you have a default implementation FooImpl from which subclasses may not inherit. You might also prefer to delegate the responsibility for implementing the method to a separate class, which is passed to the base class in its constructor. That's called the [Strategy pattern](http://en.wikipedia.org/wiki/Strategy_pattern). ``` public sealed class Foo { private IFooStrategy _strategy; public Foo(IStrategy strategy) { _strategy = strategy; } void DoStuff() { _strategy.DoStuff(); } public static IFooStrategy DefaultStrategy { //return singleton instance of the default strategy } } ``` Now instead of subclassing Foo, you instead create new implementations of the IFooStrategy interface, and pass those to your Foo instance. So you could either do: ``` new Foo(Foo.DefaultStrategy); ``` or ``` new Foo(new DifferentStrategy()); ```
Method has to be overridden but isn't abstract?
[ "", "c#", "inheritance", "" ]
Is there any programming language (or type system) in which you could express the following Python-functions in a statically typed and type-safe way (without having to use casts, runtime-checks etc)? `#1`: ``` # My function - What would its type be? def Apply(x): return x(x) # Example usage print Apply(lambda _: 42) ``` `#2`: ``` white = None black = None def White(): for x in xrange(1, 10): print ("White move #%s" % x) yield black def Black(): for x in xrange(1, 10): print ("Black move #%s" % x) yield white white = White() black = Black() # What would the type of the iterator objects be? for it in white: it = it.next() ```
**1#** This is not typeable with a finite type. This means that very few (if any) programming languages will be able to type this. However, as you have demonstrated, there is a specific type for x that allows the function to be typed: ``` x :: t -> B ``` Where `B` is some concrete type. This results in `apply` being typed as: ``` apply :: (t -> B) -> B ``` Note that Hindley-Milner will not derive this type. **2#** This is easy to represent in Haskell (left as an exercise to the reader...)
I found a Haskell solution for **#1** using [Rank-N-Types](http://en.wikibooks.org/wiki/Haskell/Polymorphism) (just for GHCi) ``` {-# LANGUAGE RankNTypes #-} apply :: (forall a . a -> r) -> r apply x = x x apply $ const 42 -- Yields 42 ```
How to make these dynamically typed functions type-safe?
[ "", "python", "language-agnostic", "type-theory", "" ]
OK, I've been looking into this a few days and am not particularly sure what I am doing wrong. If anyone has working examples of using jqGrid with C#/ASP.NET and open source tools, please, please let me know where to find them. Any tips on finding decent documentation or tools I could use to debug this would be most appreciated too (I'm pretty new to js/jQuery). Basically I just need the edit-in-place functionality, so if I'm overlooking another obvious solution for that, it could be helpful to know... I'd like to avoid using AJAX.NET if at all possible. I feel like I'm just overlooking something really obvious here. In the following example, I do get the jqGrid to display, but it shows no data. Here is the relevant JavaScript: ``` jQuery(document).ready(function(){ jQuery("#role_assignment_table").jqGrid({ url:'http://localhost:4034/WebSite2/PageItemHandler.asmx/GetPageItemRolesJson?id=3', mtype: 'GET', contentType: "application/json; charset=utf-8", datatype: "jsonstring", colModel:[ {name:'Id', label:'ID', jsonmap:'Id'}, {name:'Title', jsonmap:'Title'}, {name:'AssignedTo', label:'Assigned To', jsonmap:'AssignedTo'}, {name:'Assigned', jsonmap:'Assigned'}, {name:'Due', jsonmap:'Due'}, {name:'Completed', jsonmap:'Completed'} ], jsonReader: { page: "Page", total: "Total", records: "Records", root: "Rows", repeatitems: false, id: "Id" }, rowNum:10, rowList:[10,20,30], imgpath: 'js/themes/basic/images', viewrecords: false, caption: "Role Assignments" }); }); ``` --- **The HTML:** ``` <table id="role_assignment_table" class="scroll" cellpadding="0" cellspacing="0" /> ``` --- **The generated JSON:** I'm not sure if it makes it to the jqGrid, or if the jqGrid doesn't like my JSON or my WebMethod, but I can call it myself when I go to the proper URL and get the JSON result string. ``` {"Page":"1","Total":1.0,"Records":"4", "Rows":[ {"Id":1,"Item":null,"Title":"Story Manager","AssignedTo":null,"Assigned":"\/Date(1245186733940-0500)\/","Due":"\/Date(1248383533940-0500)\/","Completed":"\/Date(1247087533940-0500)\/"}, {"Id":2,"Item":null,"Title":"Analysis","AssignedTo":null,"Assigned":"\/Date(1245186733940-0500)\/","Due":"\/Date(1248383533940-0500)\/","Completed":"\/Date(1247087533940-0500)\/"}, {"Id":3,"Item":null,"Title":"Narrative","AssignedTo":null,"Assigned":"\/Date(1245186733940-0500)\/","Due":"\/Date(1248383533940-0500)\/","Completed":"\/Date(1247087533940-0500)\/"}, {"Id":4,"Item":null,"Title":"Graphic","AssignedTo":null,"Assigned":"\/Date(1245186733940-0500)\/","Due":"\/Date(1248383533940-0500)\/","Completed":"\/Date(1247087533940-0500)\/"} ] } ``` Cheers, William Riley-Land
Before doing anything else, download and install this: <http://www.fiddler2.com/fiddler2/> It will let you see exactly what is being requested and sent back by the jqGrid requests to get the JSON data. I have some code for a working jqGrid, and here's something different: ``` datatype: "json" ``` Instead of your: ``` datatype: "jsonstring" ``` I also have a field called `colNames` which is an array of strings containing column names. Finally, I have a `pager` field which identifies an element that will store the paging controls, and is a DIV.
In ASP.NET, Date gets serialized as JSON ["/Date(ticks)/"](http://msdn.microsoft.com/en-us/library/bb299886.aspx) which can not be interpreted by jqGrid. Possible solutions ([post](http://blogs.teamb.com/craigstuntz/2009/04/27/38243/)): * write a custom formatter for the grid * change the data we send to the grid (by sending formatted date as string) **Please tell how did you implement date display with jqGrid ?** Thank You.
How to use jqGrid with C#/ASP.NET and JSON.NET (and no AJAX.NET stuff)?
[ "", "c#", "asp.net", "jquery-plugins", "jqgrid", "json.net", "" ]
I am practising a C# console application, and I am trying to get the function to verify if the number appears in a fibonacci series or not but I'm getting errors. What I did was: ``` class Program { static void Main(string[] args) { System.Console.WriteLine(isFibonacci(20)); } static int isFibonacci(int n) { int[] fib = new int[100]; fib[0] = 1; fib[1] = 1; for (int i = 2; i <= 100; i++) { fib[i] = fib[i - 1] + fib[i - 2]; if (n == fib[i]) { return 1; } } return 0; } } ``` Can anybody tell me what am I doing wrong here?
And here is a solution that beats all of yours! Because, why **iteration** when you have smart **mathematicians** doing **closed-form solutions** for you? :) ``` static bool IsFibonacci(int number) { //Uses a closed form solution for the fibonacci number calculation. //http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression double fi = (1 + Math.Sqrt(5)) / 2.0; //Golden ratio int n = (int) Math.Floor(Math.Log(number * Math.Sqrt(5) + 0.5, fi)); //Find's the index (n) of the given number in the fibonacci sequence int actualFibonacciNumber = (int)Math.Floor(Math.Pow(fi, n) / Math.Sqrt(5) + 0.5); //Finds the actual number corresponding to given index (n) return actualFibonacciNumber == number; } ```
Here's a fun solution using an infinite iterator block: ``` IEnumerable<int> Fibonacci() { int n1 = 0; int n2 = 1; yield return 1; while (true) { int n = n1 + n2; n1 = n2; n2 = n; yield return n; } } bool isFibonacci(int n) { foreach (int f in Fibonacci()) { if (f > n) return false; if (f == n) return true; } } ``` I actually really like this kind of Fibonacci implementation vs the tradition recursive solution, because it keeps the work used to complete a term available to complete the next. The traditional recursive solution duplicates some work, because it needs two recursive calls each term.
C# fibonacci function returning errors
[ "", "c#", "console-application", "fibonacci", "" ]
I wrote some small apps using .NET 3.5 but now I am stuck with deployment problems. My customer will likely to be pissed off when he learns that he will have to download a **231megs** dependency ([.NET framework 3.5](http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe)) which installs for **30 minutes** (!!!) on an average machine. All, just to run my tiny apps. Offline distribution is also problematic, since the customer wants the program to fit on a Mini CD (185 mega bytes maximum) What can I do? I really like .NET, but now I feel hopeless. With almost any other choice (c,c++,python) I would have saved this headache. **update**: this is small data processing software and mostly deployed in offline situations on nettops. I can't host is from the net.
You can use the .NET Client Profile installer instead of the full framework. Should be around 28MB and be a pretty quick install. <http://blogs.windowsclient.net/trickster92/archive/2008/05/21/introducing-the-net-framework-client-profile.aspx>
Perhaps you should target the .NET 2.0 framework until your clients are ready to upgrade. Even if you weren't using .NET you will still have these headaches. If you were using Python you would still have to ensure that the user had the proper version of Python installed.
Problems when deploying small .NET 3.5 apps
[ "", "c#", ".net", "deployment", "" ]
I need an array where size is known at compile time. I know I can use *std::vector* or *boost::array*. But that's doesn't teach me how it works internally. Also I couldn't find how to add items into *boost::array* other than using the initializer. I have written the following code for a generic array. My intention is to get familiar with iterators, template specializations etc. Following is the code ``` template<typename T> struct iterator_traits { typedef T value_type; typedef T& reference_type; typedef T* iterator; typedef const T* const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; }; template<typename T> struct iterator_traits<T*> { typedef T* value_type; typedef T*& reference_type; typedef T** iterator; typedef const T const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; }; template<typename T, size_t size = 10> class Array { public: typedef typename iterator_traits<T>::value_type value_type; typedef typename iterator_traits<T>::reference_type reference_type; typedef typename iterator_traits<T>::iterator iterator; typedef typename iterator_traits<T>::const_iterator const_iterator; typedef typename iterator_traits<T>::reverse_iterator reverse_iterator; Array() : lastIndex(0) { } void add(value_type element) { if(lastIndex >= size) throw std::out_of_range("Array is full"); array_[lastIndex++] = element; } reference_type at(unsigned int index){ if(index < size) return array_[index]; else throw std::out_of_range("Invalid index"); } size_t capacity(){ return size; } iterator begin(){ return array_; } iterator end(){ return array_ + size; } const_iterator begin() const{ return array_; } const_iterator end() const{ return array_ + size; } reverse_iterator rbegin() { return reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } private: value_type array_[size]; unsigned int lastIndex; }; ``` The above code works well. Following are my questions 1 - How can I create my array like *boost::array* does? Something like ``` Array<int> ints = { 10, 12 }; ``` 2 - Are there any pitfalls in the code? 3 - I had to use a specialization for pointer types in traits. Is that the best practice? 4 - Iterator pattern is implemented correctly or not? Any thoughts would be great!
1 - How can I create my array like boost::array does? Something like ``` Array<int> ints = { 10, 12 }; ``` In c++, you can only (currently) use a braces enclosed initializer list if your struct, union or c-style array meets the criteria of being an aggregate. To do such, according to the standard: 8.5.1.1 An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3). You would have to make your class have those features if you wanted to use them in the current standard. The next standard (see [here](http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists)) includes a provision to allow other types to do so. 2 - Are there any pitfalls in the code? Here is one: the reason you can't add things to a boost list is it always has the same number of elements (the size it was allocated with). In your array you can add elements, but you've still constructed 10 elements underneath the hood during construction. this could lead to some suprising results if the user isn't expecting the default constructor called 10 times.
boost::array uses a feature of the language: A struct with no constructors can use an initialization list. If you provide your own constructor, you can't use an initialization list. Also, you're using `iterator_traits` wrong. Your code should be something like ``` // type definitions typedef T value_type; typedef T* iterator; typedef const T* const_iterator; typedef T& reference; typedef const T& const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; ``` iterator\_traits is for traits of iterators. Also, you can just use a pointer as an iterator. The STL explicitly allows this.
Implementing a generic fixed size array with iterator support
[ "", "c++", "arrays", "templates", "iterator", "" ]
``` SELECT sum(TotalHoursM) + (TotalHoursT) + (TotalHoursW) + (TotalHoursTH) + (TotalHoursF) AS TOTAL FROM LeaveRequest ```
If the column has a 0 value, you are fine, my guess is that you have a problem with a Null value, in that case you would need to use `IsNull(Column, 0)` to ensure it is always 0 at minimum.
The previous answers using the `ISNULL` function are correct only for MS Sql Server. The `COALESCE` function will also work in SQL Server. But will also work in standard SQL database systems. In the given example: ``` SELECT sum(COALESCE(TotalHoursM,0)) + COALESCE(TotalHoursT,0) + COALESCE(TotalHoursW,0) + COALESCE(TotalHoursTH,0) + COALESCE(TotalHoursF,0) AS TOTAL FROM LeaveRequest ``` This is identical to the `ISNULL` solution with the only difference being the name of the function. Both work in SQL Server but, `COALESCE` is ANSI standard and `ISNULL` is not. Also, `COALESCE` is more flexible. `ISNULL` will only work with two parameters. If the first parameter is NULL then the value of the second parameter is returned, else the value of the first is returned. COALESCE will take 2 to 'n' (I don't know the limit of 'n') parameters and return the value of the first parameter that is not `NULL`. When there are only two parameters the effect is the same as `ISNULL`.
SQL: sum 3 columns when one column has a null value?
[ "", "sql", "" ]
i have a webform that generates a file, but when i click the button that produces the postback to generate the file Once it finish if i press Refresh (F5) the page resubmit the postback and regenerates the file, there's any way to validate it and show a message to the user or simply DO NOTHING! thanks :)
i wrote a solution for this problem and here it is if anyone needs it. ``` protected void Page_Load(object sender, System.EventArgs e) { /*******/ //Validate if the user Refresh the webform. //U will need:: //A global private variable called ""private bool isRefresh = false;"" //a global publica variable called ""public int refreshValue = 0;"" //a html control before </form> tag: ""<input type="hidden" name="ValidateRefresh" value="<%= refreshValue %>">"" int postRefreshValue = 0; refreshValue = SII.Utils.convert.ToInt(Request.Form["ValidateRefresh"]); //u can use a int.parse() if (refreshValue == 0) Session["ValidateRefresh"] = 0; postRefreshValue = SII.Utils.convert.ToInt(Session["ValidateRefresh"]); //can use a int.parse() if (refreshValue < postRefreshValue) isRefresh = true; Session["ValidateRefresh"] = postRefreshValue + 1; refreshValue = SII.Utils.convert.ToInt(Session["ValidateRefresh"]); //can use a int.parse() /********/ if (!IsPostBack) { //your code } } ``` you just have to evaluate: ``` if (!isRefresh) PostFile(); else { //Error msg you are refreshing } ```
The simpler way will be to use Post Rediret Get pattern. <http://en.wikipedia.org/wiki/Post/Redirect/Get> Make sure to check out External Links on that Wikipedia article.
C# validate repeat last PostBack when hit Refresh (F5)
[ "", "c#", "asp.net", "validation", "refresh", "" ]
How can I achieve the following in oracle without creating a stored procedure? Data Set: ``` question_id element_id 1 7 1 8 2 9 3 10 3 11 3 12 ``` Desired Result: ``` question_id element_id 1 7,8 2 9 3 10,11,12 ```
There are many way to do the string aggregation, but the easiest is a user defined function. [Try this for a way that does not require a function.](http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php) As a note, there is no simple way without the function. This is the shortest route without a custom function: (it uses the ROW\_NUMBER() and SYS\_CONNECT\_BY\_PATH functions ) ``` SELECT questionid, LTRIM(MAX(SYS_CONNECT_BY_PATH(elementid,',')) KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements FROM (SELECT questionid, elementid, ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) AS curr, ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) -1 AS prev FROM emp) GROUP BY questionid CONNECT BY prev = PRIOR curr AND questionid = PRIOR questionid START WITH curr = 1; ```
From Oracle 11gR2, the [LISTAGG](http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions089.htm#SQLRF30030) clause should do the trick: ``` SELECT question_id, LISTAGG(element_id, ',') WITHIN GROUP (ORDER BY element_id) FROM YOUR_TABLE GROUP BY question_id; ``` Beware if the resulting string is too big (more than 4000 chars for a VARCHAR2, for instance): from version 12cR2, we can use [ON OVERFLOW TRUNCATE/ERROR](https://oracle-base.com/articles/12c/listagg-function-enhancements-12cr2) to deal with this issue.
How can multiple rows be concatenated into one in Oracle without creating a stored procedure?
[ "", "sql", "oracle", "concatenation", "string-aggregation", "" ]
[Please note that this is a different question from the already answered [How to replace a column using Python’s built-in .csv writer module?](https://stackoverflow.com/questions/1019200/how-to-replace-a-column-using-pythons-built-in-csv-writer-module)] I need to do a find and replace (specific to one column of URLs) in a huge Excel .csv file. Since I'm in the beginning stages of trying to teach myself a scripting language, I figured I'd try to implement the solution in python. I'm having trouble when I try to write back to a .csv file after making a change to the contents of an entry. I've read the [official csv module documentation](http://docs.python.org/3.0/library/csv.html) about how to use the writer, but there isn't an example that covers this case. Specifically, I am trying to get the read, replace, and write operations accomplished in one loop. However, one cannot use the same 'row' reference in both the for loop's argument and as the parameter for writer.writerow(). So, once I've made the change in the for loop, how should I write back to the file? **edit:** I implemented the suggestions from S. Lott and Jimmy, still the same result **edit #2:** I added the "rb" and "wb" to the open() functions, per S. Lott's suggestion ``` import csv #filename = 'C:/Documents and Settings/username/My Documents/PALTemplateData.xls' csvfile = open("PALTemplateData.csv","rb") csvout = open("PALTemplateDataOUT.csv","wb") reader = csv.reader(csvfile) writer = csv.writer(csvout) changed = 0; for row in reader: row[-1] = row[-1].replace('/?', '?') writer.writerow(row) #this is the line that's causing issues changed=changed+1 print('Total URLs changed:', changed) ``` **edit:** For your reference, this is the **new** full traceback from the interpreter: ``` Traceback (most recent call last): File "C:\Documents and Settings\g41092\My Documents\palScript.py", line 13, in <module> for row in reader: _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) ```
You cannot read and write the same file. ``` source = open("PALTemplateData.csv","rb") reader = csv.reader(source , dialect) target = open("AnotherFile.csv","wb") writer = csv.writer(target , dialect) ``` The normal approach to ALL file manipulation is to create a modified COPY of the original file. Don't try to update files in place. It's just a bad plan. --- **Edit** In the lines ``` source = open("PALTemplateData.csv","rb") target = open("AnotherFile.csv","wb") ``` The "rb" and "wb" are absolutely required. Every time you ignore those, you open the file for reading in the wrong format. You must use "rb" to read a .CSV file. There is no choice with Python 2.x. With Python 3.x, you can omit this, but use "r" explicitly to make it clear. You must use "wb" to write a .CSV file. There is no choice with Python 2.x. With Python 3.x, you must use "w". --- **Edit** It appears you are using Python3. You'll need to drop the "b" from "rb" and "wb". Read this: <http://docs.python.org/3.0/library/functions.html#open>
Opening csv files as binary is just wrong. CSV are normal text files so You need to open them with ``` source = open("PALTemplateData.csv","r") target = open("AnotherFile.csv","w") ``` The error ``` _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) ``` comes because You are opening them in binary mode. When I was opening excel csv's with python, I used something like: ``` try: # checking if file exists f = csv.reader(open(filepath, "r", encoding="cp1250"), delimiter=";", quotechar='"') except IOError: f = [] for record in f: # do something with record ``` and it worked rather fast (I was opening two about 10MB each csv files, though I did this with python 2.6, not the 3.0 version). There are few working modules for working with excel csv files from within python - [pyExcelerator](http://sourceforge.net/projects/pyexcelerator) is one of them.
Writing with Python's built-in .csv module
[ "", "python", "file-io", "csv", "python-3.x", "" ]
How do I check if the charset of a string is UTF8?
``` function is_utf8($string) { return preg_match('%^(?: [\x09\x0A\x0D\x20-\x7E] # ASCII | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 )*$%xs', $string); ``` } I have checked. This function is effective.
Don't reinvent the wheel. There is a builtin function for that task: [`mb_check_encoding()`](http://de.php.net/manual/en/function.mb-check-encoding.php). ``` mb_check_encoding($string, 'UTF-8'); ```
How to check the charset of string?
[ "", "php", "string", "character-encoding", "" ]
I have a small WinForms app that utilizes a BackgroundWorker object to perform a long-running operation. The background operation throws occasional exceptions, typically when somebody has a file open that is being recreated. Regardless of whether the code is run from the IDE or not .NET pops up an error dialog informing the user that an Unhandled exception has occurred. Compiling the code using the Release configuration doesn't change this either. According to [MSDN](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.dowork.aspx "MSDN"): > If the operation raises an exception that your code does not handle, the BackgroundWorker catches the exception and passes it into the RunWorkerCompleted event handler, where it is exposed as the Error property of System.ComponentModel..::.RunWorkerCompletedEventArgs. If you are running under the Visual Studio debugger, the debugger will break at the point in the DoWork event handler where the unhandled exception was raised. I expect these exceptions to be thrown on occasion and would like to handle them in the RunWorkerCompleted event rather than in DoWork. My code works properly and the error is handled correctly within the RunWorkerCompleted event but I can't for the life of me figure out how to stop the .NET error dialog complaining about the "Unhandled exception" from occurring. Isn't the BackgroundWorker supposed to catch that error automagically? Isn't that what the MSDN documentation states? What do I need to do to inform .NET that this error *is* being handled while still allowing the exception to propage into the Error property of RunWorkerCompletedEventArgs?
What you're describing is not the defined behavior of BackgroundWorker. You're doing something wrong, I suspect. Here's a little sample that proves BackgroundWorker eats exceptions in **DoWork**, and makes them available to you in **RunWorkerCompleted**: ``` var worker = new BackgroundWorker(); worker.DoWork += (sender, e) => { throw new InvalidOperationException("oh shiznit!"); }; worker.RunWorkerCompleted += (sender, e) => { if(e.Error != null) { MessageBox.Show("There was an error! " + e.Error.ToString()); } }; worker.RunWorkerAsync(); ``` My psychic debugging skills are revealing your problem to me: You are accessing e.Result in your RunWorkerCompleted handler -- if there's an e.Error, you must handle it without accessing e.Result. For example, the following code is bad, bad, bad, and will throw an exception at runtime: ``` var worker = new BackgroundWorker(); worker.DoWork += (sender, e) => { throw new InvalidOperationException("oh shiznit!"); }; worker.RunWorkerCompleted += (sender, e) => { // OH NOOOOOOOES! Runtime exception, you can't access e.Result if there's an // error. You can check for errors using e.Error. var result = e.Result; }; worker.RunWorkerAsync(); ``` Here's a proper implementation of the RunWorkerCompleted event handler: ``` private void RunWorkerCompletedHandler(object sender, RunWorkerCompletedEventArgs e) { if (e.Error == null) { DoSomethingWith(e.Result); // Access e.Result only if no error occurred. } } ``` VOILA, you won't receive runtime exceptions.
I would add to the [MSDN text](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.dowork.aspx): > If the operation raises an exception that your code does not handle, the BackgroundWorker catches the exception and passes it into the RunWorkerCompleted event handler, where it is exposed as the Error property of System.ComponentModel..::.RunWorkerCompletedEventArgs. **If you are running under the Visual Studio debugger, the debugger will break at the point in the DoWork event handler where the unhandled exception was raised.** **... AND the debugger will report the exception as "~Exception was unhandled by user code"** Solution: Don't run under the debugger and it works as expected: Exception caught in e.Error.
Unhandled exceptions in BackgroundWorker
[ "", "c#", "exception", "backgroundworker", "unhandled-exception", "" ]
Suppose I have two classes that both contain a static variable, XmlTag. The second class inherits from the first class. I have a template method that needs to obtain the XmlTag depending on the which type it is using. What would be the best way to accomplish this, without having to create an instance of the type? Here is an example(that won't compile), that should hopefully illustrate what I'm talking about. ``` class A{ public static readonly string XmlTag = "AClass"; } class B : A { public static readonly string XmlTag = "BClass"; } ``` This method is currently invalid.. Static variables can't be accessed from Type paramaters apparently. ``` string GetName<T>(T AClass) where T : A { return T.XmlTag; } ```
First off, stop thinking of generic methods as templates. They are NOT templates. They have very different behaviour from templates; your expectation that they behave like templates is possibly what is leading you astray in this situation. Here is a series of articles I wrote about your scenario and why it is illegal. <http://blogs.msdn.com/ericlippert/archive/2007/06/14/calling-static-methods-on-type-variables-is-illegal-part-one.aspx> <http://blogs.msdn.com/ericlippert/archive/2007/06/18/calling-static-methods-on-type-variables-is-illegal-part-two.aspx> <http://blogs.msdn.com/ericlippert/archive/2007/06/21/calling-static-methods-on-type-variables-is-illegal-part-three.aspx> Note that of course the "dynamic" feature that I hint at in part three is in fact shipping with C# 4.0. To address your actual question: "what's the best way to do this?" Presumably you have some problem which you believe a mechanism like this would solve. This mechanism doesn't actually exist in C#. **It is impossible for us to deduce what problem you are actually trying to solve from the fact that you would like this mechanism to exist.** Instead of asking "how can I make this impossible thing work in C#?" instead **describe the real problem you have**, and we can take a crack at trying to come up with an existing C# mechanism that better solves your real problem.
There's no direct way you could do that without resorting to reflection. If you **really** want to do that (I encourage you to consider changing your high level design first): To get a field value: ``` var returnValue = typeof(T).GetField("FieldName").GetValue(null); ``` To get a property: ``` var returnValue = typeof(T).GetProperty("PropertyName").GetValue(null, null); ``` To invoke a method: ``` typeof(T).InvokeMember("MethodName", BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.NonPublic, null, null, null); ```
Template method accessing static variables issue
[ "", "c#", ".net", "" ]
This is how i calculated the digital root of an integer. --- ``` import acm.program.*; public class Problem7 extends ConsoleProgram { public void run() { println("This program calculates the digital root of an interger."); int num = readInt("Enter the number: "); int sum = 0; while (true) { if (num > 0) { int dsum = num % 10; num /= 10; sum += dsum; } else if (sum > 9) { int dsum = sum % 10; sum /= 10; sum += dsum; } else if (sum <= 9 ) break; } println("Digital Root is: " + sum); } ``` --- The program works fine. Is there a better/shorter way of calculating the digital root of a number. ? --- EDIT/ADDED : Here is the implementation of the above problem by using [Tyler](https://stackoverflow.com/users/58657/tyler)'s answer, it works as well: --- ``` import acm.program.*; public class Problem7 extends ConsoleProgram { public void run() { println("This program calculates the digital root of an interger."); int num = readInt("Enter the number: "); println("Digital Root of " + num + " is: " + (1 + (num - 1) % 9)); } } ``` ---
``` #include <stdio.h> int main(void) { int number; scanf("%d", &number); printf("The digital root of %d is %d.", number, (1 + (number - 1) % 9)); } ``` Had I not been able to find Ramans' formula this is how I would write this program...: ``` #include <stdio.h> #include <ctype.h> int main(void) { int c; int number = 0; while ((c = getchar()) != EOF) { if (isdigit(c)) number += (c - '0'); } if (number <= 9) { printf("The digital root is %d\n", number); } else { printf("%d", number); } } ``` After compiling, to run this, basically you just chain these together. I believe four is the most you could possibly need for an integer. ``` $ echo 829382938 | ./digitalroot | ./digitalroot | ./digitalroot | ./digitalroot ```
Personally, I do not like your loop, which is essentially two loops (first going over the original digits, then going over the digits of sum) mashed into one. How about a sprinkling of recursion: ``` private int sumDigits(int in){ if (i>10) return in%10 + sumDigits(in/10); return in; } private int digitalRoot(int in){ assert (in > 0) ; while (in > 9) in=sumDigits(in); return in; } ```
Calculating Digital Root, is there a better way?
[ "", "java", "math", "" ]
I am using MySQL for my database. I have a requirement to store a list of users in the system. The user will have both first name and last name. I cannot have the first name and second name as the primary key. So I need a indexing key. But I do not want to enter the index value every time to add a new row. I want the system to handle this with auto increment of previous value every time I try to add a new user. Please let me know how to do this. Also I am supposed to do a search operation on the list of user with the first name. Please let me know the efficient way to do the search as the number of records could be more than a million.
``` create table users ( id int primary key auto_increment, name varchar(64), ... ) ``` See [here](http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html) for more info
Add an `INT()` `id` column with `auto_increment` set. This way, the `id` column value will be incremented automatically on each `INSERT`.
Auto Index in My SQL
[ "", "mysql", "sql", "" ]
If I have a class called Test :: ``` class Test { static std::vector<int> staticVector; }; ``` when does **staticVector** get constructed and when does it get destructed ? Is it with the instantiation of the first object of Test class, or just like regular static variables ? *Just to clarify, this question came to my mind after reading Concepts of Programming Languages (Sebesta Ch-5.4.3.1) and it says ::* > Note that when the **static** modifier > appears in the declaration of a > variable in a class definition in C++, > Java and C#, it has nothing to do with > the lifetime of the variable. In that > context, it means the variable is a > class variable, rather than an > instance variable. The multiple use > of a reserved word can be confusing > particularly to those learning the > language. **did you understand? :(**
Exactly like regular static (global) variables.
I want to write some text about initializaton too, which i can later link to. --- First the list of possibilities. * *Namespace* Static * *Class* Static * *Local* Static ## Namespace Static * There are two initialization methods. *static* (intended to happen at compile time) and *dynamic* (intended to happen at runtime) initialization. * *Static* Initialization *happens before* any dynamic initialization, disregarding of translation unit relations. * *Dynamic* Initiaization is ordered in a translation unit, while there is no particular order in static initialization. Objects of namespace scope of the same translation unit are dynamically initialized in the order in which their definition appears. * POD type objects that are initialized with constant expressions are statically initialized. Their value can be relied on by any object's dynamic initialization, disregarding of translation unit relations. * If the initialization throws an exception, `std::terminate` is called. Examples: The following program prints **`A(1) A(2)`** ``` struct A { A(int n) { std::printf(" A(%d) ", n); } }; A a(1); A b(2); ``` And the following, based on the same class, prints **`A(2) A(1)`** ``` extern A a; A b(2); A a(1); ``` Let's pretend there is a translation unit where `msg` is defined as the following ``` char const *msg = "abc"; ``` Then the following prints **`abc`**. Note that `p` receives dynamic initialization. But because the static initialization (`char const*` is a POD type, and `"abc"` is an address constant expression) of `msg` happens before that, this is fine, and `msg` is guaranteed to be correctly initialized. ``` extern const char *msg; struct P { P() { std::printf("%s", msg); } }; P p; ``` * *Dynamic* initialization of an object is not required to happen before main at all costs. The initialization must happen before the first use of an object or function of its translation unit, though. This is important for dynamic loadable libraries. ## Class Static - Behave like namespace statics. - There is a bug-report on whether the compiler is allowed to initialize class statics on the first use of a function or object of its translation unit too (after main). The wording in the Standard currently only allows this for namespace scope objects - but it seems it intends to allow this for class scope objects too. Read [Objects of Namespace Scope](http://groups.google.com/group/comp.std.c++/browse\_thread/thread/28cfef85456512c8). - For class statics that are member of templates the rule is that they are only initialized if they are ever used. Not using them will not yield to an initialization. Note that in any case, initialization will happen like explained above. Initialization will not be delayed because it's a member of a template. ## Local Static - For local statics, special rules happen. - POD type objects initialized with constant expression are initialized before their block in which they are defined is entered. - Other local static objects are initialized at the first time control passes through their definition. Initialization is not considered to be complete when an exception is thrown. The initialization will be tried again the next time. Example: The following program prints **`0 1`**: ``` struct C { C(int n) { if(n == 0) throw n; this->n = n; } int n; }; int f(int n) { static C c(n); return c.n; } int main() { try { f(0); } catch(int n) { std::cout << n << " "; } f(1); // initializes successfully std::cout << f(2); } ``` --- In all the above cases, in certain limited cases, for some objects that are not required to be initialized statically, the compiler can statically initialize it, instead of dynamically initializing it. This is a tricky issue, see [this answer](https://stackoverflow.com/questions/920615/why-do-some-const-variables-referring-to-some-exported-const-variables-get-the-va/921681#921681) for a more detailed example. Also note that the order of destruction is the exact order of the completion of construction of the objects. This is a common and happens in all sort of situations in C++, including in destructing temporaries.
What is the lifetime of class static variables in C++?
[ "", "c++", "static-members", "lifetime", "" ]
I know PHP 5 already supports SQLite but for some reason I can't get it to work. I followed the instructions from [*SQLite tutorial: Getting started*](http://www.scriptol.com/sql/sqlite-getting-started.php). I also made sure that the following are not commented out from php.ini: ``` extension=php_pdo_sqlite.dll extension=php_sqlite.dll. ``` But when I open the PHP file from localhost using Firefox, I get this error: > Fatal error: Class 'SQLiteDatabase' not found. I'm on Windows by the way, if that info matters. What may be the cause of this problem?
I think the class `SQLiteDatabase` is from the extension `sqlite` rather `pdo_sqlite`. So you could enable the `sqlite` extension, or use PDO instead: ``` <?php $conn = new PDO('sqlite:c:/mydb.sq3'); $conn->exec('some sql query'); ```
On Windows you need to have the following set in your ini: ``` extension=php_pdo.dll extension=php_sqlite.dll ``` I recommend you read [this page](http://php.net/manual/en/sqlite.installation.php) in the manual.
How can I use and access an SQLite DB using PHP and Wamp Server?
[ "", "php", "database", "windows", "sqlite", "pdo", "" ]
I have little bit longer question for you - but hope answer will be very simple :) Let's say I have very simple page with link and iframe (just for simple example). ``` <body> <a href="test.html" target="mframe">open link></a> <iframe name="mframe" [params] /> </body> ``` So when you click on the link it will load test.html in the frame. Now I will change the iframe with div and ajax call. ``` <body> <a href="doAjaxCall('test.html')">open link</a> <div id="main-content"></div> </body> ``` The doAjaxCall will simply use GET ajax requset to get whole response, parse it (using JavaScript) and grab content in <body> tag and put it into main-content.innerHTML. test.html contains a lot of html, also css styles (but the same as are on parent page - so I don't need them when I'm using ajax solution). **Question:** Why is this ajax solution SO faster? I'm still downloading the same amount of data (downloading whole test.html). Why is the iframe solution so slow? Is it because of browser have to parse all possible styles again? Or is there any other overhead of iframes?
You are pretty much on the right track. iframes are going to be slower because there is an additional overhead for the browser (rendering it, maintaining it's instance and references to it). The ajax call is going to be a bit faster because you get the data in and you then inject it, or do whatever you want with it. The iframe will need to build an entirely new "page" in the browsers memory, and then place it in the page.
Steve Souders has a post [*Using Iframes Sparingly*](http://www.stevesouders.com/blog/2009/06/03/using-iframes-sparingly/) on his High Performance Web Sites blog that may provide some more insight.
Why are iframes so slow?
[ "", "javascript", "html", "css", "ajax", "iframe", "" ]
I am creating a php backup script that will dump everything from a database and save it to a file. I have been successful in doing that but now I need to take hundreds of images in a directory and compress them into one simple .tar.gz file. What is the best way to do this and how is it done? I have no idea where to start. Thanks in advance
If you are using PHP 5.2 or later, you could use the [Zip Library](https://www.php.net/manual/en/book.zip.php) and then do something along the lines of: ``` $images_dir = '/path/to/images'; //this folder must be writeable by the server $backup = '/path/to/backup'; $zip_file = $backup.'/backup.zip'; if ($handle = opendir($images_dir)) { $zip = new ZipArchive(); if ($zip->open($zip_file, ZipArchive::CREATE)!==TRUE) { exit("cannot open <$zip_file>\n"); } while (false !== ($file = readdir($handle))) { $zip->addFile($images_dir.'/'.$file); echo "$file\n"; } closedir($handle); echo "numfiles: " . $zip->numFiles . "\n"; echo "status:" . $zip->status . "\n"; $zip->close(); echo 'Zip File:'.$zip_file . "\n"; } ```
``` $archive_name = 'path\to\archive\arch1.tar'; $dir_path = 'path\to\dir'; $archive = new PharData($archive_name); $archive->buildFromDirectory($dir_path); // make path\to\archive\arch1.tar $archive->compress(Phar::GZ); // make path\to\archive\arch1.tar.gz unlink($archive_name); // deleting path\to\archive\arch1.tar ```
Compressing a directory of files with PHP
[ "", "php", "compression", "backup", "" ]
In a recent interview, I was asked to implement a thread safe generic (i.e.template based) stack in C++, on linux machine. I quickly came up with the following (It may have compilation errors). I got through. The interviewer probably liked something in this implementation. Maybe the design part :) Here are a few problems that this implementation may have:- 1. Incorrect implementation to indicate overflow/underflow. There is no overflow handling since I'm using STL vector as the underlying data structure. Should there be any such handling? Also, underflow (in Pop()) yields false as return value. Should it be done by throwing of an exception? 2. Implementation of PopElem routine. Is the below implementation correct? 3. No real use of top element. 4. Better timing between start of writer and reader thread. Please make any comments/suggestions/improvements. Thanks. //Implementing a thread safe generic stack. ``` #include<pthread.h> #include<iostream> #include<vector> using namespace std; template<typename T> class MyStack { public: //interface bool Push(T elem); bool Pop(T& elem); bool IsEmpty(); //constructor MyStack() { pthread_mutex_init(&lock); top = 0; } //destructor ~MyStack() { pthread_mutex_destroy(&lock); } private: pthread_mutex_t lock; int top; vector<T> stack; bool MyStack::Push(T elem); bool MyStack::PopElem(T& elem); }; //end of MyStack template<typename T> bool MyStack<T>::Push(T elem) { pthread_mutex_lock(&lock); PushElem(elem); pthread_mutex_unlock(&lock); } template<typename T> bool MyStack<T>::Pop(T& elem) { pthread_mutex_lock(&lock); PopElem(elem); pthread_mutex_unlock(&lock); } template<typename T> bool MyStack<T>::PushElem(T elem) { stack.push_back(elem); top = stack.size(); } template<typename T> bool MyStack<T>::PopElem(T& elem) { if(this.IsEmpty()) { return false; } elem = stack.back(); //tricky, returns a reference to the last element stack.pop_back(); // is elem valid after this ?? top = stack.size(); return true; } template<typename T> bool MyStack<T>::IsEmpty() { return stack.empty(); } class MyStackTest { public: void Initialize() { pthread_init(&readerT); pthread_init(&writerT); } void Run() { pthread_create(writerT,0,writer,0); pthread_create(readerT,0,reader,0); pthread_join(&writerT); pthread_join(&readerT); } private: pthread_t readerT; pthread_t writerT; MyStack<int> stack; void reader(void); void writer(void); }; void MyStackTest::writer() { for(int i=0;i<20;i++) { stack.Push(i); cout<<"\n\t Pushed element: "<<i; } //end for } void MyStackTest::reader() { int elem; while(stack.Pop(elem)) { cout<<"\n\t Popped: "<<elem; } } int main() { MyStackTest Test; Test.Run(); } ```
Some issues: * I would implement a Locker class to claim & free the mutex using RAII * I would use std::stack * I would make the user of std::stack use the Locker to implement the locking policy - having a stack that locks itself is bad design, as the stack can't know how it is to be used
Neil, Onebyone: An attempt on using RAII for mutex lock. Any comments? ``` template<typename T> class MyStack { public: //interface bool Push(T elem); bool Pop(T& elem); bool IsEmpty(); //constructor MyStack() { //top = 0; } //destructor ~MyStack() { } private: class Locker { //RAII public: Locker() { pthread_mutex_init(&lock); } ~Locker() { pthread_mutex_destroy(&lock); } void Lock() { pthread_mutex_lock(&lock); } void UnLock() { pthread_mutex_unlock(&lock); } private: pthread_mutex_t lock; }; Locker MyLock; //int top; stack<T> mystack; bool MyStack::Push(T elem); bool MyStack::PushElem(T elem); bool MyStack::Pop(T& elem); bool MyStack::PopElem(T& elem); }; //end of MyStack template<typename T> bool MyStack<T>::Push(T elem) { MyLock.Lock(); PushElem(elem); MyLock.UnLock(); } template<typename T> bool MyStack<T>::Pop(T& elem) { MyLock.Lock(); PopElem(elem); MyLock.UnLock(); } ```
Implementing a thread-safe, generic stack in C++ on linux
[ "", "c++", "multithreading", "stl", "" ]
i am using Solaris 10 OS(x86). i installed beanstalkd and it starts fine by using command "beanstalkd -d -l hostip -p 11300". i have Python 2.4.4 on my system i installed YAML and beanstalkc python libraries to connect beanstalkd with python my problem is when i try to write some code: import beanstalkc beanstalk = beanstalkc.Connection(host='hostip', port=11300) no error so far but when i try to do someting on beanstalk like say listing queues. nothing happens. beanstalk.tubes() it just hangs and nothing returns. if i cancel the operation(using ctr+c on python env.) or stop the server i immediately see an output: Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 134, in tubes return self.\_interact\_yaml('list-tubes\r\n', ['OK']) File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 83, in \_interact\_yaml size, = self.\_interact(command, expected\_ok, expected\_err) File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 57, in \_interact status, results = self.\_read\_response() File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 66, in \_read\_response response = self.socket\_file.readline().split() File "/usr/lib/python2.4/socket.py", line 332, in readline data = self.\_sock.recv(self.\_rbufsize) any idea whats going? i am an Unix newbie so i have no idea what i did setup wrong to cause this. edit: seems like the problem lies within BeanStalkd itself, anyone have used this on Solaris 10? if so which version did you use? The v1.3 labeled one doesnt compile on Solaris while the latest from git code repository compiles it causes the above problem(or perhaps there is some configuration to do on Solaris?). edit2: i installed and compiled same components with beanstalkd, PyYAML, pythonbeanstalc and libevent to an UBUNTU machine and it works fine. problems seems to be about compilation of beanstalkd on solaris, i have yet to produce or read any solution.
I might know what is wrong: don't start it in daemon (-d) mode. I have experienced the same and by accident I found out what is wrong. Or rather, I don't know what is wrong, but it works without running it in daemon mode. ./beanstalkd -p 9977 & as an alternative.
After looking in the code (beanstalkc): your client has send his 'list-tubes' message, and is waiting for an answer. (until you kill it) your server doesn't answer or can't send the answer to the client. (or the answer is shorter than the client expect) is a network-admin at your side (or site) :-)
BeanStalkd on Solaris doesnt return anything when called from the python library
[ "", "python", "solaris", "yaml", "beanstalkd", "" ]
Just starting with js, decided to convert Friendfeed to a fluid app, and as part of that I need to be able to parse some numbers out of a string. How do I complete this function? ``` function numMessages(text) { MAGIC HAPPENS (POSSIBLY THE DARK ART OF THE REGEX) return number; } ``` input would be "Direct Messages (15)" output would be 15. Instincts tell me to find the first bracket then find the last bracket, and get the text in between but I don't know how to do that. Second instinct tells me to regex for [0-9], but I don't know how to run regexes in js. Jquery is avaliable already if needed. Thanks!
This should do it: ``` >>> 'Direct Messages (15)'.match(/[0-9]+/g); ["15"] ``` Just be careful if you expect more than 1 number to be in the string: ``` >>> 'Direct 19 Messages (15)'.match(/[0-9]+/g); ["19", "15"] ``` If you only wanted the first match, you could remove the `g` flag: ``` >>> 'Direct 19 Messages (15)'.match(/[0-9]+/); ["19"] ``` If you only wanted to match what's between the parentheses ``` >>> 'Direct 19 Messages (15)'.match(/\((.*?)\)/); ["(15)","15"] // first index will always be entire match, 2nd index will be captured match ``` As pointed out in the comments, to get the last match: ``` >>> var matches = 'Direct 19 Messages (15)'.match(/[0-9]+/g); >>> matches[matches.length-1]; "15" ``` Though some boundary checking would also be appropriate. :)
``` var reg = new RegExp('[0-9]+'); reg.exec('Direct Messages (15)'); ```
Javascript text manipulation
[ "", "javascript", "jquery", "" ]
I'd like to use date time format string (possibly UTC) which is understandable and parsable on as many platforms and languages as possible? At least PHP, Python, Perl, Java, Rails and some common C++ library should be able to understand it. Which one should I use? Sample from MSDN: ``` Culture: English (United States) (d) Short date: . . . . . . . 4/17/2006 (D) Long date:. . . . . . . . Monday, April 17, 2006 (t) Short time: . . . . . . . 2:29 PM (T) Long time:. . . . . . . . 2:29:09 PM (f) Full date/short time: . . Monday, April 17, 2006 2:29 PM (F) Full date/long time:. . . Monday, April 17, 2006 2:29:09 PM (g) General date/short time:. 4/17/2006 2:29 PM (G) General date/long time (default): . . . . . . . . . . . . . 4/17/2006 2:29:09 PM (M) Month:. . . . . . . . . . April 17 (R) RFC1123:. . . . . . . . . Mon, 17 Apr 2006 21:29:09 GMT (s) Sortable: . . . . . . . . 2006-04-17T14:29:09 (u) Universal sortable (invariant): . . . . . . . . . . . . . 2006-04-17 21:29:09Z (U) Universal full date/time: Monday, April 17, 2006 9:29:09 PM (Y) Year: . . . . . . . . . . April, 2006 (o) Roundtrip (local):. . . . 2006-04-17T14:29:09.3011250-07:00 (o) Roundtrip (UTC):. . . . . 2006-04-17T21:29:09.3011250Z (o) Roundtrip (Unspecified):. 2000-03-20T13:02:03.0000000 ```
Stick with ISO8601 and you can't go wrong. Preferably, YYYYMMDD HH:mm:ss [TZ] format as it is the most widely used. And definitely UTC "under the covers" if you are decoupling local time at the presentation layer of the application from internal stored time.
The round-trip formats are [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601) compliant. I would use them.
Which date and time format is most compatible with other platforms?
[ "", "c#", ".net", "datetime", "" ]
I'm running a Django app on Apache + mod\_python. When I make some changes to the code, sometimes they have effect immediately, other times they don't, until I restart Apache. However I don't really want to do that since it's a production server running other stuff too. Is there some other way to force that? Just to make it clear, since I see some people get it wrong, I'm talking about a *production* environment. For development I'm using Django's development server, of course.
If possible, you should switch to mod\_wsgi. This is now the [recommended way](http://docs.djangoproject.com/en/dev/howto/deployment/modwsgi/) to serve Django anyway, and is much more efficient in terms of memory and server resources. In mod\_wsgi, each site has a `.wsgi` file associated with it. To restart a site, just `touch` the relevant file, and only that code will be reloaded.
As others have suggested, use mod\_wsgi instead. To get the ability for automatic reloading, through touching the WSGI script file, or through a monitor that looks for code changes, you must be using daemon mode on UNIX. A slight of hand can be used to achieve same on Windows when using embedded mode. All the details can be found in: <http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode>
Restarting a Django application running on Apache + mod_python
[ "", "python", "django", "mod-python", "" ]
I'm using google app engine with django 1.0.2 (and the django-helper) and wonder how people go about doing recursive delete. Suppose you have a model that's something like this: ``` class Top(BaseModel): pass class Bottom(BaseModel): daddy = db.ReferenceProperty(Top) ``` Now, when I delete an object of type 'Top', I want all the associated 'Bottom' objects to be deleted as well. As things are now, when I delete a 'Top' object, the 'Bottom' objects stay and then I get data that doesn't belong anywhere. When accessing the datastore in a view, I end up with: ``` Caught an exception while rendering: ReferenceProperty failed to be resolved. ``` I could of course find all objects and delete them, but since my real model is at least 5 levels deep, I'm hoping there's a way to make sure this can be done automatically. I've found this [article](http://code.google.com/appengine/docs/java/datastore/relationships.html#Dependent_Children_and_Cascading_Deletes) about how it works with Java and that seems to be pretty much what I want as well. Anyone know how I could get that behavior in django as well?
You need to implement this manually, by looking up affected records and deleting them at the same time as you delete the parent record. You can simplify this, if you wish, by overriding the .delete() method on your parent class to automatically delete all related records. For performance reasons, you almost certainly want to use key-only queries (allowing you to get the keys of entities to be deleted without having to fetch and decode the actual entities), and batch deletes. For example: ``` db.delete(Bottom.all(keys_only=True).filter("daddy =", top).fetch(1000)) ```
Actually that behavior is GAE-specific. Django's ORM simulates "ON DELETE CASCADE" on .delete(). I know that this is not an answer to your question, but maybe it can help you from looking in the wrong places.
Recursive delete in google app engine
[ "", "python", "django", "google-app-engine", "" ]
Normally with Java Swing you can set the background color of a button with: ``` myJButton.setBackground(Color.RED); ``` which would cause the button to be red. But on the Mac OS, this method seems to be ignored. The button just stays the default color. How can the color of a JButton be set on the Mac OS?
Have you tried setting JButton.setOpaque(true)? ``` JButton button = new JButton("test"); button.setBackground(Color.RED); button.setOpaque(true); ```
Have you tried setting the painted border false? ``` JButton button = new JButton(); button.setBackground(Color.red); button.setOpaque(true); button.setBorderPainted(false); ``` It works on my mac :)
How to Set the Background Color of a JButton on the Mac OS
[ "", "java", "macos", "swing", "" ]
How can I make a "keep alive" HTTP request using Python's urllib2?
Use the [urlgrabber](http://urlgrabber.baseurl.org/) library. This includes an HTTP handler for urllib2 that supports HTTP 1.1 and keepalive: ``` >>> import urllib2 >>> from urlgrabber.keepalive import HTTPHandler >>> keepalive_handler = HTTPHandler() >>> opener = urllib2.build_opener(keepalive_handler) >>> urllib2.install_opener(opener) >>> >>> fo = urllib2.urlopen('http://www.python.org') ``` Note: you should use urlgrabber version [3.9.0](http://urlgrabber.baseurl.org/download/urlgrabber-3.9.0.tar.gz) or earlier, as the [keepalive](http://urlgrabber.baseurl.org/help/urlgrabber.keepalive.html) module has been removed in version 3.9.1 There is a [port](https://github.com/wikier/keepalive) of the keepalive module to Python 3.
Try [urllib3](https://github.com/shazow/urllib3) which has the following features: * Re-use the same socket connection for multiple requests (HTTPConnectionPool and HTTPSConnectionPool) (with optional client-side certificate verification). * File posting (encode\_multipart\_formdata). * Built-in redirection and retries (optional). * Supports gzip and deflate decoding. * Thread-safe and sanity-safe. * Small and easy to understand codebase perfect for extending and building upon. For a more comprehensive solution, have a look at Requests. or a much more comprehensive solution - [Requests](https://github.com/kennethreitz/requests) - which supports keep-alive from [version](https://github.com/kennethreitz/requests/blob/develop/HISTORY.rst) 0.8.0 (by using urllib3 internally) and has the following [features](https://github.com/kennethreitz/requests/blob/develop/README.rst): * Extremely simple HEAD, GET, POST, PUT, PATCH, DELETE Requests. * Gevent support for Asyncronous Requests. * Sessions with cookie persistience. * Basic, Digest, and Custom Authentication support. * Automatic form-encoding of dictionaries * A simple dictionary interface for request/response cookies. * Multipart file uploads. * Automatc decoding of Unicode, gzip, and deflate responses. * Full support for unicode URLs and domain names.
Python urllib2 with keep alive
[ "", "python", "http", "urllib2", "keep-alive", "" ]
In Python, how do I read in a binary file and loop over each byte of that file?
## Python >= 3.8 Thanks to the [walrus operator (`:=`)](https://peps.python.org/pep-0572/) the solution is quite short. We read `bytes` objects from the file and assign them to the variable `byte` ``` with open("myfile", "rb") as f: while (byte := f.read(1)): # Do stuff with byte. ``` ## Python >= 3 In older Python 3 versions, we get have to use a slightly more verbose way: ``` with open("myfile", "rb") as f: byte = f.read(1) while byte != b"": # Do stuff with byte. byte = f.read(1) ``` Or as benhoyt says, skip the not equal and take advantage of the fact that `b""` evaluates to false. This makes the code compatible between 2.6 and 3.x without any changes. It would also save you from changing the condition if you go from byte mode to text or the reverse. ``` with open("myfile", "rb") as f: byte = f.read(1) while byte: # Do stuff with byte. byte = f.read(1) ``` ## Python >= 2.5 In Python 2, it's a bit different. Here we don't get bytes objects, but raw characters: ``` with open("myfile", "rb") as f: byte = f.read(1) while byte != "": # Do stuff with byte. byte = f.read(1) ``` Note that the with statement is not available in versions of Python below 2.5. To use it in v 2.5 you'll need to import it: ``` from __future__ import with_statement ``` In 2.6 this is not needed. ## Python 2.4 and Earlier ``` f = open("myfile", "rb") try: byte = f.read(1) while byte != "": # Do stuff with byte. byte = f.read(1) finally: f.close() ```
This generator yields bytes from a file, reading the file in chunks: ``` def bytes_from_file(filename, chunksize=8192): with open(filename, "rb") as f: while True: chunk = f.read(chunksize) if chunk: for b in chunk: yield b else: break # example: for b in bytes_from_file('filename'): do_stuff_with(b) ``` See the Python documentation for information on [iterators](http://docs.python.org/3/tutorial/classes.html#iterators) and [generators](http://docs.python.org/3/tutorial/classes.html#generators).
Reading binary file and looping over each byte
[ "", "python", "file-io", "binary", "" ]
I'm new to ASP.net, how can I read parameters passed from ASP.net page (<http://website.com/index.aspx?id=12&nam=eee>). Any small example will be appreciated, just something for me to start from.
Using your sample URL: ``` string id = Request.QueryString["id"]; string nam = Request.QueryString["nam"]; ``` Read about [Request.QueryString on MSDN](http://msdn.microsoft.com/en-us/library/system.web.httprequest.querystring.aspx). You probably want to convert the `id` value to an int.
For security reasons, be careful with XSS attacks. Please use this library: <http://msdn.microsoft.com/en-us/library/aa973813.aspx> Example: ``` String Name = AntiXss.HtmlEncode(Request.QueryString["Name"]); ```
How to read parameter passed from asp.net page, using C#?
[ "", "c#", "asp.net-2.0", "" ]
I'm currently working on a multi-threaded application, and I occasionally receive a concurrently modification exception (approximately once or twice an hour on average, but occurring at seemingly random intervals). The faulty class is essentially a wrapper for a map -- which extends `LinkedHashMap` (with accessOrder set to true). The class has a few methods: ``` synchronized set(SomeKey key, SomeValue val) ``` The set method adds a key/value pair to the internal map, and is protected by the synchronized keyword. ``` synchronized get(SomeKey key) ``` The get method returns the value based on the input key. ``` rebuild() ``` The internal map is rebuilt once in a while (~every 2 minutes, intervals do not match up with the exceptions). The rebuild method essentially rebuilds the values based on their keys. Since rebuild() is fairly expensive, I did not put a synchronized keyword on the method. Instead, I am doing: ``` public void rebuild(){ /* initialization stuff */ List<SomeKey> keysCopy = new ArrayList<SomeKey>(); synchronized (this) { keysCopy.addAll(internalMap.keySet()); } /* do stuff with keysCopy, update a temporary map */ synchronized (this) { internalMap.putAll(tempMap); } } ``` The exception occurs at ``` keysCopy.addAll(internalMap.keySet()); ``` Inside the synchronized block. Suggestions are greatly appreciated. Feel free to point me to specific pages/chapters in *Effective Java* and/or *Concurrency in Practice*. Update 1: Sanitized stacktrace: ``` java.util.ConcurrentModificationException at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(LinkedHashMap.java:365) at java.util.LinkedHashMap$KeyIterator.next(LinkedHashMap.java:376) at java.util.AbstractCollection.toArray(AbstractCollection.java:126) at java.util.ArrayList.addAll(ArrayList.java:473) at a.b.c.etc.SomeWrapper.rebuild(SomeWraper.java:109) at a.b.c.etc.SomeCaller.updateCache(SomeCaller.java:421) ... ``` Update 2: Thanks everyone for the answers so far. I think the problem lies within the LinkedHashMap and its accessOrder attribute, although I am not entirely certain atm (investigating). **If accessOrder on a LinkedHashMap is set to true, and I access its keySet then proceed to add the keySet to a linkedList via addAll, do either of these actions mutate the order (i.e. count towards an "access")?**
If you constructed LinkedHashMap with accessOrder = true then LinkedHashMap.get() actually mutates the LinkedHashMap since it stores the most recently accessed entry at the front of the linked list of entries. Perhaps something is calling get() while the array list is making its copy with the Iterator.
This exception does not normally have anything to do with synchronization - it is normally thrown if a a Collection is modified while an Iterator is iterating through it. AddAll methods may use an iterator - and its worth noting that the posh foreach loop iterates over instances of Iterator too. e.g: ``` for(Object o : objects) { objects.remove(o); } ``` is sufficient to get the exception on some collections (e.g ArrayList). James
Concurrent Modification Exception
[ "", "java", "collections", "concurrency", "" ]
Is there a way to plot a chart with Google chart API so that the X-axis values are days in a month? I have data points that are not provided with the same frequency. For example: ``` Date - Value 1/1/2009 - 100 1/5/2009 - 150 1/6/2009 - 165 1/13/2009 - 200 1/20/2009 - 350 1/30/2009 - 500 ``` I want to make a chart that will separate each data point with the relative distance based on time during a month. This can be done with Excel, but how can I calculate and display it with Google chart? Other free solutions similar to Google chart or a free library that can be used with ASP.NET are also welcome.
> **UPDATE** This is now supported directly in the Chart API using the advanced graphs "annotated chart" feature - <https://developers.google.com/chart/interactive/docs/gallery/annotationchart> I have done this on my ~~[ReHash Database Statistics](http://rehash.dustinfineout.com/db_stats.php "ReHash Database Statistics")~~ chart (even though the dates turned out to be evenly spaced, so it doesn't exactly demonstrate that it's doing this). First, you want to get your **overall time period**, which will be analogous to the overall width of your chart. To do this we subtract the earliest date from the latest. I prefer to use Unix-epoch timestamps as they are integers and easy to compare in this way, but you could easily calculate the number of seconds, etc. Now, loop through your data. For each date we want the *percentile* in the overall period that the date is from the beginning (i.e. the earliest date is 0, the latest is 100). For each date, you first want to calculate the **distance of the present date** from the earliest date in the data set. Essentially, "how far are we from the start". So, subtract the earliest date from the present date. Then, to find the percentile, we divide the **distance of the present date** by the **overall time period**, and then multiply by 100 and truncate or round any decimal to give our integral **x-coordinate**. And it is as simple as that! Your x-values will range from 0 (the left-side of the chart) to 100 (the right side) and each data point will lie at a distance from the start respective of its true temporal distance. If you have any questions, feel free to ask! I can post pesudocode or PHP if desired.
I had the same problem, found [scatter plots](http://code.google.com/apis/ajax/playground/?type=visualization#scatter_chart) on Google Charts, it does exactly what is necessary. Here's the code I ended up with (took theirs as a starting point): ``` function drawVisualization() { // Create and populate the data table. var data = new google.visualization.DataTable(); data.addColumn('date', 'Date'); data.addColumn('number', 'Quantity'); data.addRow([new Date(2011, 0, 1), 10]) data.addRow([new Date(2011, 1, 1), 15]) data.addRow([new Date(2011, 3, 1), 40]) data.addRow([new Date(2011, 6, 1), 50]) // Create and draw the visualization. var chart = new google.visualization.ScatterChart( document.getElementById('visualization')); chart.draw(data, {title: 'Test', width: 600, height: 400, vAxis: {title: "cr", titleTextStyle: {color: "green"}}, hAxis: {title: "time", titleTextStyle: {color: "green"}}, lineWidth: 1} ); } ``` Note that they seem to count months from 0, i.e. January is 0, February is 1, ..., December is 11.
How to use dates in X-axis with Google chart API?
[ "", "javascript", "asp.net", "vb.net", "google-visualization", "" ]
Newbie question... The objective: * I intend to have an HTML text input field as a kind of command line input. * An unordered HTML list shows the 5 most recent commands. Clicking on one of the last commands in this list should populate the command line input text field with the respective command (in order to re-execute or modify it). * An unordered HTML list contains a result set. Clicking on an ID in this list should bring the respective ID into the command line input text field. **In HTML (DHTML):** Works as expected: when clicking on the the link the command line input text field is populated with a recent command. ``` <li><a href="#" id="last_cmd_01" onclick="document.getElementById('cli_input').value = document.getElementById('last_cmd_01').firstChild.nodeValue;document.getElementById('cli_input').focus()">here would be one of the recent commands</a></li> ``` **In Javascript file:** Doesn't work as expected: when clicking on the the link the command-line-input-text-field gets populated with the respective value (as it should), BUT then it seems like the full HTML page is being reloaded, the text input field and all dynamically populated lists become empty. ``` function exec_cmd(cli_input_str) { // a lot of code ... // the code that should provide similar behavior as onclick=... in the DHTML example $('.spa_id_href').click(function(){document.getElementById('cli_input').value = document.getElementById('cli_input').value + this.firstChild.nodeValue;}); } ``` **Now the Question:** Besides a potential Javascript (syntax) error, what could cause the browser to reload the page?
Change ``` $('.spa_id_href').click(function(){... ``` to ``` $('.spa_id_href').click(function(evt){...//notice the evt param ``` and in the function, call ``` evt.preventDefault(); ```
In both cases, you do nothing to cancel the default function of clicking on a link. In the plain HTML example, the link to the top of the page is followed. You don't specify what the href attribute for the second example looks like, but whatever it is, it will be followed. See <http://icant.co.uk/articles/pragmatic-progressive-enhancement/> for a good explanation of event cancelling and good event design. See <http://docs.jquery.com/Tutorials:How_jQuery_Works> for some jQuery specific guidance.
Javascript function results in HTML page reload: why?
[ "", "javascript", "jquery", "dom", "dhtml", "command-line-interface", "" ]
We are developing a c# application that imports **address-data** into a CRM-system. The CSV-file contains an address-column like 'Somethingstreet 34'. Our CRM however uses two **different fields for the streetname and the housenumber**. Of course, in the given example this poses no problem. But our Dutch addressing-system can be a bit of a pain. Real world examples: * Somestreet 88a (where 'Somestreet' is the streetname and 88a the housenumber) * 2e van Blankenburgstraat 123a (where '2e van Blankenburgstraat' is the streetname, and '123a' is the housenumber) * 2e van Blankenburgstraat 123-a (where '2e van Blankenburgstraat' is the streetname, and '123-a' is the housenumber) * 2e van Blankenburgstraat 123 a (where '2e van Blankenburgstraat' is the streetname, and '123 a' is the housenumber) Now I'm looking for a nice function (RegEx or something) that splits these addresslines correctly into two fields. Is there a nice clean way to do this ? --- **edit:** I did some further investigation on our addressing system and it seems (thank you government) that the above examples are not even the 'worst' ones. Some more (these are real streets and numbers): * Rivium 1e Straat 53/ET6 (where 'Rivium 1e Straat' is the street and '53/ET6' is the housenumber) * Plein 1940-1945 34 (where 'Plein 1940-1945' is the street and '34' is the housenumber) * Apollo 11-Laan 11 (where 'Apollo 11-Laan' is the street and '11' (the second one) is the housenumber) * Charta 77 Vaart 159 3H (where 'Charta 77 Vaart' is the streetname and '159 3H' is the housenumber) * Charta 77 Vaart 44/2 (where 'Charta 77 Vaart' is the streetname and '44/2' is the housenumber)
The best solution for data correctness would be to compare the existing database against a known address api that has a function to do this for you. Otherwise you're just giving your best guess and some, if not all, of the data should be manually reviewed.
What I did, but I doubt that it is the most performant solution is to reverse the address and then get the first part till you find a digit and take them all. i.e. the regex `.*\d+` on the reversed address. This solves your problem when a street contains a digit.
Best way to split an address line into two fields
[ "", "c#", ".net", "import", "split", "street-address", "" ]