Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm curious how others have offered customizable forms to their website's users (who are primarily non-technical). It is possible that there is a library out there that achieves this, but I have not seen one. Some of the concerns are: * **Options for each form element** What kind of options to provide to the user, keeping in mind that all of these need to be persisted. * **Layout Customization** Is it enough to just have a top to bottom sequential layout. Is it really necessary to offer different layouts? (For instance, a two column layout) * **Database storage** Any efficient/relatively quick methods for storing the data entered in the form in a database. The issue here being that you don't know how many columns will be needed. And also, is it okay to store everything as a VARCHAR (losing some of the 'queryability' of dates/integer). * **Validation** Should validation be built in (dependant on field type), or customizable? There are a lot of possibilities, and I'm looking to see what others have used/offered and what they found to be effective. And any potential gotchas or whether it is not really worth it to offer this.
This is one of the holy grails of vertical market application software architecture. Many have tried, most have failed. See what Sharepoint does in this regard. You can't see the architecture, but you can see the user interface. Beyond a fairly trite level of complexity you will need to add technically literate people into the process. For example, an insurance platform called [ZygoWare](http://www.instimes.co.uk/story.asp?storyCode=340818) was released under the premise that it could be customised directly by the business. In practice this tends not to work very well on something like an insurance policy administration system and the product has a reputation for being difficult to implement. For something like salesforce.com or an online store builder the product is simpler, so it will be easier to achieve direct end-user customisation. At one point I was involved in specifying an insurance underwriting product. Supporting customisation in such a product has several key aspects: * Database schema - allowing the system to be configured with custom attributes. In commercial insurance a contract record can have 200 fields and may also have several complex structures sitting below it. * User interface. The system will need to record these, so a means to custom fields on a form is necessary. You may also need to set up other screens and database tables. * Business rules. You may want to use a business rules engine to support configurable business logic. This gets quite complex in its own right and the analyst designing the rule sets needs to be deeply familiar with both the business domain and the system architecture. * Workflows. Workflows are de rigeur in volume business and making inroads into large commercial business as well. In subscription markets your workflows involve third parties that may or may not actually have the facilities to participate in the workflow. * Products. A platform may need to support multiple insurance products (e.g. commericial property, life/health, marine cargo, motor, offshore energy). In order to avoid having to deploy a different policy administration system for each department in your company (A typical Lloyds syndicate employs 50-200 people) your platform must support different product lines in some way, possibly involving custom screens, workflows and business rules for the different products. This lives at the complex end of software customisation. In practice, software like this requires analyst and development skills to sucessfully implement a business solution. The domain and product are sufficiently complex that they are not feasible to implement without specialist skills. On that basis, my approach to customising a system has a few key pillars: **Recognise who will actually be customising the system** Build it to suit them. In the case above the right level is a team of analysts and developers working for the vendor, in-house (contractors and permanent staff) or a third party consultancy. The appropriate level of abstraction is a scripting language that allows extension (on a per-product basis), a form building tool (such as QT designer or Visual Studio), a database schema management tool and possibly a rule engine such as Ilog. In the case of an on-line store builder a power user could reasonably figure out how to do it themselves. **Address what needs to be customised** In the case of an insurance platform you will have customisation at a level that you are rolling out a substantially bespoke system. The system architecture for this should allow extensions to be plugged in without having to regression test the whole system. In the case of an online store you are substantially customising the layout of the displays and configuring account information with payment providers. **Don't delude yourself about the complexity of the problem.** Don't try to dumb down a system beyond its natural level. History is littered with people who thought they could make a platform that end users could use to build and maintain a complex business application. The *only* commercially successful example of such a product is a spreadsheet. If you want to see how well this works in practice, try spending some time working in the back office of a large finance company. Most regulatory authorities such as the FSA take a dim view of 'end-user computing' and the regulatory environments of such industries drive many FTEs worth of time-consuming CYA and manual controls over such processes. It is quite common to find the same computation done redundantly in multiple areas within the back office of such an organisation and the results reconciled against each other to provide a manual control so somebody can feel safe signing off the figures.
I would not try to build a system like that from scratch. Creating a generic form building application that would be able to edit data of any shape, as well as edit the layout, is indeed a holy grail. Entire companies have been built around this; take a look at, for example: www.wufoo.com, or Microsoft Office InfoPath. Simpler efforts include Google Spreadsheet (with its form editing / data entry piece), but it's a bit too simplistic for most scenarios.
Providing customizable forms to non-technical users
[ "", "php", "database", "forms", "" ]
I have a list of strings that can contain a letter or a string representation of an int (max 2 digits). They need to be sorted either alphabetically or (when it is actually an int) on the numerical value it represents. Example: ``` IList<string> input = new List<string>() {"a", 1.ToString(), 2.ToString(), "b", 10.ToString()}; input.OrderBy(s=>s) // 1 // 10 // 2 // a // b ``` What I would want is ``` // 1 // 2 // 10 // a // b ``` I have some idea involving formatting it with trying to parse it, then if it is a successfull tryparse to format it with my own custom stringformatter to make it have preceding zeros. I'm hoping for something more simple and performant. **Edit** I ended up making an IComparer I dumped in my Utils library for later use. While I was at it I threw doubles in the mix too. ``` public class MixedNumbersAndStringsComparer : IComparer<string> { public int Compare(string x, string y) { double xVal, yVal; if(double.TryParse(x, out xVal) && double.TryParse(y, out yVal)) return xVal.CompareTo(yVal); else return string.Compare(x, y); } } //Tested on int vs int, double vs double, int vs double, string vs int, string vs doubl, string vs string. //Not gonna put those here [TestMethod] public void RealWorldTest() { List<string> input = new List<string>() { "a", "1", "2,0", "b", "10" }; List<string> expected = new List<string>() { "1", "2,0", "10", "a", "b" }; input.Sort(new MixedNumbersAndStringsComparer()); CollectionAssert.AreEquivalent(expected, input); } ```
Perhaps you could go with a more generic approach and use a [natural sorting](https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/) algorithm such as the C# implementation [here](http://www.codeproject.com/KB/recipes/NaturalComparer.aspx).
Two ways come to mind, not sure which is more performant. Implement a custom IComparer: ``` class MyComparer : IComparer<string> { public int Compare(string x, string y) { int xVal, yVal; var xIsVal = int.TryParse( x, out xVal ); var yIsVal = int.TryParse( y, out yVal ); if (xIsVal && yIsVal) // both are numbers... return xVal.CompareTo(yVal); if (!xIsVal && !yIsVal) // both are strings... return x.CompareTo(y); if (xIsVal) // x is a number, sort first return -1; return 1; // x is a string, sort last } } var input = new[] {"a", "1", "10", "b", "2", "c"}; var e = input.OrderBy( s => s, new MyComparer() ); ``` Or, split the sequence into numbers and non-numbers, then sort each subgroup, finally join the sorted results; something like: ``` var input = new[] {"a", "1", "10", "b", "2", "c"}; var result = input.Where( s => s.All( x => char.IsDigit( x ) ) ) .OrderBy( r => { int z; int.TryParse( r, out z ); return z; } ) .Union( input.Where( m => m.Any( x => !char.IsDigit( x ) ) ) .OrderBy( q => q ) ); ```
Sorting mixed numbers and strings
[ "", "c#", "sorting", "formatting", "tostring", "" ]
I want to return two values, one of which is a new object. I can do this using `std::pair`: ``` class A { //... }; std::pair<A*, int> getA() { A* a = new A; //... } ``` To make the code exception-safe, I would like to do: ``` std::pair<std::auto_ptr<A>, int> getA() { std::auto_ptr<A> a(new A); //... } ``` But this won't compile as the `auto_ptr` cannot be copied without modifying the `auto_ptr` being copied. Ok, this means `auto_ptr` does not compose well like other types (in one more way). What is a good way of returning a new object in this case? One alternative is to return a `shared_ptr` and another is an inout reference. But I am looking for some other alternative. I can do something like: ``` class AGetter { void getAExecute() { //... // set a_ and i_ } std::auto_ptr<A> getA() const { return a_.release(); } int getInt() const { return i_; } private: std::auto_ptr<A> a_; int i_; }; ``` Is there a better way?
Just create a new class and return that class ``` class Result { A* a; int i; public: Result( A*a, int i ) : a(a), i(i) { } ~Result() { delete a; } // access functions, copy constructor, ... }; Result getA() { //... return Result(new A, intValue); } ```
There are two major ways to handle this problem: 1. Do the cleanup yourself, via try/catch. 2. Use some kind of automated memory management, like `shared_ptr`. `auto_ptr` doesn't really work in these sorts of cases, as you discovered, but the new standard and Boost both contain reference-counted pointers that do what you want. Let us know what you don't like about `shared_ptr`, and maybe we can suggest an alternative.
Returning a new object along with another value
[ "", "c++", "auto-ptr", "" ]
A search query returned this error. I have a feeling its because the in clause is ginormous on a subordinant object, when I'm trying to ORM the other object. Apparently in clauses shouldn't be built 1 parameter at a time. Thanks ibatis.
Your best bet is to revise your application to pass less than 2100 parameters to the stored procedure. This is a [DBMS limit that can't be raised](http://msdn.microsoft.com/en-us/library/ms143432.aspx).
I got this same error when using an apparently innocent LINQ to SQL query. I just wanted to retrieve all the records whose ids were amongst the ones stored in an array: ``` dataContext.MyTable.Where(item => ids.Contains(item.Id)).ToArray(); ``` It turned out that the ids array had more than 2100 items, and it seems that the DataContext adds one parameter for each item in the array in the resulting SQL query. At the end it was a bug in my code, since the ids array had not to have so many items. But anyway it is worth to keep in mind that some extra validation is needed when using such constructs in LINQ to SQL.
Too many parameters were provided in this RPC request. The maximum is 2100.?
[ "", "c#", ".net", "sql-server", "ibatis.net", "" ]
In PHP, I have a string like this: ``` $string = "user@domain.com MIME-Version: bla bla bla"; ``` How do i get the email address only? Is there any easy way to get the value??
If you're not sure which part of the space-separated string is the e-mail address, you can split the string by spaces and use ``` filter_var($email, FILTER_VALIDATE_EMAIL) ``` on each substring.
Building on mandaleeka's answer, break the string up using a space delimeter then use filter\_var to sanitize then validate to see if what remains is a legitimate email address: ``` function extract_email_address ($string) { foreach(preg_split('/\s/', $string) as $token) { $email = filter_var(filter_var($token, FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL); if ($email !== false) { $emails[] = $email; } } return $emails; } ```
How to get email address from a long string
[ "", "php", "string", "email", "" ]
How to 'union' 2 or more DataTables in C#? Both table has same structure. Is there any build-in function or should we do manually?
You are looking most likely for the [DataTable.Merge](http://msdn.microsoft.com/en-us/library/system.data.datatable.merge.aspx) method. **Example**: ``` private static void DemonstrateMergeTable() { DataTable table1 = new DataTable("Items"); // Add columns DataColumn idColumn = new DataColumn("id", typeof(System.Int32)); DataColumn itemColumn = new DataColumn("item", typeof(System.Int32)); table1.Columns.Add(idColumn); table1.Columns.Add(itemColumn); // Set the primary key column. table1.PrimaryKey = new DataColumn[] { idColumn }; // Add RowChanged event handler for the table. table1.RowChanged += new System.Data.DataRowChangeEventHandler(Row_Changed); // Add ten rows. DataRow row; for (int i = 0; i <= 9; i++) { row = table1.NewRow(); row["id"] = i; row["item"] = i; table1.Rows.Add(row); } // Accept changes. table1.AcceptChanges(); PrintValues(table1, "Original values"); // Create a second DataTable identical to the first. DataTable table2 = table1.Clone(); // Add column to the second column, so that the // schemas no longer match. table2.Columns.Add("newColumn", typeof(System.String)); // Add three rows. Note that the id column can't be the // same as existing rows in the original table. row = table2.NewRow(); row["id"] = 14; row["item"] = 774; row["newColumn"] = "new column 1"; table2.Rows.Add(row); row = table2.NewRow(); row["id"] = 12; row["item"] = 555; row["newColumn"] = "new column 2"; table2.Rows.Add(row); row = table2.NewRow(); row["id"] = 13; row["item"] = 665; row["newColumn"] = "new column 3"; table2.Rows.Add(row); // Merge table2 into the table1. Console.WriteLine("Merging"); table1.Merge(table2, false, MissingSchemaAction.Add); PrintValues(table1, "Merged With table1, schema added"); } private static void Row_Changed(object sender, DataRowChangeEventArgs e) { Console.WriteLine("Row changed {0}\t{1}", e.Action, e.Row.ItemArray[0]); } private static void PrintValues(DataTable table, string label) { // Display the values in the supplied DataTable: Console.WriteLine(label); foreach (DataRow row in table.Rows) { foreach (DataColumn col in table.Columns) { Console.Write("\t " + row[col].ToString()); } Console.WriteLine(); } } ```
You could try this: ``` public static DataTable Union (DataTable First, DataTable Second) { //Result table DataTable table = new DataTable("Union"); //Build new columns DataColumn[] newcolumns = new DataColumn[First.Columns.Count]; for(int i=0; i < First.Columns.Count; i++) { newcolumns[i] = new DataColumn( First.Columns[i].ColumnName, First.Columns[i].DataType); } table.Columns.AddRange(newcolumns); table.BeginLoadData(); foreach(DataRow row in First.Rows) { table.LoadDataRow(row.ItemArray,true); } foreach(DataRow row in Second.Rows) { table.LoadDataRow(row.ItemArray,true); } table.EndLoadData(); return table; } ``` From [here](http://weblogs.sqlteam.com/davidm/archive/2004/01/15/724.aspx) (not tested).
How to 'union' 2 or more DataTables in C#?
[ "", "c#", "datatable", "" ]
I have four DB tables in an Oracle database that need to be rewritten/refreshed every week or every month. I am writing this script in PHP using the standard OCI functions, that will read new data in from XML and refresh these four tables. The four tables have the following properties TABLE A - up to 2mil rows, one primary key (One row might take max 2K data) TABLE B - up to 10mil rows, one foreign key pointing to TABLE A (One row might take max 1100 bytes of data) TABLE C - up to 10mil rows, one foreign key pointing to TABLE A (One row might take max 1100 bytes of data) TABLE D - up to 10mil rows, one foreign key pointing to TABLE A (One row might take max 120 bytes of data) So I need to repopulate these tables without damaging the user experience. I obviously can't delete the tables and just repopulate them as it is a somewhat lengthy process. I've considered just a big transaction where I DELETE FROM all of the tables and just regenerate them. I get a little concerned about the length of the transaction (don't know yet but it could take an hour or so). I wanted to create temp table replicas of all of the tables and populate those instead. Then I could DROP the main tables and rename the temp tables. However you can't do the DROP and ALTER table statements within a transaction as they always do an auto commit. This should be able to be done quickly (four DROP and and four ALTER TABLE statements), but it can't guarantee that a user won't get an error within that short period of time. Now, a combination of the two ideas, I'm considering doing the temp tables, then doing a DELETE FROM on all four original tables and then and INSERT INTO from the temp tables to repopulate the main tables. Since there are no DDL statements here, this would all work within a transaction. Then, however, I wondering if the memory it takes to process some 60 million records within a transaction is going to get me in trouble (this would be a concern for the first idea as well). I would think this would be a common scenario. Is there a standard or recommended way of doing this? Any tips would be appreciated. Thanks.
Am I the only one (except Vincent) who would first test **the simplest possible solution**, i.e. DELETE/INSERT, before trying to build something more advanced? > Then, however, I wondering if the memory it takes to process some 60 million records within a transaction is going to get me in trouble (this would be a concern for the first idea as well). Oracle manages memory quite well, it hasn't been written by a bunch of Java novices (oops it just came out of my mouth!). So the real question is, do you have to worry about the performance penalties of thrashing REDO and UNDO log files... In other words, build a performance test case and run it on your server and see how long it takes. During the DELETE / INSERT the system will be not as responsive as usual but other sessions can still perform SELECTs without any fears of deadlocks, memory leaks or system crashes. Hint: DB servers are usually disk-bound, so getting a proper RAID array is usually a very good investment. On the other hand, if the performance is critical, you can select one of the alternative approaches described in this thread: * partitioning if you have the license * table renaming if you don't, but be mindful that DDLs on the fly can cause some side effects such as object invalidation, ORA-06508...
You could have a synonym for each of your big tables. Create new incarnations of your tables, populate them, drop and recreate the synonyms, and finally drop your old tables. This has the advantage of (1) only one actual set of DML (the inserts) avoiding redo generation for your deletes and (2) the synonym drop/recreate is very fast, minimizing the potential for a "bad user experience". Reminds me of a minor peeve of mine about Oracle's synonyms: why isn't there an ALTER SYNONYM command?
How to do monthly refresh of large DB tables without interrupting user access to them
[ "", "php", "database", "oracle", "" ]
I'm using a progress bar to display the battery status. If the user clicks on the progress bar i want to display a popup with details. Excluding the solution that requires checking if the click coordonates is in the bounds of the progress bar has anyone found another solution or a workaround to this?
OK, an easier way to do the custom control is to just start with a UserControl, drop a ProgressBar on it and dock it so that it fills the UserControl, then expose the ProgressBar as a public property of the UserControl, so that your code would say ``` myProgressBar1.ProgressBar.Max = 100 ``` instead of ``` progressBar1.Max = 100 ``` Then just use the Click event of the usercontrol to show the details (I think you might have to disable the inner ProgressBar for the click to work, but that shouldn't affect the appearance of the progress bar). This way your user control looks exactly like a regular progress bar (and, hence, like ass). :)
Also, it's generally considered good form to only use controls in the way that users are accustomed to. Progress bars are meant (and traditionally used) only to display information. This is why they removed all the interaction events in Compact Framework. I think a better approach would be to leave the progress bar as it is, and add a "Details" LinkLabel above or next to the bar.
Progress bar click (Compact framework)
[ "", "c#", "compact-framework", "progress-bar", "" ]
I would like to get the dimensions (coordinates) for all the HTML elements of a webpage as they are rendered by a browser, that is the positions they are rendered at. For example, `(top-left,top-right,bottom-left,bottom-right)` Could not find this in lxml. So, is there any library in Python that does this? I had also looked at Mechanize::Mozilla in Perl but, that seems difficult to configure/set-up. I think the best way to do this for my requirement is to use a rendering engine - like WebKit or Gecko. Are there any perl/python bindings available for the above two rendering engines? Google searches for tutorials on how to "plug-in" to the WebKit rendering engine is not very helpful.
I was not able to find any easy solution (ie. Java/Perl/Python :) to hook onto Webkit/Gecko to solve the above rendering problem. The best I could find was the [Lobo rendering engine](http://lobobrowser.org/) written in Java which has a very clear API that does exactly what I want - access to both DOM and the rendering attributes of HTML elements. [JRex](http://jrex.mozdev.org/docs.html) is a Java wrapper to Gecko rendering engine.
lxml isn't going to help you at all. It isn't concerned about front-end rendering at all. To accurately work out how something renders, you need to render it. For that you need to hook into a browser, spawn the page and run some JS on the page to find the DOM element and get its attributes. It's totally possible but I think you should start by looking at how website screenshot factories work (as they'll share 90% of the code you need to get a browser launching and showing the right page). You may want to still use lxml to inject your javascript into the page.
Finding rendered HTML element positions using WebKit (or Gecko)
[ "", "python", "html", "perl", "rendering", "rendering-engine", "" ]
What is the difference between a `Class` and a `Class<?>` declaration. * `Class a;` * `Class<?> b;`
It's the same as with all generic and raw types: ``` Class // An unknown class (raw type) Class<?> // An unknown class (generic version) Class<String> // The String class ``` In this special case there's not much practical difference between `Class` and `Class<?>` because they both denote an unknown class. Depending on the existing declarations the compiler can demand a generic type instead of a raw type. **But:** Since Java 1.5 you should use the generic form wherever possible. `Class<?>` clearly states that you mean "an unknown class", `Class<String>` cleary states that you mean the `String` class. A raw `Class` could mean *both*. In the end it makes not much of a difference to the compiler but it makes a huge difference in making the intentions of your code more understandable and maintainable.
Class [javadoc](http://java.sun.com/javase/6/docs/api/java/lang/Class.html): > **Type Parameters:** > `T` - the type of the class modeled by this `Class` object. For example, the type of `String.class` is `Class<String>`. Use `Class<?>` if the class being modeled is unknown. Use of `Class` without the type parameter is similar to using any generic class (`Map`, `List`, etc.) without the type parameter - either it's a pre-1.5 legacy usage or it's just a segment of code that does not care about unchecked type casting.
Difference between Class and Class<?>
[ "", "java", "generics", "" ]
Is it possible to break the execution of a Python script called with the execfile function without using an if/else statement? I've tried `exit()`, but it doesn't allow `main.py` to finish. ``` # main.py print "Main starting" execfile("script.py") print "This should print" # script.py print "Script starting" a = False if a == False: # Sanity checks. Script should break here # <insert magic command> # I'd prefer not to put an "else" here and have to indent the rest of the code print "this should not print" # lots of lines below ```
`main` can wrap the `execfile` into a `try`/`except` block: `sys.exit` raises a SystemExit exception which `main` can catch in the `except` clause in order to continue its execution normally, if desired. I.e., in `main.py`: ``` try: execfile('whatever.py') except SystemExit: print "sys.exit was called but I'm proceeding anyway (so there!-)." print "so I'll print this, etc, etc" ``` and `whatever.py` can use `sys.exit(0)` or whatever to terminate *its own* execution only. Any other exception will work as well as long as it's agreed between the source to be `execfile`d and the source doing the `execfile` call -- but `SystemExit` is particularly suitable as its meaning is pretty clear!
``` # script.py def main(): print "Script starting" a = False if a == False: # Sanity checks. Script should break here # <insert magic command> return; # I'd prefer not to put an "else" here and have to indent the rest of the code print "this should not print" # lots of lines bellow if __name__ == "__main__": main(); ``` I find this aspect of Python (the `__name__` == `"__main__`", etc.) irritating.
Stop execution of a script called with execfile
[ "", "python", "control-flow", "execfile", "" ]
I have 3 models: Books, Notifications, and NotificationTypes. Books have notifications as the Notification model has a book\_id. Notifications have one notification\_type as the Notification model has one notification\_type\_id I want all Books created between date1 and date2 ``` books_set1 = Book.find :all, :conditions => ["created_at <= ? AND show_time >= ?", max_date, min_date] ``` But I do not want books that have notifications of notification.notification\_type\_id = 1 and ideally i would like to say this by referring to notification\_type.name so i would not want books that have notifications of notification.notification\_type.name = 'type1' If there has been a notification of type1 created for a book already, I do not want it returned in the set (because i am going to create notifications of that type with the returned set). I am not sure if there is a way to do this in one query, I am thinking I need 2 queries with and INTERSECT - the first I already included in this post and the second i am not sure about. But in pseudo-code, i think this is what it needs to do: ``` notification_type_id = Notification.find_by_name('type1') get all notifications where notification_id = notification_type_id set2 = get the associated book set from the notification set (since each notification has one book) ``` then i do set1 - set2 **UPDATE** Thanks to some help I have written two queries that get me the desired results. I would love for this to be in 1 query if anyone knows how to do it: ``` books_in_range = Book.find :all, :conditions => ["created_at <= ? AND created_at >= ?", max_date, min_date] books_without_these_notifications = Book.find(:all, :joins => { :notifications => :notification_type }, :conditions => ["notification_types.name = ?","type1"] ) books_to_consider = books_in_range - books_without_these_reminders ``` Again, the idea is to get all books that do not have a notification of type1 created and fall within a specific date range.
You could do it with NOT EXISTS but I'm not sure how efficient it would be: ``` Book.find( :all, :conditions => ['created_at <= ? AND show_time >= ? AND NOT EXISTS (SELECT * FROM notifications INNER JOIN notification_types ON notifications.notification_type_id = notification_types.id WHERE notification_types.name = ? AND notifications.book_id = books.id)', max_date, min_date, 'type1' ]) ``` You might be able to come at it from a different direction and keep track of those which *have* had a notification of type1 sent out by adding a boolean to books or some other object joined directly to books. Then your query could be: ``` Book.find(:all, :conditions => ['created_at <= ? AND show_time >= ? AND type1_notification_sent = ?', max_date, min_date, false ]) ```
The following should work: ``` Book.scoped(:conditions => ["created_at <= ? AND show_time >= ?", max_date, min_date]).find(:all, :joins => { :notifications => :notification_types }, :conditions => ["notification_type.name <> ?", "type1"]) ``` Extract some of the arguments into `named_scope`s or local variables for extra clarity. *Updated to reflect the negation.*
SQL noob needs help writing a Rails query involving joins and maybe intersect
[ "", "sql", "ruby-on-rails", "" ]
I just came across something pretty weird to me : when you use the Equals() method on a value type (and if this method has not been overriden, of course) you get something *very very* slow -- fields are compared one to one using reflection ! As in : ``` public struct MyStruct{ int i; } (...) MyStruct s, t; s.i = 0; t.i = 1; if ( s.Equals( t )) /* s.i will be compared to t.i via reflection here. */ (...) ``` My question : why does the C# compiler do not generate a simple method to compare value types ? Something like (in MyStruct's definition) : ``` public override bool Equals( Object o ){ if ( this.i == o.i ) return true; else return false; } ``` The compiler knows what are the fields of MyStruct at compile time, why does it wait until runtime to enumerate MyStruct fields ? Very strange to me. Thanks :) **ADDED** : Sorry, I just realize that, of course, `Equals` is not a language keyword but a runtime method... The compiler is completely unaware of this method. So it make sens here to use reflection.
The following is the decompiled ValueType.Equals method from mscorlib: ``` public override bool Equals(object obj) { if (obj == null) { return false; } RuntimeType type = (RuntimeType) base.GetType(); RuntimeType type2 = (RuntimeType) obj.GetType(); if (type2 != type) { return false; } object a = this; if (CanCompareBits(this)) { return FastEqualsCheck(a, obj); } FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); for (int i = 0; i < fields.Length; i++) { object obj3 = ((RtFieldInfo) fields[i]).InternalGetValue(a, false); object obj4 = ((RtFieldInfo) fields[i]).InternalGetValue(obj, false); if (obj3 == null) { if (obj4 != null) { return false; } } else if (!obj3.Equals(obj4)) { return false; } } return true; } ``` When possible, a bit-wise comparison will be done (note the CanCompareBits and FastEqualsCheck, both of which are defined as InternalCall. The JIT would presumably inject the appropriate code here. As to why it is so slow, I couldn't tell you.
It doesn't use reflection *when it doesn't need to*. It just compare values bit by bit in case the `struct` if it can do so. However, there if any of the `struct` members (or members of members, any descendants) override `object.Equals` and provide its own implementation, obviously, it can't rely on bit-by-bit comparison to calculate the return value. The reason it's slow is that the parameter to `Equals` is of type `object` and value types have to be boxed to be treated as an `object`. Boxing involves allocating memory on the heap and memory copying the value type to that location. You could manually provide an overload for the `Equals` method that takes your own `struct` as parameter to prevent boxing: ``` public bool Equals(MyStruct obj) { return obj.i == i; } ```
C# - Value Type Equals method - why does the compiler use reflection?
[ "", "c#", "compiler-construction", "struct", "" ]
I'm working my way through some C++ training. So far so good, but I need some help reinforcing some of the concepts I am learning. My question is how do I go about visualizing the byte patterns for objects I create. For example, how would I print out the byte pattern for structs, longs, ints etc? I understand it in my head and can understand the diagrams in my study materials, I'd just like to be able to programaticially display byte patterns from within some of my study programs. I realize this is pretty trivial but any answers would greatly help me hammer in these concepts. Thanks. Edit: I use mostly XCode for my other development projects, but have VMs for Windows7 and fedora core. At work I use XP with visual studio 2005. ( I can't comment as I am still a n00b here :D) I used unwind's solution which is about what I am looking for. I am also thinking that maybe I could just use the dos DEBUG command as I'd also like to look at chunks for memory too. Again, this is just to help me reinforce what I am learning. Thanks again people!
You can use a function such as this, to print the bytes: ``` static void print_bytes(const void *object, size_t size) { #ifdef __cplusplus const unsigned char * const bytes = static_cast<const unsigned char *>(object); #else // __cplusplus const unsigned char * const bytes = object; #endif // __cplusplus size_t i; printf("[ "); for(i = 0; i < size; i++) { printf("%02x ", bytes[i]); } printf("]\n"); } ``` Usage would look like this, for instance: ``` int x = 37; float y = 3.14; print_bytes(&x, sizeof x); print_bytes(&y, sizeof y); ``` This shows the bytes just as raw numerical values, in hexadecimal which is commonly used for "memory dumps" like these. On a random (might even be virtual, for all I know) Linux machine running a "Intel(R) Xeon(R)" CPU, this prints: ``` [ 25 00 00 00 ] [ c3 f5 48 40 ] ``` This handily also demonstrates that the Intel family of CPU:s really are [little endian](http://en.wikipedia.org/wiki/Endianness).
If you are using gcc and X, you can use the [DDD debugger](http://www.gnu.org/software/ddd/) to draw pretty pictures of your data structures for you.
How to visualize bytes with C/C++
[ "", "c++", "c", "" ]
I'm trying to dump a list of all active threads including the current stack of each. I can get a list of all threads using threading.enumerate(), but i can't figure out a way to get to the stack from there. Background: A Zope/Plone app freaks out from time to time, consuming 100% of cpu and needs to be restarted. I have a feeling it's a loop which doesn't terminate properly, but i cannot reproduce it in the test-environemt for verification. I managed to register a signal handler which can be triggered from the outside, so i can trigger some code as soon as the situation occurs again. If I could dump the stacktrace for all active threads, that would give me a clue what goes wrong. The hole thing runs on python 2.4... Any ideas on how to trace down situations like these are appreciated :) Cheers, Chriss
When using Zope, you want to install [`Products.signalstack`](http://pypi.python.org/pypi/Products.signalstack) or [mr.freeze](https://pypi.python.org/pypi/mr.freeze); these were designed for just this purpose! Send a USR1 signal to your Zope server and it'll immediately dump stack traces for all threads to the console. It'll do this even if all Zope threads are locked up. Under the hood these packages indirectly use [`threadframes`](http://web.archive.org/web/20100111034624/https://majid.info/blog/threadframe-multithreaded-stack-frame-extraction-for-python/); for Python versions 2.5 and up, when *not* using Zope, you can build the same functionality using the [`sys._current_frames()`](https://docs.python.org/2/library/sys.html#sys._current_frames) function to access per-thread stack frames. As of [Zope 2.12.5](https://github.com/zopefoundation/Zope/commit/16796274463f21327e1b7bb3831b39eb671460af) this functionality is integrated into Zope itself, and there is no need to install additional packages anymore.
As jitter points out in an earlier answer `sys._current_frames()` gives you what you need for v2.5+. For the lazy the following code snippet worked for me and may help you: ``` print >> sys.stderr, "\n*** STACKTRACE - START ***\n" code = [] for threadId, stack in sys._current_frames().items(): code.append("\n# ThreadID: %s" % threadId) for filename, lineno, name, line in traceback.extract_stack(stack): code.append('File: "%s", line %d, in %s' % (filename, lineno, name)) if line: code.append(" %s" % (line.strip())) for line in code: print >> sys.stderr, line print >> sys.stderr, "\n*** STACKTRACE - END ***\n" ```
Dump stacktraces of all active Threads
[ "", "python", "multithreading", "plone", "zope", "" ]
I'm really bad at Javascript and I'm struggling to get my head round it. What I'm trying to do is get something to select all checkboxes. However everything I have found tries to do it by name, I want to do it by ID or class. Select all by name is just inpractical isn't it?
Using [JQuery](http://www.jquery.com), you can do this very easilly! ``` $(".ClassName").attr("checked", "true"); ``` or a single ID ``` $("#ID").attr("checked", "true"); ``` See: [Check All Checkboxes with JQuery](http://www.iknowkungfoo.com/blog/index.cfm/2008/7/9/Check-All-Checkboxes-with-JQuery).
``` var array = document.getElementsByTagName("input"); for(var ii = 0; ii < array.length; ii++) { if(array[ii].type == "checkbox") { if(array[ii].className == YOUR_CLASS_NAME) { array[ii].checked = true; } } } ``` by ID: ``` var checkbox = document.getElementById(YOUR_ID); if(null != checkbox) checkbox.checked = true; ```
Select All Checkboxes By ID/Class
[ "", "javascript", "" ]
I have some POCOs and there are corresponding persistence objects that do the CRUD. What is a good name for the persistence objects? I've seen people use the term "service objects" for these, but when I think service, I think WCF. Maybe "persistence objects" is the best, but I'd like to hear what other people think.
One common convention is the Repository pattern when dealing with persisting objects to a datastore, so you would expect to see naming conventions in the form of (given an corresponding type Poco): ``` PocoRepository ```
I believe you are looking for the "Data Access Object", or DAO suffix. Say you have the concept of a customer in your code, and a customer table in your database, then you may end up with the following model: * **CustomerDAO** - A class that maps directly to the customer table. This is your "Persistence class". Maybe it has some technical fields such as database index id or sequence * **Customer** - A class that represents your business logic. Maybe this lacks some of your database related fields, but has some additional business related fields or methods. For instance when you store a birthdate it may have a calculateAge() method. * **CustomerDTO** - A class that represents what your API exposes to the outside world. This means it may not expose birthdate due to privacy reasons. But instead it may expose additional fields such as "coupons" because it may be useful for the caller to obtain these as well. As Kevin Swiber already referenced above and linked to Martin Fowler Often you'll see these 3 functions being performed by one and the same class, but this is not considered best practice. Unless you are building a very simple application, splitting them up is better. Whether this is worth the effort and does not overengineer/overcomplicate things is a design decision you have to make. Sources: <https://en.wikipedia.org/wiki/Data_access_object>
Persistence Object Naming Convention
[ "", "c#", "naming-conventions", "poco", "" ]
Lets say I am calling some web service method that I do not control. This method takes a long time to run, and whoever developed the web service did not think to include a asynchronous version. What is the best way to create an asynchronous wrapper for such a method in C#/winforms? At the moment I am using a ThreadPool to run the webservice method and then calling an event when the webservice finishes. Something like this. ``` DoWorkAsync() { Webservice.LongMethod() WorkCompleteEvent() } ``` However, this doesn't appear to be ideal. For example, if I try to modify the form controls from the event handler I get a warning about not doing that from a different thread etc. Does anyone have any other suggestions for solving this problem?
See the MSDN article on [How to: Make Thread-Safe Calls to Windows Forms Controls](http://msdn.microsoft.com/en-us/library/ms171728.aspx) & also Jon Skeet's great [guide to threading](http://www.yoda.arachsys.com/csharp/threads/index.shtml) more specifically [Threading in Windows Forms](http://www.yoda.arachsys.com/csharp/threads/winforms.shtml). Quoting Jon (emphasis mine): > Never invoke any method or property on a control created on another thread other than *Invoke*, *BeginInvoke*, *EndInvoke* or *CreateGraphics*, and *InvokeRequired*. > Each control is effectively bound to a thread which runs its message pump. **If you try to access or change anything in the UI (for example changing the Text property) from a different thread, you run a risk of your program hanging or misbehaving in other ways.** You may get away with it in some cases, but only by blind luck. **Fortunately, the Invoke, BeginInvoke and EndInvoke methods have been provided so that you can ask the UI thread to call a method for you in a safe manner.**
The solution is to use built in asynchronous solution to the web services. Use the webservice.BeginLongMethod() to call and use the IAsyncResult. But remember that you must always use Invoke methods to update windows forms code since it is on a different thread. See following articles <http://www.informit.com/articles/article.aspx?p=29395&seqNum=4> <http://msdn.microsoft.com/en-us/library/ms228972.aspx>
Making a Webservice Method Asynchronous in C#/Winforms
[ "", "c#", "winforms", "asynchronous", "event-handling", "" ]
here is working java code ``` class Cup { public String sayColor() { return "i have a color ."; } } class TCup extends Cup{ public String sayColor(){ System.out.println(super.getClass().getName()); return super.sayColor()+"color is tee green."; } } class MyTCup extends TCup { public String sayColor(){ System.out.println(super.getClass().getName()); return super.sayColor()+"but brushed to red now!"; } } class Test { public static void main(String[] args) { Cup c = new MyTCup(); System.out.print(c.sayColor()); } } ``` and running the Test class prints ``` MyTCup MyTCup i have a color .color is tee green.but brushed to red now! ``` question 1: At the runtime, the type of object C is MyTCup, but it can always call the super method. Is there a method stack in the memory within MyTCup after initializing the object, and then can call through at runtime like the code ? question 2: There is no way to call the super method in other objects. As I know ,c++ can cast to call parent method at any time. Why is it different in Java?
You can't call the super method in other objects - that would violate encapsulation. The whole point is that the object controls what its overridden methods do. For instance, you might override a collection's `add` method to throw an exception in certain circumstances, so it could ensure only "valid" items got added to the collection. That would be pointless if callers could just bypass it with a cast! The only reason an object gets to call `super.foo()` for itself is to enable one call to be implemented by using the parent implementation. It's up to the code in the class to make sure it only ever does that sensibly. Again, to take the add-in-a-collection example, if the collection overrides `add` it would have to have *some* way of adding the validated item to the collection, which it would do with `super.add()`. Note that for the same reason of encapuslation, you can *only* call your parent implementation, not the grandparent implementation - so `super.foo()` is valid, but `super.super.foo()` isn't.
1: Your question is not quite clear. What do you mean by "call through at runtime like the code"? If you are asking how instance c knows what its super class is, then yes, the class hierarchy is stored in memory, and can be accessed by the VM. 2: Java actually does allow you to cast an instance to its parent. It's just that calling a method on an instance always uses the instance's actual class, not its compile-time class. I.e. in Java all methods are what would be called "virtual" in C++. Why this was decided I do not know. *Edit:* Actually Jon Skeet explains very nicely why you cannot call a method of a super class on an instance of a sub class, so now I know :-).
Can java call parent overridden method in other objects but not subtype?
[ "", "java", "overriding", "" ]
My generic method needs to serialize the object passed to it, however just insisting that it implements ISerializable doesn't seem to work. For example, I have a struct returned from a web service (marked with SerializableAttribute) that serializes to xml just fine, but, as expected, the C# compiler complains. Is there a way I can check the object is serializable before attempting to serialize it, or, better still, a way of using the `where` keyword to check the object is suitable? Here's my full method: ``` public static void Push<T>(string url, T message) where T : ISerializable { string xml = SerializeMessage(message); // Send the message to Amazon SQS SendMessageRequest sendReq = new SendMessageRequest { QueueUrl = url, MessageBody = xml }; AmazonSQSClient client = new AmazonSQSClient(S3User, S3Pass); client.SendMessage(sendReq); } ``` And SerializeMessage: ``` private static string SerializeMessage<T>(T message) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); using (StringWriter stringWriter = new StringWriter()) { xmlSerializer.Serialize(stringWriter, message); return stringWriter.ToString(); } } ``` If this isn't possible, what's the best way to perform a check that an object is serializable at runtime?
You can't do this totally via generic constraints, but you can do a couple things to help: 1) Put the **new()** constraint on the generic type (to enable the ability to deserialize and to ensure the XmlSerializer doesn't complain about a lack of default ctor): ``` where T : new() ``` 2) On the first line of your method handling the serialization (or constructor or anywhere else you don't have to repeat it over and over), you can perform this check: ``` if( !typeof(T).IsSerializable && !(typeof(ISerializable).IsAssignableFrom(typeof(T)) ) ) throw new InvalidOperationException("A serializable Type is required"); ``` Of course, there's still the possibility of runtime exceptions when trying to serialize a type, but this will cover the most obvious issues.
I wrote a length blog article on this subject that you may find helpful. It mainly goes into binary serialization but the concepts are applicable to most any serialization format. * <http://blogs.msdn.com/jaredpar/archive/2009/03/31/is-it-serializable.aspx> The long and short of it is * There is no way to add a reliable generic constraint * The only way to check and see if an object **was** serializable is to serialize it and see if the operation succeeds
How can I add a type constraint to include anything serializable in a generic method?
[ "", "c#", "generics", "attributes", "serializable", "" ]
I am trying to display a element from mysql table in a input box type=text. The data is a string value. But i can see only the first word of the entire string. but if i echo the element, i get the full string value. My code looks like this: ``` echo "Title: <input type=\"text\" name=\"title\" value=".$row['Title']."></input><br>"; ``` Please let me know what am i doing wrong here. Best Zeeshan
You haven't enclosed the text in quotes in the resulting HTML, try this: ``` echo "Title: <input type=\"text\" name=\"title\" value=\"".$row['Title']."\"></input><br>"; ``` or better still ``` echo 'Title: <input type="text" name="title" value="'.$row['Title'].'"></input><br>'; ``` which avoids having to escape the double quotes.
You're missing quotes around the attribute value: ``` echo "<input type=\"text\" name=\"title\" value=\"" . htmlspecialchars($row['Title']) . "\"><br>" ``` Also you should use htmlspecialchars incase the title contains `"` or `<>`. Finally, there is no `</input>`
Problem displaying the entire string in input box (in php)
[ "", "php", "html", "" ]
When you search google, it estimates the number of search results e.g. > Results 1 - 10 of about 103,000,000 for hello world How do I get the number 103,000,000 programmically? I'm not interested in the results, just that number, and I need to do about 100 of these searches at a time so webpage scrapping is not an option since google tends to block this kind of thing. I've seen solutions where you can use the google soap API to do this but that's no longer an option since it's deprecated and they're no longer giving away API keys, and the AJAX API doesn't seem to offer this field :/
I completed this using C# with Bing instead of Google. You can find the answer here: [Google Search API - Number of Results](https://stackoverflow.com/questions/4231663/google-search-api-number-of-results)
When the search object is returned, it will have a property of 'results' as an array that contains the results objects, and a 'Cursor' property that contains the cursor object that has an estimatedResultsCount property. That's the fella your after.
Estimated number of search results Google search API
[ "", "javascript", "google-search-api", "google-ajax-api", "" ]
How do you pass a class type into a function in C#? As I am getting into db4o and C# I wrote the following function after reading the tutorials: ``` public static void PrintAllPilots("CLASS HERE", string pathToDb) { IObjectContainer db = Db4oFactory.OpenFile(pathToDb); IObjectSet result = db.QueryByExample(typeof("CLASS HERE")); db.Close(); ListResult(result); } ```
There are two ways. The first is to explicitly use the Type type. ``` public static void PrintAllPilots(Type type, string pathToDb) { ... IObjectSet result = db.QueryByExample(type); } PrintAllPilots(typeof(SomeType),somePath); ``` The second is to use generics ``` public static void PrintAllPilots<T>(string pathToDb) { ... IObjectSet result = db.QueryByExample(typeof(T)); } PrintAllPilots<SomeType>(somePath); ```
The answers given by by Jon, Jared, and yshuditelu use query-by-example which is largely unused DB4o querying mechanism, and could potentially be deprecated in the future. The preferred methods of querying on DB4O for .NET is native queries and LINQ. ``` // Query for all Pilots using DB4O native query: var result = db.Query<Pilot>(); ``` Or alternatively using Linq-to-DB4O: ``` // Query for all Pilots using LINQ var result = from Pilot p in db select p; ``` Both of these work provided you know the type (e.g. Pilot) at compile time. If you don't know the type at compile time, you can instead use a DB4O SODA query: ``` var query = db.Query(); query.Constrain(someObj.GetType()); var results = query.Execute(); ``` *edit* Why use LINQ instead of SODA, Query-by-Example (QBE), or Native Query (NQ)? Because LINQ makes it very natural to do query expressions. For example, here's how you'd query for pilots named Michael: ``` var michaelPilots = from Pilot p in db where p.Name == "Michael" select p; ``` And LINQ is composable, meaning you can do things like this: ``` var first20MichaelPilots = michaelPilots.Take(20); ``` And you'll still get an efficient query executed in DB4O when you iterate over the results. Doing the same in SODA or QBE or NQ is ugly at best.
Querying by type in DB4O
[ "", "c#", ".net", "function", "db4o", "argument-passing", "" ]
Can anyone tell me why the following code might not cycle through the array of colors defined here: ``` var colors = ["white", "yellow", "orange", "red"]; ``` and here is the line of code in question: ``` setInterval(function(){ currElm.style.background = colors[(nextColor++)%(colors.length)]); }, 500); ``` It seems like that should work and I've seen several examples where code just like this produced a color cycling effect. Does anyone see a problem with the above (or below) code? Whole function(a work in progress): ``` function setHighlight(elmId, index, songLength){ //alert("called set highlight, params are " + elmId + " " + index + " " + songLength); var colors = ["white", "yellow", "orange", "red"]; var nextColor = 0; if(index < 10) index = "000" + (index); else if (index < 100) index = "000" + (index); else if(index < 1000) index = "0" + (index); if(index >= 1000) index = index; //alert("called set highlight, params are " + elmId + " " + index + " " + songLength); //this will be useful for finding the element but pulsate will not work, need to research animations in javascript var mainElm = document.getElementById('active_playlist'); var elmIndex = ""; for(var currElm = mainElm.firstChild; currElm !== null; currElm = currElm.nextSibling){ if(currElm.nodeType === 1){ var elementId = currElm.getAttribute("id"); if(elementId.match(/\b\d{4}/)){ elmIndex = elementId.substr(0,4); alert(currElm.getAttribute('id')); if(elmIndex == index){ setInterval(function(){ currElm.style.background = colors[(nextColor++)%(colors.length)]); }, 500); } } } }//end for } ``` All help is greatly appreciated. Thanks
A couple of different things. First, it looks like you are matching elements whose ids contain a space followed by 4 digits. I don't think that spaces are allowed in ids. I'd really like to see the HTML for the elements that should be matched. Second, I think you want to assign currElm to a new variable that will be captured in your setInterval handler. If you don't, I think it may always refer to the last element matched instead of each element matched. ``` for(var currElm = mainElm.firstChild; currElm !== null; currElm = currElm.nextSibling){ if(currElm.nodeType === 1){ var elementId = currElm.getAttribute("id"); if(elementId.match(/\b\d{4}/)){ elmIndex = elementId.substr(0,4); alert(currElm.getAttribute('id')); if(elmIndex == index){ var that = currElm; setInterval(function(){ that.style.background = colors[(nextColor++)%(colors.length)]; }, 500); } } } }//end for ``` **EDIT** Also fix the extra parenthesis in the interval handler.
Syntax error, extra right parenthesis `')'` at end of line: ``` currElm.style.background = colors[(nextColor++)%(colors.length)]); ```
cycling through background colors with javascript
[ "", "javascript", "background", "" ]
I'm looking to write a notification application where I'd like to provide popup notifications from the taskbar similiar to the ones in MSN Messenger or most other chat programs. Are there any good examples using VB .NET or C#, ideally without using Win32 calls? Thanks.
I found a better solution for what I'm looking to to do: <http://msdn.microsoft.com/en-us/magazine/cc163732.aspx>
Perhaps try this, modeled after Outlook rather than MSN Messenger, but of course you can still tweak it: <http://www.codeguru.com/csharp/csharp/cs_misc/userinterface/article.php/c10139>
MSN Messenger like notification - Do you know any examples in .NET VB .NET or C#?
[ "", "c#", "vb.net", "notifications", "taskbar", "" ]
Normally, if I want to force a link to open in a new tab (or window) when posting to my blog, I have to either use the link GUI and select "open in new window", or, since I use the HTML view by default, after inserting a link, manually add the "target=" portion of the tag: ``` <a href="http://link.to/something.great" target="_blank">link text</a> ``` Is there a plugin or hook location I can use to automatically insert the target attribute, or am I stuck doing it manually? **EDIT:** I am looking specifically for a way to modify the link while I am creating it in the editor. If that isn't possible, then maybe a hack on the save process. But I don't want a "run-time" front-end hack, which isn't necessarily permanent.
Then there is always a plugin <http://wordpress.org/extend/plugins/target-blank-in-posts-and-comments/>
If you use jQuery 1.3+ you can easily do this with the following line of JavaScript: ``` $("a:not([href^='http://your.website-url.here']").attr('target', '_blank'); ``` Just add this to the `load()` event of jQuery.
How can I force links to automatically open in a new window?
[ "", "php", "wordpress", "" ]
``` $result = $db_con->query("SELECT SQL_CALC_FOUND_ROWS * FROM users LIMIT 0,10"); $count_result = $db_con->query("SELECT FOUND_ROWS() as totalcount"); $row = $count_result->fetch_assoc(); $total = $row['totalcount']; ``` $total keeps returning 0 even though the $result contains all the user rows in it. ``` ini_set("mysql.trace_mode", "0"); ``` I found out about this setting via searching a similar Q on here, but it did not resolve my issue. When I use the 2 select statements in my MySQL client it always outputs the right count. Just can't seem to figure out how to get it working on my php page. PHP Version: 5.2.5 build 6 MySQL Version: 5.1.30 Note: The code I provided here is not being used on my actual project, however, it does exemplify the problem I am having with not being able to retrieve the total count. This code, from what I've read about found\_rows(), should work but it doesn't.
On php.net I found someone with maybe the same problem. He is speaking of a race condition that could occur: [php.net](https://www.php.net/manual/en/function.mysql-num-rows.php#85654). Basically he solves this problem by temporary locking the table at the cost of slowing things down.
**`LIMIT` is required to make found\_rows() work correctly** Add a LIMIT to the end of your query, ie. ``` SELECT SQL_CALC_FOUND_ROWS * FROM users LIMIT 0,10; ``` <http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows> `FOUND_ROWS()` -- For a SELECT with a LIMIT clause, the number of rows that would be returned were there no LIMIT clause
FOUND_ROWS() keeps returning 0
[ "", "php", "select", "count", "" ]
I am tryng to loop through an xml doc and I am still getting the first element in the second iteration, not sure what I am missing. Can anyone help? Pretty new with Xpath ``` string file = HttpContext.Current.Server.MapPath("~/XML/Locations.xml"); Dictionary<string, Location> locationCollection = new Dictionary<string, Location>(); XPathDocument xDocument = new XPathDocument(file); XPathNavigator xPathNavigator = xDocument.CreateNavigator(); foreach (XPathNavigator node in xPathNavigator.Select("//locations/*")) { string value = node.SelectSingleNode("/locations/location/cell").Value; } <?xml version="1.0" encoding="utf-8" ?> <locations> <location> <locationName>Glendale</locationName> <street>3717 San Fernando Road</street> <city>Glendale</city> <state>CA</state> <zipcode>91204</zipcode> <generalManager>DJ Eldon</generalManager> <phone>(818) 552‐6246</phone> <tollFree>(888) 600‐6011</tollFree> <fax>(818) 552‐6248</fax> <cell>(347) 834‐2249</cell> <counterEmail>BUR@Eaglerider.com</counterEmail> <directEmail>DJ@Eaglerider.com</directEmail> </location> <location> <locationName>Chicago</locationName> <street>1301 S. Harlem Ave.</street> <city>Chicago</city> <state>IL</state> <zipcode>60402</zipcode> <generalManager>Dave Schnulle</generalManager> <phone>(708) 749‐1500</phone> <tollFree>(888) 966‐1500</tollFree> <fax>(818) 552‐6248</fax> <cell>(708) 749‐3800</cell> <counterEmail>ORD@Eaglerider.com</counterEmail> <directEmail>Dave@Eaglerider.com</directEmail> </location> </locations> ```
You're effectively ignoring the value of `node` by using a leading slash to get back to the document root. Try this instead: ``` // This assumes that there are only location nodes under locations; // You may want to use //locations/location instead foreach (XPathNavigator node in xPathNavigator.Select("//locations/*")) { string value = node.SelectSingleNode("cell").Value; // Use value } ``` Having said that, is there any reason you're not doing it in a single XPath query? ``` // Name changed to avoid scrolling :) foreach (XPathNavigator node in navigator.Select("//locations/location/cell")) { string value = node.Value; // Use value } ```
Try the following: ``` XPathNodeIterator ni = xPathNavigator.Select("//locations/*"); while (ni.MoveNext()) { string value = ni.Current.Value); } ``` Just a quick blurt, hope it helps you.
looping through items using xPath
[ "", "c#", "asp.net", "xpath", "" ]
I am randomly getting an org.datanucleus.exceptions.ClassNotPersistableException when I try to perform a query on the local JDO data store of my GWT/App Engine application. This only happens when I run the application on Hosted mode. When I deploy it to the Google App Engine everything works perfectly. Stack Trace: ``` org.datanucleus.exceptions.ClassNotPersistableException: The class "com.wayd.server.beans.WinePost" is not persistable. This means that it either hasnt been enhanced, or that the enhanced version of the file is not in the CLASSPATH (or is hidden by an unenhanced version), or the Meta-Data/annotations for the class are not found. at org.datanucleus.jdo.NucleusJDOHelper.getJDOExceptionForNucleusException(NucleusJDOHelper.java:305) at org.datanucleus.ObjectManagerImpl.getExtent(ObjectManagerImpl.java:3700) at org.datanucleus.jdo.JDOPersistenceManager.getExtent(JDOPersistenceManager.java:1515) at com.wayd.server.WinePostServiceImpl.getPosts(WinePostServiceImpl.java:212) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:527) ... 25 more Caused by: org.datanucleus.exceptions.ClassNotPersistableException: The class "com.wayd.server.beans.WinePost" is not persistable. This means that it either hasnt been enhanced, or that the enhanced version of the file is not in the CLASSPATH (or is hidden by an unenhanced version), or the Meta-Data/annotations for the class are not found. at org.datanucleus.ObjectManagerImpl.assertClassPersistable(ObjectManagerImpl.java:3830) at org.datanucleus.ObjectManagerImpl.getExtent(ObjectManagerImpl.java:3693) ... 32 more) ``` WinePost class is a very simple JDO persistence capable class: @PersistenceCapable(identityType = IdentityType.APPLICATION) public class WinePost { ``` @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private User author; @Persistent private String grape; @Persistent private String comment; public WinePost(final User author, final String grape, final String comment) { super(); this.grape = grape; this.comment = comment; } public User getAuthor() { return author; } public void setAuthor(final User author) { this.author = author; } public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getGrape() { return grape; } public void setGrape(final String grape) { this.grape = grape; } public String getComment() { return comment; } public void setComment(final String comment) { this.comment = comment; } public String getUserNickname() { String retVal = null; if (author != null) { retVal = author.getNickname(); } return retVal; } public WinePostModel getWinePostModel() { final WinePostModel winePostModel = new WinePostModel(grape, vintage, getUserNickName()); return winePostModel; } ``` } The datastore query is performed by the following method: ``` public ArrayList<WinePostModel> getPosts() { final ArrayList<WinePostModel> posts = new ArrayList<WinePostModel>(); final PersistenceManager persistenceManager = PMF.get() .getPersistenceManager(); final Extent<WinePost> winePostExtent = persistenceManager.getExtent( WinePost.class, false); for (final WinePost winePost : winePostExtent) { posts.add(winePost.getWinePostModel()); } winePostExtent.closeAll(); return posts; } ```
I am pretty sure there's nothing wrong with your code. The reason you get this error is because of a problem with the Datanucleus enhancer. If you see this error, quit Jetty and check the console inside Eclipse (you'll need to select the correct console in the little toolbar above the console window). It should say something like: DataNucleus Enhancer (version 1.1.4) : Enhancement of classes DataNucleus Enhancer completed with success for **X** classes. Timings : input=547 ms, enhance=76 ms, total=623 ms. Consult the log for full details ... where **X** is the number of classes it has processed. The number should be equal to the number of 'entity' classed you have defined. But sometimes, for some reason it will say 0 which is why you get the ClassNotPersistableException error. To fix, open an entity class and change something (add a space or something) and save. Check the console until it says that it has enhanced all of your entity classes. Then restart the debugger and try again.
Posting for future reference for anybody running into same problem, despite this being an old thread. I ran into the 'same' problem, and found that my classpath had multiple instances of datanucleus-appengine-1.0.7.final.jar. I got to know this from the log which was prompted when I tried to build my workspace. Here's the log content. java.lang.RuntimeException: Unexpected exception at com.google.appengine.tools.enhancer.Enhancer.execute(Enhancer.java:59) at com.google.appengine.tools.enhancer.Enhance.(Enhance.java:60) at com.google.appengine.tools.enhancer.Enhance.main(Enhance.java:41) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.google.appengine.tools.enhancer.Enhancer.execute(Enhancer.java:57) ... 2 more Caused by: org.datanucleus.exceptions.NucleusException: Plugin (Bundle) "org.datanucleus.store.appengine" is already registered. Ensure you dont have multiple JAR versions of the same plugin in the classpath. The URL "file:/G:/eclipse/plugins/com.google.appengine.eclipse.sdkbundle.1.3.4\_1.3.4.v201005212032/appengine-java-sdk-1.3.4/lib/user/orm/datanucleus-appengine-1.0.7.final.jar" is already registered, and you are trying to register an identical plugin located at URL "file:/G:/WS\_Quotemandu/quotemandu/war/WEB-INF/lib/datanucleus-appengine-1.0.7.final.jar." at org.datanucleus.plugin.NonManagedPluginRegistry.registerBundle(NonManagedPluginRegistry.java:434) at org.datanucleus.plugin.NonManagedPluginRegistry.registerBundle(NonManagedPluginRegistry.java:340) at org.datanucleus.plugin.NonManagedPluginRegistry.registerExtensions(NonManagedPluginRegistry.java:222) at org.datanucleus.plugin.NonManagedPluginRegistry.registerExtensionPoints(NonManagedPluginRegistry.java:153) at org.datanucleus.plugin.PluginManager.registerExtensionPoints(PluginManager.java:82) at org.datanucleus.OMFContext.(OMFContext.java:160) at org.datanucleus.enhancer.DataNucleusEnhancer.(DataNucleusEnhancer.java:172) at org.datanucleus.enhancer.DataNucleusEnhancer.(DataNucleusEnhancer.java:150) at org.datanucleus.enhancer.DataNucleusEnhancer.main(DataNucleusEnhancer.java:1157) ... 7 more G:/eclipse/plugins/com.google.appengine.eclipse.sdkbundle.1.3.4\_1.3.4.v201005212032/appengine-java-sdk-1.3.4/lib/user/orm/datanucleus-appengine-1.0.7.final.jar file:/G:/WS\_Quotemandu/quotemandu/war/WEB-INF/lib/datanucleus-appengine-1.0.7.final.jar Hope this helps!
Why do I get ClassNotPersistableException while running GWT App Engine application in hosted mode?
[ "", "java", "google-app-engine", "gwt", "" ]
I am working on an application to get data from a MS-SQL server (2005). In the command text, I can pass a sql query like this: ``` string query = "SELECT T1.f1, T1.f2, T2.f3 FROM table1 T1 join table2 T2" + "on T1.id = T2.id AND T1.dt = T2.dt ..." .... cmd.CommandText = query; ``` I could also put the query as a view on my SQL server like this: ``` CREATE VIEW V1 AS "SELECT T1.f1, ..." ``` Then I can use the view in a simplified query like this: ``` string query = "SELECT f1, f2, f3 FROM V1"; .... cmd.CommandText = query; ``` I am not sure which way is better. Will be the view be faster then a SQL query? By the way, the query I show here is a simplified one. The actual query SELECT is more complicated one.
I would create a VIEW for several reasons A) A well constructed view does tend to perform faster than a query, though with query optimization you may not notice much of a difference. B) It keeps knowledge of the database structure within the database itself - adding a good layer of abstraction (as a side note, consider using a stored procedure rather than an inline query - this also keeps database knowledge within the database itself) C) If you do need to make a structural change to the database, you can keep the view consistent without needing to rebuild your code. **AMENDMENT** I'm going to amend this answer in light of some of the comments so as to clarify some points ... It is absolutely true that a standard view does not provide any real performance gain over a query. A standard view is materialized at run time which essentially makes it no different than a convenient way to execute a query of the same structure. An index view, however, is materialized immediately and the results are persisted in physical storage. As with any design decision, the use of an indexed view should be carefully considered. There is no free lunch; the penalty you pay for use of indexed views comes in the form of additional storage requirements and overhead associated with maintaining the view when there are any changes to the underlying database. These are best used in instances of commonly used complex joining and aggregation of data from multiple tables and in cases in which data is accessed far more frequently than it is changed. I also concur with comments regarding structural changes - addition of new columns will not affect the view. If, however, data is moved, normalized, archived, etc it can be a good way to insulate such changes from the application. These situations are RARE and the same results can be attained through the use of stored procedures rather than a view.
In general I've found it's best to use views for several reasons: * Complex queries can get hard to read in code * You can change the view without recompiling * Related to that, you can handle changes in the underlying database structure in the view without it touching code as long as the same fields get returned There are probably more reasons, but at this point I would never write a query directly in code. You should also look into some kind of ORM (Object Relational Mapper) technology like LINQ to SQL (L2S). It lets you use SQL-like queries in your code but everything is abstracted through objects created in the L2S designer. (I'm actually moving our current L2S objects to run off of views, actually. It's a bit more complicated because the relationships don't come through as well... but it's allowing me to create one set of objects that run across 2 databases, and keep everything nicely abstracted so I can change the underlying table names to fix up naming conventions. )
Use SQL View or SQL Query?
[ "", "c#", "sql-server", "" ]
HI , In Java Script , var a ="apple-orange-mango" var b ="grapes-cheery-apple" var c = a + b // Merging with 2 variable var c should have value is "apple-orange-mango-grapes-cheery" .Duplicated should be removed. Thanks , Chells
Here's a brute force algorithm: ``` var a; var b; // inputs var words = split(a+b); var map = {}; var output; for( index in words ) { if( map[ words[index] ]!=undefined ) continue; map[ words[index] ] = true; output += (words[index] + '-'); } output[output.length-1]=' '; // remove the last '-' ``` The `map` acts as a hashtable. Thats it!
After your string is combined, you will want to split it using the delimiters (you can add these back in later). example: ``` var a ="apple-orange-mango" var b ="grapes-cheery-apple" var c = a + "-" + b var Splitted = c.split("-"); ``` the Splitted variable now contains an array such as [apples,orange,mango,grapes,cherry,apple] you can then use one of many [duplicate removing algorithms](http://www.martienus.com/code/javascript-remove-duplicates-from-array.html) to remove the duplicates. Then you can simply do this to add your delimiters back in: ``` result = Splitted.join("-"); ```
Merging the Strings
[ "", "javascript", "" ]
I'm new to a team working on a rather large project, with lots of components and dependencies. For every component, there's an `interfaces` package where the exposed interfaces for that component are placed. Is this a good practice? My usual practice has always been interfaces and implementations go in the same package.
Placing both the interface and the implementation is common place, and doesn't seem to be a problem. Take for example the Java API -- most classes have both interfaces and their implementations included in the same package. Take for example the [`java.util`](http://java.sun.com/javase/6/docs/api/java/util/package-summary.html) package: It contains the interfaces such as `Set`, `Map`, `List`, while also having the implementations such as `HashSet`, `HashMap` and `ArrayList`. Furthermore, the Javadocs are designed to work well in those conditions, as it separates the documentation into the *Interfaces* and *Classes* views when displaying the contents of the package. Having packages only for interfaces may actually be a little bit excessive, unless there are enormous numbers of interfaces. But separating the interfaces into their own packages just for the sake of doing so sounds like bad practice. If differentiating the name of a interface from an implementation is necessary, one could have a naming convention to make interfaces easier to identify: * *Prefix the interface name with an `I`.* This approach is taken with the interfaces in the .NET framework. It would be fairly easy to tell that `IList` is an interface for a list. * *Use the -`able` suffix.* This approach is seen often in the Java API, such as `Comparable`, `Iterable`, and `Serializable` to name a few.
For any language, putting them together in the same package is fine. The important thing is what's exposed to the outside world, and how it looks from outside. Nobody's going to know or care if the implementation is in that same package or not. Let's look at this particular instance. If you have all public things in one package, and private things in another package that is not publicly exposed, the client of the library sees one package. If you move the private things to the package with the publicly exposed things, but do not expose them from within the package, the client sees exactly the same thing. Thus, this has the smell of a rule with no good reason: it's making a decision based on something being publicly visible without that decision having any effect on what's publicly visible. That said, if in any particular instance it seems like a good idea to split the interface and implementation in to separate packages, go right ahead and do that. Reasons for doing this that come to mind are that the package is huge, or you have an alternate implementation you might want to link in instead of the standard one.
Should interfaces be placed in a separate package?
[ "", "java", "interface", "package", "" ]
programmer mates. I was testing java threading capabilities with a very simple code (or at least it *seemed* simple). I have this class Account: ``` public class Account { protected double balance; public synchronized void withdraw(double value) { this.balance = this.balance - value; } public synchronized void deposit(double value) { this.balance = this.balance + value; } public synchronized double getBalance() { return this.balance; } } ``` And I have two threads: `Depositer`, that deposits $10 a thousand times: ``` public class Depositer extends Thread { protected Account account; public Depositer(Account a) { account = a; } @Override public void run() { for(int i = 0; i < 1000; i++) { this.account.deposit(10); } } } ``` And `Withdrawer`, that withdraws $10 a thousand times: ``` public class Withdrawer extends Thread { protected Account account; public Withdrawer(Account a) { account = a; } @Override public void run() { for(int i = 0; i < 1000; i++) { this.account.withdraw(10); } } } ``` This arrangement is executed by: ``` public class Main { public static void main(String[] args) { Account account = new Account(); Thread c1 = new Depositer(account); Thread c2 = new Withdrawer(account); c2.start(); c1.start(); System.out.println(account.getBalance()); } } ``` As the methods are sychronized, I just expected that the balance was always 0 at the end, but this not happens sometimes. And I sincerely cannot figure out why. Can someone see where is my fault?
You do the following: ``` c2.start(); // Start a thread in the background c1.start(); // Start a 2nd thread in the background // print out the balance while both threads are still running System.out.println(account.getBalance()); ``` You need to wait for these threads to complete their processing: ``` c2.start(); // Start a thread in the background c1.start(); // Start a 2nd thread in the background try { c2.join(); // Wait until the c2 thread completes c1.join(); // Wait until the c1 thread completes } catch (InterruptedException e) { // LOG AN ERROR HERE } // print out the final balance System.out.println(account.getBalance()); ``` If you interrupt your main Thread then you'll need to *do* something with an interrupted exception. Assuming that none of your code does this, you should always, at a minimum, log the Exception. NOTE: You'll get the `InterruptedException` *not* if someone interrupts `c1` or `c2`, but if someone interrupts your main thread, the thread that calls `join()`. If someone has called `interrupt()` on your main thread but you don't check for it, then you'll probably get the `InterruptedException` the moment you call `join()`.
The `c2.start()` and `c1.start()` runs the process asynchronously. Your main thread needs to wait for those two threads to finish before printing out the results. Call ``` try { c2.join(); c1.join(); } catch (InterruptedException e) { e.printStackTrace(); } ``` before calling println. See [`join`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#join%28%29). > Waits for this thread to die.
Java synchronization not working as (I) expected
[ "", "java", "multithreading", "synchronization", "" ]
The db structure: ``` fid subid fieldname fieldval ``` To get a record for a person, I do something like this: ``` $querystr = " SELECT FN.sub_id, FN.`First Name` , LN.`Last Name` , DOB.`dob` , EMAIL.`email` , PHONE.`phone` FROM ( SELECT sub_id, field_val AS 'First Name' FROM $db->data WHERE `field_name` = 'First Name' )FN, ( SELECT sub_id, field_val AS 'Last Name' FROM $db->data WHERE `field_name` = 'Last Name' )LN, ( SELECT sub_id, field_val AS `Team` FROM $db->data WHERE `field_name` = 'Team' )TEAM, ( SELECT sub_id, field_val AS `dob` FROM $db->data WHERE `field_name` = 'DOB' )DOB, ( SELECT sub_id, field_val AS `email` FROM $db->data WHERE `field_name` = 'EMail' )EMAIL, ( SELECT sub_id, field_val AS `phone` FROM $db->data WHERE `field_name` = 'Telephone' )PHONE WHERE FN.sub_id = LN.sub_id AND LN.sub_id = DOB.sub_id and DOB.sub_id = EMAIL.sub_id and EMAIL.sub_id = PHONE.sub_id ORDER BY LN.`Last Name` "; ``` Any suggestions for how to streamline this?
You can make these many self-joins of table `data` more explicit, which makes the query more readable but most likely won't affect speed. I.e.: ``` SELECT FN.sub_id, FN.field_val AS `First Name`, LN.field_val AS `Last Name`, DOB.field_val AS `dob`, EMAIL.field_val AS `email`, PHONE.field_val AS `phone` FROM $db->data FN JOIN $db->data LN ON (LN.field_name = 'Last Name' AND LN.sub_id = FN.sub_id) JOIN $db->data TEAM ON (TEAM.field_name = 'Team' AND TEAM.sub_id = FN.sub_id) JOIN $db->data DOB ON (DOB.field_name = 'DOB' AND DOB.sub_id = FN.sub_id) JOIN $db->data EMAIL ON (EMAIL.field_name = 'EMail' AND EMAIL.sub_id = FN.sub_id) JOIN $db->data PHONE ON (PHONE.field_name = 'Telephone' AND PHONE.sub_id = FN.sub_id) WHERE FN.field_name = 'First Name' ORDER BY LN.field_val ``` Basically, the many tedious self-join are the price you pay for this "flexible" organization of the table as a collection of attribute names and values. BTW, if some of the data might be missing for a certain sub\_id and you still want to see that row in the output (with NULL for the missing data), use LEFT JOIN instead of plain JOIN for that field's instance of the data in the above query.
If it's possible, I would try to change your database schema, and make a Person table with all of those attributes (First Name, Last Name, Team, etc); it would be far more straightforward for someone who might later want to maintain this. That would make writing your query a cinch. Of course, I'm not aware of any additional requirements you might have. I'm also assuming your'e using this on a relational database that speaks SQL, and not some other database type.
Better SQL Query?
[ "", "sql", "" ]
I want to create a dictionary whose values are lists. For example: ``` { 1: ['1'], 2: ['1','2'], 3: ['2'] } ``` If I do: ``` d = dict() a = ['1', '2'] for i in a: for j in range(int(i), int(i) + 2): d[j].append(i) ``` I get a KeyError, because d[...] isn't a list. In this case, I can add the following code after the assignment of a to initialize the dictionary. ``` for x in range(1, 4): d[x] = list() ``` Is there a better way to do this? Lets say I don't know the keys I am going to need until I am in the second `for` loop. For example: ``` class relation: scope_list = list() ... d = dict() for relation in relation_list: for scope_item in relation.scope_list: d[scope_item].append(relation) ``` An alternative would then be replacing ``` d[scope_item].append(relation) ``` with ``` if d.has_key(scope_item): d[scope_item].append(relation) else: d[scope_item] = [relation,] ``` What is the best way to handle this? Ideally, appending would "just work". Is there some way to express that I want a dictionary of empty lists, even if I don't know every key when I first create the list?
You can use [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict): ``` >>> from collections import defaultdict >>> d = defaultdict(list) >>> a = ['1', '2'] >>> for i in a: ... for j in range(int(i), int(i) + 2): ... d[j].append(i) ... >>> d defaultdict(<type 'list'>, {1: ['1'], 2: ['1', '2'], 3: ['2']}) >>> d.items() [(1, ['1']), (2, ['1', '2']), (3, ['2'])] ```
You can build it with list comprehension like this: ``` >>> dict((i, range(int(i), int(i) + 2)) for i in ['1', '2']) {'1': [1, 2], '2': [2, 3]} ``` And for the second part of your question use [defaultdict](http://www.python.org/doc/2.5.2/lib/defaultdict-examples.html) ``` >>> from collections import defaultdict >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] >>> d = defaultdict(list) >>> for k, v in s: d[k].append(v) >>> d.items() [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] ```
Python creating a dictionary of lists
[ "", "python", "dictionary", "" ]
I need to build a Swing GUI like this [GUI Mockup http://img199.imageshack.us/img199/7271/mockupl.png](http://img199.imageshack.us/img199/7271/mockupl.png) where there are typically 40 tour columns. In each column there are typically up to 20 orders per tour. Orders may be grouped together within a tour. It should be possible to horizontally enlarge to columns, to D&D orders within a tour and to other tours. Later the representation might change including e.g. images. I once did something similar using JTable, but for this task I think a JTable is not the right solution. And because of the grouping of orders there are no real rows. Thought #1: I thought of using a JPanel, a LayoutManager (or NullLayout) and JComponents for this, but I am not sure if this is the way to go. Thought #2: Another possibility is to use a JPanel (in a scrollpanel), set it's size to correct value, override paintComponent, and paint everything myself (maybe by using an approach like TableCellRenderer for not needing to paint *everything* myself -- i.e. using *one* renderer per type to render, set it's values, use Graphics.translate and then component.paint...) In both approaches I need to implement the D&D code myself, #1 would make it possible to use the JComponents D&D implementation, but this wouldn't be that hard in #2 either. Inserting and removing of orders in #2 seems easier, since in #1 some LayoutManager (or in case of NullLayout all elements below) are involved, otherwise only a repaint is necessary. #1 might be a memory problem when that many JComponents are created, and the initial add(component) seems to be somewhat costly in my first tests. What do you think? How would you implement this? Or maybe is there some library for swing to create such a panel?
to expand on Thought #1: you could do this with a succession of JPanels. Your parent JPanel would layout a set of Tour panels in fixed width columns. the Tour classes could be panels that contain a TourHeader panel and a set of ItineraryItem panels. This might be heavier weight, but potentially easier for others to follow. you could also reconsider the JTable option. take a look at some of the JTable examples on [this ancient site](http://www.crionics.com/products/opensource/faq/swing_ex/SwingExamples.html) for some ideas for cells spanning rows.
The approach #1 should work. I did it several times. But if you want to make your drag and drop simpler I would suggest using JLists(without scroll panes) for your orders. You will be able to implement D&D within lists as well as between them if needed. To customize how order looks you can use renderers. On top of lists you can use panels or labels as tour headers. So I would create specialized TourView component with header on top and JList on the bottom. Then add many of TourViews to panel as you thought in case #1. In all cases, except when using JTable, you have to implement column enlarging yourself.
Planning view component in Swing
[ "", "java", "swing", "" ]
I am writting a test program for a server. At the test app, I try to connect a great number of clients to the server, but after a while a get all kind of errors like these : ``` Connection reset by peer: socket write error ``` or ``` java.net.SocketException: Connection reset ``` or ``` java.net.ConnectException: Connection refused: connect ``` I use a new socket for every client I connect to the server. Could someone enlighten me about this strange behaviour?
Unfortunately you haven't provided much details of your server's nature. I suppose you are writing a typical TCP server. In this answer I will *not* talk about any Java-specific details. The short advice is: insert a delay between clients connections. Without it you are actively simulating a DoS attack to your server. For the longer one, read below. Usually a TCP server creates only 1 *listening* socked by calling (in lovely C interface) `int sockfd = socket(...)` function, and passing the result (`sockfd` in our case) to `bind()` and `listen()` functions. After this preparations, the server would call an `accept()` which will steep the server in slumber (if the socket was marked as blocking) and if a client on the other side of the Earth will start calling a `connect()` function, than `accept()` (on the server side) with the support of the OS kernel will create *the connected socket*. The actual number of possible *pending connectins* can be known by looking at the `listen()` function. `listen()` has a *backlog* parameter which defines the maximum number of connection the *OS kernel* should queue to the socket (this is basically a sum of all connections in `SYN_RCVD` and `ESTABLISHED` states). Historically the recommended value for *backlog* in 1980s was something like 5 which is obviously miserable in our days. In FreeBSD 7.2, for example, a *hard limit* for *backlog* may be guessed by typing: ``` % sysctl kern.ipc.somaxconn kern.ipc.somaxconn: 128 ``` and in Fedora 10: ``` % cat /proc/sys/net/core/somaxconn 128 ``` P.S. Sorry for my terrible English.
There are OS and webserver limits how fast and how many connection you can start/accept. If you want to do performance testing on the server, try Apache JMeter as it has solutions to these limits.
Socket closed unexpectedly
[ "", "java", "sockets", "socketexception", "connectionexception", "" ]
Does Java have any syntax for managing exceptions that might be thrown when declaring and initializing a class's member variable? ``` public class MyClass { // Doesn't compile because constructor can throw IOException private static MyFileWriter x = new MyFileWriter("foo.txt"); ... } ``` Or do such initializations always have to be moved into a method where we can declare `throws IOException` or wrap the initialization in a try-catch block?
Use a static initialization block ``` public class MyClass { private static MyFileWriter x; static { try { x = new MyFileWriter("foo.txt"); } catch (Exception e) { logging_and _stuff_you_might_want_to_terminate_the_app_here_blah(); } // end try-catch } // end static init block ... } ```
it is best practice to move those sorts of initializations to methods that can property handle exceptions.
Unhandled exceptions in field initializations
[ "", "java", "exception", "initialization", "" ]
The code below consists of **two classes**: * **SmartForm** (simple model class) * **SmartForms** (plural class that contains a collection of **SmartForm** objects) I want to be able to instantiate both singular and plural classes **like this** (i.e. I don't want a factory method GetSmartForm()): ``` SmartForms smartForms = new SmartForms("all"); SmartForm smartForm = new SmartForm("id = 34"); ``` To consolidate logic, **only the plural class should access the database**. The singular class, when asked to instantiate itself, will simply instantiate a plural class, then pick the one object out of the the plural object's collection and ***become that object***. **How do I do that?** I tried to assign the object to `this` which doesn't work. ``` using System.Collections.Generic; namespace TestFactory234 { public class Program { static void Main(string[] args) { SmartForms smartForms = new SmartForms("all"); SmartForm smartForm = new SmartForm("id = 34"); } } public class SmartForm { private string _loadCode; public string IdCode { get; set; } public string Title { get; set; } public SmartForm() {} public SmartForm(string loadCode) { _loadCode = loadCode; SmartForms smartForms = new SmartForms(_loadCode); //this = smartForms.Collection[0]; //PSEUDO-CODE } } public class SmartForms { private string _loadCode; public List<SmartForm> _collection = new List<SmartForm>(); public List<SmartForm> Collection { get { return _collection; } } public SmartForms(string loadCode) { _loadCode = loadCode; Load(); } //fills internal collection from data source, based on "load code" private void Load() { switch (_loadCode) { case "all": SmartForm smartFormA = new SmartForm { IdCode = "customerMain", Title = "Customer Main" }; SmartForm smartFormB = new SmartForm { IdCode = "customerMain2", Title = "Customer Main2" }; SmartForm smartFormC = new SmartForm { IdCode = "customerMain3", Title = "Customer Main3" }; _collection.Add(smartFormA); _collection.Add(smartFormB); _collection.Add(smartFormC); break; case "id = 34": SmartForm smartForm2 = new SmartForm { IdCode = "customerMain2", Title = "Customer Main2" }; _collection.Add(smartForm2); break; default: break; } } } } ```
It doesn't have to be exactly the same object, it just has to appear to be the same to external observers. If you copy all the data from one object to another, it will accomplish the same thing. ``` public SmartForm(string loadCode) { _loadCode = loadCode; SmartForms smartForms = new SmartForms(_loadCode); this.IdCode = smartForms[0].IdCode; this.Title = smartForms[0].Title; } ```
You can't get one object to "become" another. Use static methods instead of constructors (and make the constructors private/internal/whatever so that only the static methods can access them). There are numerous benefits to using static methods over constructors: * You can return null if appropriate * You can return an existing object if appropriate * You can do plenty of work and *then* call a simple constructor which just sets fields The downside is they don't work with C# collection/object initializers :( An alternative to static methods (which don't work well with dependency injection, admittedly) is to have a separate factory and call instance methods on that.
How can I force a C# constructor to be a factory?
[ "", "c#", "constructor", "instantiation", "" ]
I want to partially specialize an existing template that I cannot change (`std::tr1::hash`) for a base class and all derived classes. The reason is that I'm using the curiously-recurring template pattern for polymorphism, and the hash function is implemented in the CRTP base class. If I only want to partially specialize for a the CRTP base class, then it's easy, I can just write: ``` namespace std { namespace tr1 { template <typename Derived> struct hash<CRTPBase<Derived> > { size_t operator()(const CRTPBase<Derived> & base) const { return base.hash(); } }; } } ``` But this specialization doesn't match actual derived classes, only `CRTPBase<Derived>`. What I want is a way of writing a partial specialization for `Derived` if and only if it derives from `CRTPBase<Derived>`. My pseudo-code is ``` namespace std { namespace tr1 { template <typename Derived> struct hash<typename boost::enable_if<std::tr1::is_base_of<CRTPBase<Derived>, Derived>, Derived>::type> { size_t operator()(const CRTPBase<Derived> & base) const { return base.hash(); } }; } } ``` ...but that doesn't work because the compiler can't tell that `enable_if<condition, Derived>::type` is `Derived`. If I could change `std::tr1::hash`, I'd just add another dummy template parameter to use `boost::enable_if`, as recommended by the `enable_if` documentation, but that's obviously not a very good solution. Is there a way around this problem? Do I have to specify a custom hash template on every `unordered_set` or `unordered_map` I create, or fully specialize `hash` for every derived class?
There are two variants in the following code. You could choose more appropriated for you. ``` template <typename Derived> struct CRTPBase { size_t hash() const {return 0; } }; // First case // // Help classes struct DummyF1 {}; struct DummyF2 {}; struct DummyF3 {}; template<typename T> struct X; // Main classes template<> struct X<DummyF1> : CRTPBase< X<DummyF1> > { int a1; }; template<> struct X<DummyF2> : CRTPBase< X<DummyF2> > { int b1; }; // typedefs typedef X<DummyF1> F1; typedef X<DummyF2> F2; typedef DummyF3 F3; // Does not work namespace std { namespace tr1 { template<class T> struct hash< X<T> > { size_t operator()(const CRTPBase< X<T> > & base) const { return base.hash(); } }; }} // namespace tr1 // namespace std // // Second case struct DummyS1 : CRTPBase <DummyS1> { int m1; }; // template<typename T> struct Y : T {}; // typedef Y<DummyS1> S1; namespace std { namespace tr1 { template<class T> struct hash< Y<T> > { size_t operator()(const CRTPBase<T> & base) const { return base.hash(); } }; }} // namespace tr1 // namespace std void main1() { using std::tr1::hash; F1 f1; F2 f2; F3 f3; hash<F1> hf1; size_t v1 = hf1(f1); // custom hash functor hash<F2> hf2; size_t v2 = hf2(f2); // custom hash functor hash<F3> hf3; size_t v3 = hf3(f3); // error: standard hash functor S1 s1; hash<S1> hs1; size_t w1 = hs1(s1); // custom hash functor } ```
Instead of modifying `std::tr1::hash` you should make your own namespace and define there new structure `hash` which inherited from `std::tr1::hash` or is specialized for `CRTPBase<Derived>`. ``` template <typename Derived> struct CRTPBase { size_t hash() {return 0; } }; struct AA : CRTPBase <AA> {}; struct BB {}; // namespace mynamespace { template <typename Some, typename Dummy=char> struct hash : std::tr1::hash<Some> {}; // template <typename Derived> struct hash<Derived, typename boost::enable_if< std::tr1::is_base_of<CRTPBase<Derived>, Derived>, char>::type > { size_t operator()(const CRTPBase<Derived> & base) const { return base.hash(); } }; } // namespace mynamespace {} // // void ff() { using namespace mynamespace; hash<AA> aa; // my hash hash<BB> bb; // std::tr1::hash } ```
How to partially specialize a class template for all derived types?
[ "", "c++", "derived-class", "partial-specialization", "crtp", "" ]
I'm writing a windows service that needs to sleep for long periods of time (15 hrs is the longest it will sleep, 30 mins is the shortest). I'm currently using **Thread.Sleep(calculatedTime)** to put my code into sleep mode. Is Thread.Sleep the best option or should I be using a timer? I've been googling this for a while and can't find a concise answer. Since this is a windows service, I don't have to worry about locking the UI, so I can't think of a reason not to use Thread.Sleep. Any insight would be appreciated.
I would use a timer, Thread.Sleep, could cause a blocking piece that could prevent the service from shutting down. If the interval is that wide spread, and regular, you might just schedule it as well. But if you are talking about long, non-consistent intervals, then yes a Timer would be better.
Since a service may be asked to stop at any time by the Service Control Manager, your thread should always be ready to respond to these requests, so you should not use Thread.Sleep(). Instead, create a manual-reset event in the main thread and use its WaitOne method with a timeout in your worker thread. WaitOne will return false when the time expires. When your service class's OnStop or OnShutdown methods are called, set the event and that will cause WaitOne to return true and you can then exit your worker thread.
Using Thread.Sleep() in a Windows Service
[ "", "c#", "multithreading", "windows-services", "sleep", "" ]
My limited understanding of [ThreadLocal](http://java.sun.com/javase/6/docs/api/java/lang/ThreadLocal.html) is that it has [resource leak issues](http://www.google.com/search?q=threadlocal+leak). I gather this problem can be remedied through proper use of [WeakReferences](http://java.sun.com/javase/6/docs/api/java/lang/ref/WeakReference.html) with ThreadLocal (although I may have misunderstood this point.) I would simply like a pattern or example for correctly using ThreadLocal with WeakReference, if one exists. For instance, in this code snippet where would the WeakReference be introduced? ``` static class DateTimeFormatter { private static final ThreadLocal<SimpleDateFormat> DATE_PARSER_THREAD_LOCAL = new ThreadLocal<SimpleDateFormat>() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy/MM/dd HH:mmz"); } }; public String format(final Date date) { return DATE_PARSER_THREAD_LOCAL.get().format(date); } public Date parse(final String date) throws ParseException { return DATE_PARSER_THREAD_LOCAL.get().parse(date); } } ```
`ThreadLocal` uses a `WeakReference` internally. If the `ThreadLocal` is not strongly referenced, it will be garbage-collected, even though various threads have values stored via that `ThreadLocal`. Additionally, `ThreadLocal` values are actually stored in the `Thread`; if a thread dies, all of the values associated with that thread through a `ThreadLocal` are collected. If you have a `ThreadLocal` as a final class member, that's a strong reference, and it cannot be collected until the class is unloaded. But this is how any class member works, and isn't considered a memory leak. --- *Update:* The cited problem only comes into play when the value stored in a `ThreadLocal` strongly references that `ThreadLocal`—sort of a circular reference. In this case, the value (a `SimpleDateFormat`), has no backwards reference to the `ThreadLocal`. There's no memory leak in this code.
I'm guessing you're jumping through these hoops since SimpleDateFormat is *not thread-safe*. Whilst I'm aware I'm not solving your problem above, can I suggest you look at [Joda](http://joda-time.sourceforge.net/) for your date/time work ? Joda has a thread-safe date/time formatting mechanism. You won't be wasting your time learning the Joda API either, as it's the foundation for the new standard date/time API proposal.
ThreadLocal Resource Leak and WeakReference
[ "", "java", "thread-local", "weak-references", "" ]
What's the best way to determine the first key in a possibly associative array? My first thought it to just foreach the array and then immediately breaking it, like this: ``` foreach ($an_array as $key => $val) break; ``` Thus having $key contain the first key, but this seems inefficient. Does anyone have a better solution?
## 2019 Update Starting from **PHP 7.3**, there is a new built in function called `array_key_first()` which will retrieve the first key from the given array without resetting the internal pointer. Check out the [documentation](http://php.net/manual/en/function.array-key-first.php) for more info. --- You can use [`reset`](http://php.net/reset) and [`key`](http://php.net/key): ``` reset($array); $first_key = key($array); ``` It's essentially the same as your initial code, but with a little less overhead, and it's more obvious what is happening. Just remember to call `reset`, or you may get any of the keys in the array. You can also use [`end`](http://php.net/end) instead of `reset` to get the last key. If you wanted the key to get the first value, `reset` actually returns it: ``` $first_value = reset($array); ``` There is one special case to watch out for though (so check the length of the array first): ``` $arr1 = array(false); $arr2 = array(); var_dump(reset($arr1) === reset($arr2)); // bool(true) ```
`array_keys` returns an array of keys. Take the first entry. Alternatively, you could call `reset` on the array, and subsequently `key`. The latter approach is probably slightly faster (Thoug I didn't test it), but it has the side effect of resetting the internal pointer.
Get first key in a (possibly) associative array?
[ "", "php", "arrays", "" ]
I'm looking for a standalone Java library which allows me to parse LDAP style filter expressions Is such thing available, or is it advisable to use ANTLR instead and build it by one self? As background: the filter itself is submitted through a network, and I want to create say, the appropriate hibernate Criteria. **I'm not doing anything with LDAP!** Any other ideas for a technology independent solution to transfer and transform user defined queries are also appreciated.
You can use the apache directory server's shared LDAP library. It is available in maven at ``` <dependency> <groupId>org.apache.directory.shared</groupId> <artifactId>shared-ldap</artifactId> <version>0.9.15</version> </dependency> ``` And you can use it like: ``` final ExprNode filter = FilterParser.parse(filterString); ```
You could also look at using [Apache directory server](http://directory.apache.org/) either for using some of its classes like lavinio's suggestion for OpenLDAP or to embed it as part of your application.
Is there a standalone Java library which provides LDAP style parsing?
[ "", "java", "parsing", "filter", "ldap", "" ]
I am having trouble casting an object to a generic IList. I have a group of in statements to try to work around this, but there has to be a better way to do this. This is my current method: ``` string values; if (colFilter.Value is IList<int>) { values = BuildClause((IList<int>)colFilter.Value, prefix); } else if (colFilter.Value is IList<string>) { values = BuildClause((IList<string>)colFilter.Value, prefix); } else if (colFilter.Value is IList<DateTime>) { values = BuildClause((IList<DateTime>)colFilter.Value, prefix); } else if (...) //etc. ``` What I want to do is this: ``` values = BuildClause((IList<colFilter.ColumnType>)colFilter.Value, prefix); ``` or ``` values = BuildClause((IList<typeof(colFilter.ColumnType)>)colFilter.Value, prefix); ``` or ``` values = BuildClause((IList<colFilter.ColumnType.GetType()>)colFilter.Value, prefix); ``` Each of these produces this compiler error: The type or namespace name 'colFilter' could not be found (are you missing a using directive or an assembly reference?) In my example, colFilter.ColumnType is int, string, datetime, etc. I am not sure why this does not work. Any ideas? **EDIT: This is C#2.0** **EDIT #2** Here is the BuildClause method (I have overloads for each type): ``` private static string BuildClause(IList<int> inClause, string strPrefix) { return BuildClause(inClause, strPrefix, false); } private static string BuildClause(IList<String> inClause, string strPrefix) { return BuildClause(inClause, strPrefix, true); } private static string BuildClause(IList<DateTime> inClause, string strPrefix) { return BuildClause(inClause, strPrefix, true); } //.. etc for all types private static string BuildClause<T>(IList<T> inClause, string strPrefix, bool addSingleQuotes) { StringBuilder sb = new StringBuilder(); //Check to make sure inclause has objects if (inClause.Count > 0) { sb.Append(strPrefix); sb.Append(" IN("); for (int i = 0; i < inClause.Count; i++) { if (addSingleQuotes) { sb.AppendFormat("'{0}'", inClause[i].ToString().Replace("'", "''")); } else { sb.Append(inClause[i].ToString()); } if (i != inClause.Count - 1) { sb.Append(","); } } sb.Append(") "); } else { throw new Exception("Item count for In() Clause must be greater than 0."); } return sb.ToString(); } ```
There's no way to relate method overloading and generics: although they look similar, they are very different. Specifically, overloading lets you do **different things** based on the type of arguments used; while generics allows you to do **the exact same thing** regardless of the type used. If your BuildClause method is overloaded and every overload is doing something different (not just different by the type used, but really different logic, in this case - choosing whether or not to add quotes) then somewhere, ultimately, you're gonna have to say something like "if type is this do this, if type is that do that" (I call that "switch-on-type"). Another approach is to avoid that "switch-on-type" logic and replace it with polymorphism. Suppose you had a `StringColFilter : ColFilter<string>` and a `IntColFilter : ColFilter<int>`, then each of them could override a virtual method from `ColFilter<T>` and provide its own BuildClause implementation (or just some piece of data that would help BuildClause process it). But then you'd need to explicitly create the correct subtype of ColFilter, which just moves the "switch-on-type" logic to another place in your application. If you're lucky, it'll move that logic to a place in your application where you have the knowledge of which type you're dealing with, and then you could explicitly create different ColFilters at different places in your application and process them generically later on. Consider something like this: ``` abstract class ColFilter<T> { abstract bool AddSingleQuotes { get; } List<T> Values { get; } } class IntColFilter<T> { override bool AddSingleQuotes { get { return false; } } } class StringColFilter<T> { override bool AddSingleQuotes { get { return true; } } } class SomeOtherClass { public static string BuildClause<T>(string prefix, ColFilter<T> filter) { return BuildClause(prefix, filter.Values, filter.AddSingleQuotes); } public static string BuildClause<T>(string prefix, IList<T> values, bool addSingleQuotes) { // use your existing implementation, since here we don't care about types anymore -- // all we do is call ToString() on them. // in fact, we don't need this method to be generic at all! } } ``` Of course this also gets you to the problem of whether ColFilter should know about quotes or not, but that's a design issue and deserves another question :) I also stand by the other posters in saying that if you're trying to build something that creates SQL statements by joining strings together, you should probably stop doing it and move over to parameterized queries which are easier and, more importantly, safer.
What does the function BuildClause() look like. It seems to me that you can create BuildClause() as an **extension** method on IList, and you can append the values together. I assume that you just want to call .ToString() method on different types.
C# Generics and Casting Issue
[ "", "c#", "generics", "casting", "" ]
I have a lot of C# code that uses public fields, and I would like to convert them to properties. I have Resharper, and it will do them one by one, but this will take forever. Does anyone know of an automated refactoring tool that can help with this?
Resharper does it very quickly, using Alt+PageDown / ALt+Enter (with the default key bindings). If you are at the first field, Alt+PageDown will jump to the next one (since it'll include wrapping public fields as a suggested refactoring), and Alt+Enter will prompt you to wrap it in a property. Since you most likely want to avoid a full blanket wrapping of all properties, this is probably the quickest approach. It's quite fast to do this to a class, since it jumps exactly where you need to go...
# Refactor fields to properties (no extensions needed): [![Refactor C# fields to properties](https://i.stack.imgur.com/Bhdd4.gif)](https://i.stack.imgur.com/Bhdd4.gif) **Step 1: Refactor all fields to be encapsulated by properties** **Step 2: Refactor all properties into auto-implemented properties**
Tools for refactoring C# public fields into properties
[ "", "c#", ".net", "refactoring", "automated-refactoring", "public-fields", "" ]
Is there an alternative method or a trick to the hover method which can trigger a function when the cursor moves from one div to another as the user scrolls the page. I have **sort of** got it working using some javascript (jQuery) on the hover event of the current post div. However, I've noticed the hover event only triggers when the mouse is actually moved. If the page is scrolled using the keyboard (page) up/down it does not trigger. (I can note that soup.io for instance has found a way to get this working, but I can't find how they do it)
Unfortunately, it's quite complicated; you can no longer rely on the **`onMouseOver`** event - the only event that triggers when a page is scrolled is **`onScroll`**. The steps involved: 1. Go through elements, storing each of their widths, heights and offsets (distance from left/top of screen) in an array. 2. When the onScroll event is triggered check the last known position of the cursor against all chosen elements (go through the array) - if the cursor resides over one of the elements then call the handler. Quick (unreliable) prototype: <http://pastie.org/507589>
Do you have a sample? I'm guessing that the layout of the elements on the page are blocking the *mouseover* event. My simple example below works as you described it should. With the cursor at the top of the page and using keyboard navigation, the *mouseover* events are fired. ``` <html> <body> <script> function log(text) { document.getElementById('logger').value += text + "\n"; } </script> <div id="div1" style="background: yellow; height: 100px;margin-top: 100px" onmouseover="log('mouseover div1');"> div1 </div> <textarea id="logger" cols="60" rows="12" style="float:right;"></textarea> <div id="div2" style="background: red; height: 1000px" onmouseover="log('mouseover div2');"> div2 </div> </body> </html> ```
Anyone know a mousehover trick/alternative which triggers when scrolling with keyboard
[ "", "javascript", "mouse", "hover", "" ]
i read the answer of the question [Do event handlers stop garbage collection from occuring?](https://stackoverflow.com/questions/298261/do-event-handlers-stop-garbage-collection-from-occuring), but what happens when the publisher is the target ? To be more specific, i am using MVVM design for a WPF app. Model-View classes raise a NotifyPropertyChanged on every change. In some classes, i need to call a method when something is modified. I would like to do this: ``` this.PropertyChanged += this.MyHandler; ``` Will this instances be destroyed by the GC ?
The GC looks and sees if any references to the object are currently rooted in the application. It is smart enough to handle circular references like the one above. In addition, it is smart enough to handle the case where you have two objects, A, and B, and: ``` A.Event += B.Handler; B.Event += A.Handler; ``` If A and B both go out of scope, the GC is smart enough to find and clean both of these objects, even though they subscribe to each other. However, if a separate object (in use) refers to either, it will prevent both from being collected. This is one of the main advantages to a true GC solution, when compared to reference counting solutions. Reference counting will fail to collect this, but the .NET gc will handle it perfectly.
Yes the GC will clean the object up since there is nothing external to the object referencing it. The GC takes all the references held at root level (static fields, references on each threads stack etc.) and leaps from these to objects that these may reference and then to objects the those objects may reference and so on. As it goes it marks each object as "not to be collected". Once it has munched through them anything not yet marked as "not to be collected" is up for collection. When you follow that through there is no way for the GC to get to your object from the root and hence it will be collected.
Do a self handled event prevent the instance from being garbage-Collected?
[ "", "c#", ".net", "events", "mvvm", "garbage-collection", "" ]
This is a two-pronged question: Scenario: I have a script to query MSDB and get me details of job schedules. Obviously, the tables differ from SQL 2000 to SQL 2005. Hence, I want to check the version running on the box and query accordingly. Now the questions: Question 1: This is what I am doing. ``` IF LEFT(CAST(SERVERPROPERTY('ProductVersion') As Varchar),1)='8' BEGIN PRINT 'SQL 2000'--Actual Code Goes Here END IF LEFT(CAST(SERVERPROPERTY('ProductVersion') As Varchar),1)='9' BEGIN PRINT 'SQL 2005'--Actual Code Goes Here END ``` Is there a better way of doing this? Question 2: Though the above script runs fine on both 2000 and 2005 boxes, when I replace the "Print.." statements with my actual code, it runs fine on a 2000 box, but when executed on a 2005 box,tries to run the code block meant for 2000 and returns errors. Here is the actual code: ``` USE [msdb] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO --Check SQL Server Version IF LEFT(CAST(SERVERPROPERTY('ProductVersion') As Varchar),1)='9' BEGIN SELECT @@SERVERNAME ,sysjobs.name ,dbo.udf_schedule_description(dbo.sysschedules.freq_type, dbo.sysschedules.freq_interval, dbo.sysschedules.freq_subday_type, dbo.sysschedules.freq_subday_interval, dbo.sysschedules.freq_relative_interval, dbo.sysschedules.freq_recurrence_factor, dbo.sysschedules.active_start_date, dbo.sysschedules.active_end_date, dbo.sysschedules.active_start_time, dbo.sysschedules.active_end_time) AS [Schedule Description] , CONVERT(CHAR(8), CASE WHEN LEN(msdb.dbo.sysschedules.Active_Start_Time) = 3 THEN CAST('00:0' + LEFT(msdb.dbo.sysschedules.Active_Start_Time, 1) + ':' + SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)), 2, 2) AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysschedules.Active_Start_Time) = 4 THEN CAST('00:' + SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)), 1, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)), 3, 2) AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysschedules.Active_Start_Time) = 5 THEN CAST('0' + LEFT(msdb.dbo.sysschedules.Active_Start_Time, 1) + ':' + SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)), 2, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)), 4, 2) AS VARCHAR(8)) WHEN msdb.dbo.sysschedules.Active_Start_Time = 0 THEN '00:00:00' ELSE CAST(LEFT(msdb.dbo.sysschedules.Active_Start_Time, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)), 3, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)), 5, 2) AS VARCHAR(8)) END, 108) AS Start_Time, CONVERT(CHAR(8), CASE WHEN LEN(msdb.dbo.sysschedules.active_end_time) = 3 THEN CAST('00:0' + LEFT(msdb.dbo.sysschedules.active_end_time, 1) + ':' + SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)), 2, 2) AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysschedules.active_end_time) = 4 THEN CAST('00:' + SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)), 1, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)), 3, 2) AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysschedules.active_end_time) = 5 THEN CAST('0' + LEFT(msdb.dbo.sysschedules.active_end_time, 1) + ':' + SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)), 2, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)), 4, 2) AS VARCHAR(8)) WHEN msdb.dbo.sysschedules.active_end_time = 0 THEN '00:00:00' ELSE CAST(LEFT(msdb.dbo.sysschedules.active_end_time, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)), 3, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)), 5, 2) AS VARCHAR(8)) END, 108) AS End_Time ,CAST(CASE WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 1 THEN CAST('00:00:0' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 1)AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 2 THEN CAST('00:00:' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 2)AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 3 THEN CAST('00:0' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 1) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 2, 2) AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 4 THEN CAST('00:' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 1, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 3, 2) AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 5 THEN CAST('0' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 1) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 2, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 4, 2) AS VARCHAR(8)) WHEN msdb.dbo.sysjobservers.last_run_duration = 0 THEN '00:00:00' ELSE CAST(LEFT(msdb.dbo.sysjobservers.last_run_duration, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 3, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 5, 2) AS VARCHAR(8)) END AS VARCHAR(8)) AS LastRunDuration FROM msdb.dbo.sysjobs INNER JOIN msdb.dbo.syscategories ON msdb.dbo.sysjobs.category_id = msdb.dbo.syscategories.category_id LEFT OUTER JOIN msdb.dbo.sysoperators ON msdb.dbo.sysjobs.notify_page_operator_id = msdb.dbo.sysoperators.id LEFT OUTER JOIN msdb.dbo.sysjobservers ON msdb.dbo.sysjobs.job_id = msdb.dbo.sysjobservers.job_id LEFT OUTER JOIN msdb.dbo.sysjobschedules ON msdb.dbo.sysjobschedules.job_id = msdb.dbo.sysjobs.job_id LEFT OUTER JOIN msdb.dbo.sysschedules ON msdb.dbo.sysjobschedules.schedule_id = msdb.dbo.sysschedules.schedule_id WHERE sysjobs.enabled = 1 AND msdb.dbo.sysschedules.Active_Start_Time IS NOT NULL ORDER BY Start_time,sysjobs.name END IF LEFT(CAST(SERVERPROPERTY('ProductVersion') As Varchar),1)='8' BEGIN SELECT @@SERVERNAME ,sysjobs.name ,dbo.udf_schedule_description(sysjobschedules.freq_type, sysjobschedules.freq_interval, sysjobschedules.freq_subday_type, sysjobschedules.freq_subday_interval, sysjobschedules.freq_relative_interval, sysjobschedules.freq_recurrence_factor, sysjobschedules.active_start_date, sysjobschedules.active_end_date, sysjobschedules.active_start_time, sysjobschedules.active_end_time) AS [Schedule Description] , CONVERT(CHAR(8), CASE WHEN LEN(msdb.dbo.sysjobschedules.Active_Start_Time) = 3 THEN CAST('00:0' + LEFT(msdb.dbo.sysjobschedules.Active_Start_Time, 1) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)), 2, 2) AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysjobschedules.Active_Start_Time) = 4 THEN CAST('00:' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)), 1, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)), 3, 2) AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysjobschedules.Active_Start_Time) = 5 THEN CAST('0' + LEFT(msdb.dbo.sysjobschedules.Active_Start_Time, 1) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)), 2, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)), 4, 2) AS VARCHAR(8)) WHEN msdb.dbo.sysjobschedules.Active_Start_Time = 0 THEN '00:00:00' ELSE CAST(LEFT(msdb.dbo.sysjobschedules.Active_Start_Time, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)), 3, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)), 5, 2) AS VARCHAR(8)) END, 108) AS Start_Time, CONVERT(CHAR(8), CASE WHEN LEN(msdb.dbo.sysjobschedules.active_end_time) = 3 THEN CAST('00:0' + LEFT(msdb.dbo.sysjobschedules.active_end_time, 1) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)), 2, 2) AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysjobschedules.active_end_time) = 4 THEN CAST('00:' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)), 1, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)), 3, 2) AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysjobschedules.active_end_time) = 5 THEN CAST('0' + LEFT(msdb.dbo.sysjobschedules.active_end_time, 1) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)), 2, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)), 4, 2) AS VARCHAR(8)) WHEN msdb.dbo.sysjobschedules.active_end_time = 0 THEN '00:00:00' ELSE CAST(LEFT(msdb.dbo.sysjobschedules.active_end_time, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)), 3, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)), 5, 2) AS VARCHAR(8)) END, 108) AS End_Time ,CAST(CASE WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 1 THEN CAST('00:00:0' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 1)AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 2 THEN CAST('00:00:' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 2)AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 3 THEN CAST('00:0' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 1) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 2, 2) AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 4 THEN CAST('00:' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 1, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 3, 2) AS VARCHAR(8)) WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 5 THEN CAST('0' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 1) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 2, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 4, 2) AS VARCHAR(8)) WHEN msdb.dbo.sysjobservers.last_run_duration = 0 THEN '00:00:00' ELSE CAST(LEFT(msdb.dbo.sysjobservers.last_run_duration, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 3, 2) + ':' + SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)), 5, 2) AS VARCHAR(8)) END AS VARCHAR(8)) AS LastRunDuration FROM sysjobs LEFT OUTER JOIN msdb.dbo.sysjobservers ON msdb.dbo.sysjobs.job_id = msdb.dbo.sysjobservers.job_id INNER JOIN sysjobschedules ON sysjobs.job_id = sysjobschedules.job_id WHERE sysjobs.enabled = 1 ORDER BY Start_time,sysjobs.name END ``` This script requires a udf in MSDB. Here is the code for the function: ``` USE [msdb] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[udf_schedule_description] (@freq_type INT , @freq_interval INT , @freq_subday_type INT , @freq_subday_interval INT , @freq_relative_interval INT , @freq_recurrence_factor INT , @active_start_date INT , @active_end_date INT, @active_start_time INT , @active_end_time INT ) RETURNS NVARCHAR(255) AS BEGIN DECLARE @schedule_description NVARCHAR(255) DECLARE @loop INT DECLARE @idle_cpu_percent INT DECLARE @idle_cpu_duration INT IF (@freq_type = 0x1) -- OneTime BEGIN SELECT @schedule_description = N'Once on ' + CONVERT(NVARCHAR, @active_start_date) + N' at ' + CONVERT(NVARCHAR, cast((@active_start_time / 10000) as varchar(10)) + ':' + right('00' + cast((@active_start_time % 10000) / 100 as varchar(10)),2)) RETURN @schedule_description END IF (@freq_type = 0x4) -- Daily BEGIN SELECT @schedule_description = N'Every day ' END IF (@freq_type = 0x8) -- Weekly BEGIN SELECT @schedule_description = N'Every ' + CONVERT(NVARCHAR, @freq_recurrence_factor) + N' week(s) on ' SELECT @loop = 1 WHILE (@loop <= 7) BEGIN IF (@freq_interval & POWER(2, @loop - 1) = POWER(2, @loop - 1)) SELECT @schedule_description = @schedule_description + DATENAME(dw, N'1996120' + CONVERT(NVARCHAR, @loop)) + N', ' SELECT @loop = @loop + 1 END IF (RIGHT(@schedule_description, 2) = N', ') SELECT @schedule_description = SUBSTRING(@schedule_description, 1, (DATALENGTH(@schedule_description) / 2) - 2) + N' ' END IF (@freq_type = 0x10) -- Monthly BEGIN SELECT @schedule_description = N'Every ' + CONVERT(NVARCHAR, @freq_recurrence_factor) + N' months(s) on day ' + CONVERT(NVARCHAR, @freq_interval) + N' of that month ' END IF (@freq_type = 0x20) -- Monthly Relative BEGIN SELECT @schedule_description = N'Every ' + CONVERT(NVARCHAR, @freq_recurrence_factor) + N' months(s) on the ' SELECT @schedule_description = @schedule_description + CASE @freq_relative_interval WHEN 0x01 THEN N'first ' WHEN 0x02 THEN N'second ' WHEN 0x04 THEN N'third ' WHEN 0x08 THEN N'fourth ' WHEN 0x10 THEN N'last ' END + CASE WHEN (@freq_interval > 00) AND (@freq_interval < 08) THEN DATENAME(dw, N'1996120' + CONVERT(NVARCHAR, @freq_interval)) WHEN (@freq_interval = 08) THEN N'day' WHEN (@freq_interval = 09) THEN N'week day' WHEN (@freq_interval = 10) THEN N'weekend day' END + N' of that month ' END IF (@freq_type = 0x40) -- AutoStart BEGIN SELECT @schedule_description = FORMATMESSAGE(14579) RETURN @schedule_description END IF (@freq_type = 0x80) -- OnIdle BEGIN EXECUTE master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'IdleCPUPercent', @idle_cpu_percent OUTPUT, N'no_output' EXECUTE master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'IdleCPUDuration', @idle_cpu_duration OUTPUT, N'no_output' SELECT @schedule_description = FORMATMESSAGE(14578, ISNULL(@idle_cpu_percent, 10), ISNULL(@idle_cpu_duration, 600)) RETURN @schedule_description END -- Subday stuff SELECT @schedule_description = @schedule_description + CASE @freq_subday_type WHEN 0x1 THEN N'at ' + CONVERT(NVARCHAR, cast( CASE WHEN LEN(cast((@active_start_time / 10000)as varchar(10)))=1 THEN '0'+cast((@active_start_time / 10000) as varchar(10)) ELSE cast((@active_start_time / 10000) as varchar(10)) END as varchar(10)) + ':' + right('00' + cast((@active_start_time % 10000) / 100 as varchar(10)),2)) WHEN 0x2 THEN N'every ' + CONVERT(NVARCHAR, @freq_subday_interval) + N' second(s)' WHEN 0x4 THEN N'every ' + CONVERT(NVARCHAR, @freq_subday_interval) + N' minute(s)' WHEN 0x8 THEN N'every ' + CONVERT(NVARCHAR, @freq_subday_interval) + N' hour(s)' END IF (@freq_subday_type IN (0x2, 0x4, 0x8)) SELECT @schedule_description = @schedule_description + N' between ' + CONVERT(NVARCHAR, cast( CASE WHEN LEN(cast((@active_start_time / 10000)as varchar(10)))=1 THEN '0'+cast((@active_start_time / 10000) as varchar(10)) ELSE cast((@active_start_time / 10000) as varchar(10)) END as varchar(10)) + ':' + right('00' + cast((@active_start_time % 10000) / 100 as varchar(10)),2) ) + N' and ' + CONVERT(NVARCHAR, cast( CASE WHEN LEN(cast((@active_end_time / 10000)as varchar(10)))=1 THEN '0'+cast((@active_end_time / 10000) as varchar(10)) ELSE cast((@active_end_time / 10000) as varchar(10)) END as varchar(10)) + ':' + right('00' + cast((@active_end_time % 10000) / 100 as varchar(10)),2) ) RETURN @schedule_description END ``` I have got this far and have spent too much time trying to find out what the problem is. Please help.
the errors are compile time (I ran on 2005): ``` Msg 207, Level 16, State 1, Line 106 Invalid column name 'freq_type'. Msg 207, Level 16, State 1, Line 106 Invalid column name 'freq_interval'. Msg 207, Level 16, State 1, Line 107 Invalid column name 'freq_subday_type'. Msg 207, Level 16, State 1, Line 107 Invalid column name 'freq_subday_interval'. Msg 207, Level 16, State 1, Line 107 Invalid column name 'freq_relative_interval'. Msg 207, Level 16, State 1, Line 108 Invalid column name 'freq_recurrence_factor'. Msg 207, Level 16, State 1, Line 108 Invalid column name 'active_start_date'. Msg 207, Level 16, State 1, Line 108 Invalid column name 'active_end_date'. Msg 207, Level 16, State 1, Line 109 Invalid column name 'active_start_time'. Msg 207, Level 16, State 1, Line 109 Invalid column name 'active_end_time'. Msg 207, Level 16, State 1, Line 110 ``` I added PRINTs and they never appear. your code has problems because the column names are not compatible with the database you are running. SQL Server 2005 does not have a "sysjobschedules.freq\_type" column. Make a stored procedure XYZ, put the 2000 version in the 2000 database, put the same XYZ procedure on the 2005 machine and put the 2005 version in it. No IF necessary... **EDIT** run this code: ``` PRINT 'Works' ``` now run this code ``` PRINT 'will not see this' error ``` try this: ``` PRINT 'will not see this' SELECT xyz from sysjobschedules ``` now try running this, but only highlight the PRINT line: ``` PRINT 'you can see this' --only select this line of code and run it SELECT xyz from sysjobschedules ``` see how compile errors prevent anything from running **EDIT** you might try something like this... ``` DECLARE @Query varchar(max) IF LEFT(CAST(SERVERPROPERTY('ProductVersion') As Varchar),1)='8' BEGIN SET @Query=...... END IF LEFT(CAST(SERVERPROPERTY('ProductVersion') As Varchar),1)='9' BEGIN SET @Query=...... END EXEC (@Query) ```
The original question is only specific to 2000,2005 but here's some code that should work on 2000, 2005, 2008 and onwards ``` DECLARE @ver NVARCHAR(128) DECLARE @majorVersion int SET @ver = CAST(SERVERPROPERTY('productversion') AS NVARCHAR) SET @ver = SUBSTRING(@ver,1,CHARINDEX('.',@ver)-1) SET @majorVersion = CAST(@ver AS INT) IF @majorVersion < 11 PRINT 'Plesae Upgrade' ELSE PRINT @majorVersion ```
Best way to determine Server Product version and execute SQL accordingly?
[ "", "sql", "sql-server", "t-sql", "" ]
I have been scouring the net but I can't seem to find any examples of consuming data from [WikiNews](http://en.wikinews.org/wiki/Main_Page). They have an RSS feed with links to individual stories as HTML, but I would like to get the data in a structured format such as XML etc. By structured format I mean an XML file for each story that has a defined XML schema (XSD) file. See: [<http://www.w3schools.com/schema/schema_intro.asp][2]> Has anyone written a program that consumes stories from WikiNews? Do they have a documented API? I would like to use C# to collect selected stories and store them in SQL Server 2008. [2]: By "structured format" I mean something like an XML schema (XSD) file. See: <http://www.w3schools.com/schema/schema_intro.asp>
The software they use [has an API](http://www.mediawiki.org/wiki/API) but I'm not sure if WikiNews supports it.
Their feed: <http://feeds.feedburner.com/WikinewsLatestNews> If you put that in your browser and read the source, you'll see that it is XML. The XML contains the title, description, a link, etc. Only the description is in HTML. Here is the beginning of the response: ``` <rss xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"> <channel> <title>Wikinews</title> <description>Wikinews RSS feed</description> <language>en</language> <link>http://en.wikinews.org</link> <copyright>Creative Commons Attribution 2.5 (unless otherwise noted)</copyright> <generator>Wikinews Fetch</generator> <ttl>180</ttl> <docs>http://none</docs> <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/WikinewsLatestNews" /><feedburner:info uri="wikinewslatestnews" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><creativeCommons:license>http://creativecommons.org/licenses/by/2.5/</creativeCommons:license><feedburner:browserFriendly>This is an XML content feed. It is intended to be viewed in a newsreader or syndicated to another site.</feedburner:browserFriendly><item> <title>Lufthansa pilots begin strike</title> <link>http://feedproxy.google.com/~r/WikinewsLatestNews/~3/1K2xloPGlmI/Lufthansa_pilots_begin_strike</link> <description>&lt;p&gt;&lt;a href="http://en.wikinews.org/w/index.php?title=File:LocationGermany.png&amp;filetimestamp=20060604120306" class="image" title="A map showing the location of Germany"&gt;&lt;img alt="A map showing the location of Germany" src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/de/LocationGermany.png/196px-LocationGermany.png" width="196" height="90" /&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;b class="published"&gt;&lt;span id="publishDate" class="value-title" title="2010-02-22"&gt;&lt;/span&gt;Monday, February 22, 2010&lt;/b&gt;&lt;/p&gt; &lt;p&gt;The pilot's union of &lt;a href="http://en.wikinews.org/wiki/Germany" title="Germany" class="mw-redirect"&gt;German&lt;/a&gt; airline &lt;a href="http://en.wikipedia.org/wiki/Lufthansa" class="extiw" title="w:Lufthansa"&gt;Lufthansa&lt;/a&gt; have begun a four-day strike over pay and job security. Operations at subsidiary airlines &lt;a href="http://en.wikipedia.org/wiki/Lufthansa_Cargo" class="extiw" title="w:Lufthansa Cargo"&gt;Lufthansa Cargo&lt;/a&gt; and &lt;a href="http://en.wikipedia.org/wiki/Germanwings" class="extiw" title="w:Germanwings"&gt;Germanwings&lt;/a&gt; are also affected by the strike.&lt;/p&gt; &lt;em&gt;&lt;a href='http://en.wikinews.org/wiki/Lufthansa_pilots_begin_strike'&gt;More...&lt;/a&gt;&lt;/em&gt;&lt;div class="feedflare"&gt; &lt;a href="http://feeds.feedburner.com/~ff/WikinewsLatestNews?a=1K2xloPGlmI:9SJI0YV04-M:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/WikinewsLatestNews?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/WikinewsLatestNews?a=1K2xloPGlmI:9SJI0YV04-M:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/WikinewsLatestNews?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/WikinewsLatestNews?a=1K2xloPGlmI:9SJI0YV04-M:YwkR-u9nhCs"&gt;&lt;img src="http://feeds.feedburner.com/~ff/WikinewsLatestNews?d=YwkR-u9nhCs" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;/div&gt;</description> <guid isPermaLink="false">http://en.wikinews.org/wiki/Lufthansa_pilots_begin_strike</guid> <feedburner:origLink>http://en.wikinews.org/wiki/Lufthansa_pilots_begin_strike</feedburner:origLink></item> ```
Consuming data from WikiNews
[ "", "c#", "" ]
When creating an FixedThreadPool Executor object in Java you need to pass an argument describing the number of threads that the Executor can execute concurrently. I'm building a service class that's responsibility is to process a large collections of phone numbers. For each phone number I need to execute web service (that's my bottleneck) and then save response in a hashmap. To make this bottleneck less harmful to the performance of my service I've decided to create Worker class which fetches unprocessed elements and processes them. Worker class implements Runnable interface and I run Workers using Executor. The number of Workers that can be run in the same time depends on the size of Executor FixedThreadPool. What is the safe size for a ThreadPool? What can happen when I create FixedTheradPool with some big number as an argument?
If each worker thread needs to make a web service call, then the number of threads in your pool should be influenced strongly by how many simultaneous requests your web service can handle. Any more threads than that will do nothing more than overwhelm the web service.
Something that could be considered is looking at ``` Runtime.getRuntime().availableProcessors() ``` which gives some direction on how many threads that would make sense for the system.
Reasonable number of threads for thread pool running web service requests
[ "", "java", "web-services", "concurrency", "threadpool", "" ]
I'm trying to keep the database tables for a project I'm working on nice and normalized, but I've run into a problem. I'm trying to figure out how I can insert a row into a table and then find out what the value of the auto\_incremented `id` column was set to so that I can insert additional data into another table. I know there are functions such as `mysql_insert_id` which "get the ID generated from the previous INSERT operation". However, if I'm not mistaken `mysql_insert_id` just returns the ID of the very last operation. So, if the site has enough traffic this wouldn't necessarily return the ID of the query you want since another query could have been run between when you inserted the row and look for the ID. Is this understanding of `mysql_insert_id` correct? Any suggestions on how to do this are greatly appreciated. Thanks.
`LAST_INSERT_ID()` has session scope. It will return the identity value inserted in the current session. If you don't insert any rows between `INSERT` and `LAST_INSERT_ID`, then it will work all right. Note though that for multiple value inserts, it will return the identity of the first row inserted, not the last one: ``` INSERT INTO mytable (identity_column) VALUES (NULL) SELECT LAST_INSERT_ID() -- 1 INSERT INTO mytable (identity_column) VALUES (NULL), (NULL) /* This inserts rows 2 and 3 */ SELECT LAST_INSERT_ID() -- 2 /* But this returns 2, not 3 */ ```
**You could:** A. Assume that won't be a problem and use mysql\_insert\_id **or** B. Include a timestamp in the row and retrieve the last inserted ID before inserting into another table.
Retrieving the index of an inserted row
[ "", "php", "mysql", "" ]
This is a continuation of the question ["Java rounded Swing JButton"](https://stackoverflow.com/questions/778222/make-a-button-round). I have searched for an extension of javax.swing.JButton which will inherit all runtime behavior and just override drawing of the corners. Using the code given by [noah.w](http://forums.sun.com/profile.jspa?userID=81148) on [sun forums page](http://forums.sun.com/thread.jspa?threadID=284897&tstart=28696) the result looks like this: [![alt text](https://i.stack.imgur.com/sZX30.png)](https://i.stack.imgur.com/sZX30.png) I'd like to be able to have the same gradient in the background, on mouse over change etc. Does anybody know how to do that? Code which creates the Java Swing window from the picture is: ``` public class XrButton extends JButton implements MouseListener { private static final long serialVersionUID = 9032198251140247116L; String text; boolean mouseIn = false; public XrButton(String s) { super(s); text = s; setBorderPainted(false); addMouseListener(this); setContentAreaFilled(false); } @Override public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; if (getModel().isPressed()) { g.setColor(g.getColor()); g2.fillRect(3, 3, getWidth() - 6, getHeight() - 6); } super.paintComponent(g); if (mouseIn) g2.setColor(Color.red); else g2.setColor(new Color(128, 0, 128)); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setStroke(new BasicStroke(1.2f)); g2.draw(new RoundRectangle2D.Double(1, 1, (getWidth() - 3), (getHeight() - 3), 12, 8)); g2.setStroke(new BasicStroke(1.5f)); g2.drawLine(4, getHeight() - 3, getWidth() - 4, getHeight() - 3); g2.dispose(); } public static void main(String[] args) { JFrame frame = new JFrame(); frame.getContentPane().setLayout(new FlowLayout()); XrButton xrButton = new XrButton("XrButton"); JButton jButton = new JButton("JButton"); frame.getContentPane().add(xrButton); frame.getContentPane().add(jButton); frame.setSize(150, 150); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { mouseIn = true; } public void mouseExited(MouseEvent e) { mouseIn = false; } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } ```
I think you've got 2 choices here: 1.Implement drawing yourself in a paint method of your component 2.Create new ButtonUI for your look and feel. In this case i would suggest to use Synch LAF In both cases drawing different states is your resposibility
The best implementation I have seen of rounded buttons in Swing are in the Substance look and feel: <https://substance.dev.java.net/> Not all themes have rounded buttons so you may need to change the defaults in the demo. The project is open source so it might be worth poking around in the code for some ideas.
How to create a JButton extension with rounded corners?
[ "", "java", "swing", "rounded-corners", "jbutton", "" ]
I have this piece of code, and it doesn't work as I expect (it's demo code, distilled from a larger program): ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Test</title> <script language="javascript" type="text/javascript"> var test = { variable: true, go: function() { alert(this.variable); } }; function s() { test.go(); setTimeout(test.go, 500); } </script> </head> <body> <form action="#"> <input type="button" value="Go" onclick="s();" /> </form> </body> </html> ``` When I click the Go button, both in IE and FF (the only browsers I care about atm), the first alert box shows "true", the second one "undefined". My questions are why, and how can I avoid it?
**`setTimeout`** will execute the passed function in the context of the window, so 'this' refers to the window. Try this instead: ``` setTimeout(function(){ test.go(); }, 500); ```
change the line ``` setTimeout(test.go, 500); ``` with ``` setTimeout(function(){test.go()}, 500); ``` and your script shoud work fine.
Javascript literal loses its variables when called with setTimeout
[ "", "javascript", "variables", "settimeout", "" ]
I have an ASP.NET (C#) class that is used both on the client and server. Depending on whether the code is being executed on the client or the server, it needs to behave differently. What is the simplest & most efficient way of telling if the code is executing on the client or the server? Thanks!
unless you are running Silverlight 2 or Silverlight 3 There is no way for Asp.Net to run C# code in the client (the users' browser)
It's executing on the server. Unless you are using Silverlight, C# is probably not run on the client.
What's the simplest & most efficient way of telling if your code is executing on the client or the server?
[ "", "c#", "asp.net", "" ]
What is the best way to convert an [internationalized domain name](http://en.wikipedia.org/wiki/Internationalized_domain_name) to its ASCII-form? I want to convert **`Bücher.ch`** into **`xn--bcher-kva.ch`** by using some sort of (free) .net code.
Have a look at the [GNU IDN Library - Libidn](http://www.gnu.org/software/libidn/). The introduction says that C# libraries are available.
``` using System.Globalization; ... IdnMapping idn = new IdnMapping(); MessageBox.Show(idn.GetAscii("www.kraków.pl")); ```
How to convert IDN to ASCII?
[ "", "c#", ".net", "idn", "" ]
If I have two different file paths, how can I determine whether they point to the same file ? This could be the case, if for instance the user has a network drive attached, which points to some network resource. For example drive S: mapped to \servercrm\SomeFolder. Then these paths actually point to the same file: ``` S:\somefile.dat ``` And ``` \\servercrm\SomeFolder\somefile.dat ``` How can I detect this ? I need to code it so that it works in all scenarios where there might be different ways for a path to point to the same file.
I don't know if there is an easy way to do this directly in C# but you could do an unmanaged call to [GetFileInformationByHandle](http://msdn.microsoft.com/en-us/library/aa364952(VS.85).aspx) (pinvoke page [here](http://www.pinvoke.net/default.aspx/kernel32/GetFileInformationByHandle.html)) which will return a [BY\_HANDLE\_FILE\_INFORMATION](http://msdn.microsoft.com/en-us/library/aa363788(VS.85).aspx) structure. This contains three fields which can be combined to uniquely ID a file: > dwVolumeSerialNumber: > The serial number of the volume that contains a file. > > ... > > nFileIndexHigh: > The high-order part of a unique identifier that is associated with a > file. > > nFileIndexLo: > The low-order part of a unique identifier that is associated with a > file. > > The identifier (low and high parts) and the volume serial number uniquely identify a file on a single computer. To determine whether two open handles represent the same file, combine the identifier and the volume serial number for each file and compare them. Note though that this only works if both references are declared from the same machine. --- Edited to add: As per [this question](https://stackoverflow.com/questions/410705/best-way-to-determine-if-two-path-reference-to-same-file-in-c) this may not work for the situation you have since the dwVolumeSerialNumber may be different is the share definitions are different. I'd try it out first though, since I always thought that the volume serial number was drive specific, not path specific. I've never needed to actually prove this though, so I could be (and probably am) wrong.
At the very least you could take and compare the MD5 hashes of the combined file contents, file name, and metadata such as CreationTime, LastAccessTime, and LastWriteTime.
How do I determine whether two file system URI's point to the same resource?
[ "", "c#", ".net", "io", "" ]
Apple really had bad documentation about how the provider connects and communicates to their service (at the time of writing - 2009). I am confused about the protocol. How is this done in C#?
Working code example: ``` int port = 2195; String hostname = "gateway.sandbox.push.apple.com"; //load certificate string certificatePath = @"cert.p12"; string certificatePassword = ""; X509Certificate2 clientCertificate = new X509Certificate2(certificatePath, certificatePassword); X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate); TcpClient client = new TcpClient(hostname, port); SslStream sslStream = new SslStream( client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null ); try { sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, true); } catch (AuthenticationException ex) { client.Close(); return; } // Encode a test message into a byte array. MemoryStream memoryStream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(memoryStream); writer.Write((byte)0); //The command writer.Write((byte)0); //The first byte of the deviceId length (big-endian first byte) writer.Write((byte)32); //The deviceId length (big-endian second byte) String deviceId = "DEVICEIDGOESHERE"; writer.Write(ToByteArray(deviceId.ToUpper())); String payload = "{\"aps\":{\"alert\":\"I like spoons also\",\"badge\":14}}"; writer.Write((byte)0); //First byte of payload length; (big-endian first byte) writer.Write((byte)payload.Length); //payload length (big-endian second byte) byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload); writer.Write(b1); writer.Flush(); byte[] array = memoryStream.ToArray(); sslStream.Write(array); sslStream.Flush(); // Close the client connection. client.Close(); ```
I hope this is relevant (slightly), but I have just successfully created one for Java, so conceptually quite similar to C# (except perhaps the SSL stuff, but that shouldn't be too hard to modify. Below is a sample message payload and crypto setup: ``` int port = 2195; String hostname = "gateway.sandbox.push.apple.com"; char []passwKey = "<keystorePassword>".toCharArray(); KeyStore ts = KeyStore.getInstance("PKCS12"); ts.load(new FileInputStream("/path/to/apn_keystore/cert.p12"), passwKey); KeyManagerFactory tmf = KeyManagerFactory.getInstance("SunX509"); tmf.init(ts,passwKey); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(tmf.getKeyManagers(), null, null); SSLSocketFactory factory =sslContext.getSocketFactory(); SSLSocket socket = (SSLSocket) factory.createSocket(hostname,port); // Create the ServerSocket String[] suites = socket.getSupportedCipherSuites(); socket.setEnabledCipherSuites(suites); //start handshake socket.startHandshake(); // Create streams to securely send and receive data to the server InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); // Read from in and write to out... ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(0); //The command System.out.println("First byte Current size: " + baos.size()); baos.write(0); //The first byte of the deviceId length baos.write(32); //The deviceId length System.out.println("Second byte Current size: " + baos.size()); String deviceId = "<heaxdecimal representation of deviceId"; baos.write(hexStringToByteArray(deviceId.toUpperCase())); System.out.println("Device ID: Current size: " + baos.size()); String payload = "{\"aps\":{\"alert\":\"I like spoons also\",\"badge\":14}}"; System.out.println("Sending payload: " + payload); baos.write(0); //First byte of payload length; baos.write(payload.length()); baos.write(payload.getBytes()); out.write(baos.toByteArray()); out.flush(); System.out.println("Closing socket.."); // Close the socket in.close(); out.close(); ``` } Once again, not C#, but at least closer than the poor ObjC sample that Apple provides.
How to write an Apple Push Notification Provider in C#?
[ "", "c#", "ios", "apple-push-notifications", "" ]
I have this array.prototype on my page and it seems to be sucking up a lot of processing time: ``` Array.prototype.findInArray = function(searchStr) { var returnArray = false; for (i=0; i<this.length; i++) { if (typeof(searchStr) == 'function') { if (searchStr.test(this[i])) { if (!returnArray) { returnArray = [] } returnArray.push(i); } } else { var regexp = new RegExp(".*" + searchStr + ".*"); if (this[i].match(regexp)) { if (!returnArray) { returnArray = [] } returnArray.push(i); } } } return returnArray; } ```
First of all, you know that you don't have to have the ".\*" on either side, right? A regular expression already by default will match anywhere inside the string. Second, if you are just searching for a constant string, and don't need to use any of the advanced stuff that regular expressions offer, then it's definitely faster to use `.indexOf()`. Plus that way you won't have to worry about escaping characters that have special meaning.
Regular expressions can vary wildly. I imagine that a simple, well-crafted regular expression might work as fast or faster than indexOf(). On the other hand, a complex regular expression would need more time since it's doing more work. You also have a browser implementation issue clouding matters. Short of writing a timed loop to measure the time taken for each browser to do each type of detection with your specific needs, you can't really get a solid answer.
What has higher performance used within large loops: .indexOf(str) or .match(regex)?
[ "", "javascript", "regex", "arrays", "match", "indexof", "" ]
We keep getting this error randomly in our web application. > System.Data.SqlClient.SqlException: A > network-related or instance-specific > error occurred while establishing a > connection to SQL Server. The server > was not found or was not accessible. > Verify that the instance name is > correct and that SQL Server is > configured to allow remote > connections. (provider: Named Pipes > Provider, error: 40 - Could not open a > connection to SQL Server) It would make sense if we got the error ever time but to get it intermittently suggest something else is going on. Has anyone experienced this? Any suggestions or theories? Thanks!
It's possible that the server is too busy to respond - are you using SQL Express or Workgroup Edition? Also, how many connections at a time does this server have? Is this error happening on all connections at a certain time, or do some connections get rejected while others succeed at the same time? Also, if you do a "PING -t Servername" and watch it, does every ping come back, or are some lost? This can be an indicator of network interruptions that might also cause this error.
We had this because of too many firewalls: the further away the client (say HK or NY, we're in Switzerland) the more often it happened. London: rarely. Switzerland: never. It was explained to us (via our DB engineering and MS help) that the delays because of routers and firewalls sometimes upset Kerberos and/or related timings. Fix: use the port in the connection string. This avoids the roundtrip to port 1434 to enumerate the instance. We already used FQDN. Example: server.domain.tld\instance,port YNNV of course, but it worked for us
Why would I get this error intermittently? "The server was not found or was not accessible"
[ "", "asp.net", "sql", "sql-server-2005", "ado.net", "" ]
The below stored procedure will not allow me to add it to Modify it. When attempting to modify it I get the following error --> `Msg 213, Level 16, State 1, Procedure spPersonRelationshipAddOpposing, Line 51 Insert Error: Column name or number of supplied values does not match table definition.` Also, Since the DB was set up for Merge Rep (a rowguid column has been added) this stored procedure now no longer works properly. Do I need to change the way the columns are listed? One of the warnings when setting up Merge Rep was this --> `Adding Guid Column MAY Cause INSERT Statements without column lists to Fail` What does that mean? How do I fix this? ``` USE [Connect] GO /****** Object: StoredProcedure [dbo].[spPersonRelationshipAddOpposing] Script Date: 07/15/2009 08:14:35 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[spPersonRelationshipAddOpposing] @ExistingRelationshipID INT AS BEGIN --Declare local variables DECLARE @PersonID INT --PersonID of established relarionship DECLARE @RelatedID INT --RelatedID of established relarionship DECLARE @Relationship VARCHAR(4) --Established relarionship DECLARE @RelatedSex as VARCHAR(1) DECLARE @OpposingRelationship VARCHAR(4) DECLARE @OpposingRelationshipID INT --Fill variables from existing relationship SELECT @PersonID = PersonID, @RelatedID = RelatedID, @Relationship=PersonRelationshipTypeID FROM tblPersonRelationship where PersonRelationshipID = @ExistingRelationshipID --Get gender of relative for finding opposing relationship type SELECT @RelatedSex = (SELECT Gender FROM tblPerson WHERE PersonID = @PersonID) --get opposing relationship types IF (@RelatedSex='M') BEGIN SELECT @OpposingRelationship = (SELECT OpposingMaleRelationship From tblAdminPersonRelationshipType WHERE PersonRelationshipTypeID = @Relationship) END ELSE IF (@RelatedSex='F') BEGIN SELECT @OpposingRelationship = (SELECT OpposingFemaleRelationship From tblAdminPersonRelationshipType WHERE PersonRelationshipTypeID = @Relationship) END --check for existing opposing relationship SELECT @OpposingRelationshipID = (SELECT MAX(PersonRelationshipID) FROM tblPersonRelationship WHERE PersonID = @RelatedID AND RelatedID = @PersonID) --if an opposing relationship was found IF (@OpposingRelationship IS NOT NULL) BEGIN --if there is a relationship, update it IF ISNUMERIC(@OpposingRelationshipID)=1 BEGIN UPDATE tblPersonRelationship SET PersonRelationshipTypeID = @OpposingRelationship, MarriageDate = (SELECT MarriageDate FROM tblPersonRelationship WHERE PersonRelationshipID = @ExistingRelationshipID), ResidesWithPersonFlag = (SELECT ResidesWithPersonFlag FROM tblPersonRelationship WHERE PersonRelationshipID = @ExistingRelationshipID), UpdateDateTime = (SELECT UpdateDateTime FROM tblPersonRelationship WHERE PersonRelationshipID = @ExistingRelationshipID), UpdateProgram = (SELECT UpdateProgram FROM tblPersonRelationship WHERE PersonRelationshipID = @ExistingRelationshipID), UpdateUserID = (SELECT UpdateUserID FROM tblPersonRelationship WHERE PersonRelationshipID = @ExistingRelationshipID) WHERE PersonRelationshipID = @OpposingRelationshipID END --otherwise add record ELSE IF (@OpposingRelationship IS NOT NULL) BEGIN INSERT INTO tblPersonRelationship SELECT @RelatedID, @OpposingRelationship, @PersonID, MarriageDate, NULL, NULL, ResidesWithPersonFlag, NULL, UpdateDateTime, UpdateProgram, UpdateUserID, UpdateDateTime, UpdateProgram, UpdateUserID, NULL FROM tblPersonRelationship WHERE PersonRelationshipID = @ExistingRelationshipID END END END ```
You should always specify explicitly the list of columns when doing the INSERT. Rewrite your code like this: ``` INSERT INTO tblPersonRelationship (RelatedID, PersonRelationshipID, PersonID, ...) SELECT @RelatedID, @OpposingRelationship, @PersonID, ... ``` A guid column was implicitly added to support merge replication, that's why you got the error about column lists mismatch.
This error message (Insert Error: Column name or number of supplied values does not match table definition) appears during an INSERT operation when either the number of supplied column names or the number of supplied values does not match the table definition. I think you are dealing with the latter -- **the number of supplied values does not match the table definition.** That's my hunch based on the fact that you noted a rowguid column has been added to one of your tables. Let's take your insert into tblPersonRelationship, for example. Based on the SELECT, one should assume tblPersonRelationship has 15 non-defaulted columns. If you added a rowguid column, it now needs to be represented in the SELECT in the proper position. ``` INSERT INTO tblPersonRelationship SELECT @RelatedID, @OpposingRelationship, @PersonID, MarriageDate, NULL, NULL, ResidesWithPersonFlag, NULL, UpdateDateTime, UpdateProgram, UpdateUserID, UpdateDateTime, UpdateProgram, UpdateUserID, NULL, newid() FROM tblPersonRelationship WHERE PersonRelationshipID = @ExistingRelationshipID ``` You may also get this error when dealing with computed columns. I don't believe this to be your issue, but you may [find more here](http://www.sql-server-performance.com/faq/supplied_value_not_match_p1.aspx).
Adding rowguid column broke this Stored Procedure?
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "replication", "" ]
When adding controls to a form at runtime, you can do either of the following: ``` Button btn = new Button(); //... this.Controls.Add(btn); ``` or ``` Button x = new Button(); //... btn.Parent = this; ``` I had assumed that they were the same, and it was just down to personal preference which way to do it, but someone at work mentioned that the second method is worse as the button will not get disposed when the form is disposed (assuming no event handlers have been added and are being held onto). This didn't make a lot of sense to me so I had a look online, but couldn't find anything to say one way or the other. Does someone know the answer or can point me in the right direction?
Since speculating is a waste of time, I grabbed my copy of [Reflector](http://www.red-gate.com/products/reflector/) and had a look at the actual code. The Parent property calls the ParentInternal property, which in turn calls **value.Controls.Add(this)** ``` /* this code is part of the .NET Framework was decompiled by Reflector and is copyright Microsoft */ internal virtual Control ParentInternal { get { return this.parent; } set { if (this.parent != value) { if (value != null) { value.Controls.Add(this); } else { this.parent.Controls.Remove(this); } } } } ``` Based on this code, the methods are equivalent and this is strictly a matter of preference.
I've always preferred identifying which object's controls I'm going to add the new control to... ``` Button btn = new Button(); this.PlaceHolder1.Controls.Add(btn); Button btn2 = new Button(); this.PlaceHolder2.Controls.Add(btn2); ``` I feel that this is easier to read and you don't have to do any family tree analysis to figure out who the parent is... I believe that using the .Parent code internally does the .Controls.Add, so they should have the same end result, but to me it comes down to code readability. There is a similar question here on [StackOverflow](https://stackoverflow.com/questions/961554/difference-between-setting-control-parent-property-and-using-controls-add).
Best practice for adding controls at run-time
[ "", "c#", ".net", "vb.net", "dynamic", "controls", "" ]
I have MAMP installed. Now I am trying to run a script from the command line, but I can't seem to get it to work. How should I set up my environment so that I can run a script from the command line and use the PHP version I installed with MAMP? **Update:** I agree with jjeaton below, [here is a nice solution](https://stackoverflow.com/questions/4262006/how-to-use-mamps-version-of-php-instead-of-the-default-on-osx) of creating an alias to MAMP's PHP: ``` # add this to your ~/.bash_profile alias phpmamp='/Applications/MAMP/bin/php/php5.3.6/bin/php' ``` Now you can use it from the command line: ``` $ phpmamp --help ```
Please note that with version 2.0.5 of MAMP, the path has changed. It is now one of the following: ``` /Applications/MAMP/bin/php/php5.2.17/bin/ /Applications/MAMP/bin/php/php5.3.6/bin/ ``` Therefore the command to add MAMP's php command should probably look like this: ``` export PATH=/Applications/MAMP/bin/php/php5.2.17/bin/:$PATH ``` or like this (depending on which version of PHP you want to use): ``` export PATH=/Applications/MAMP/bin/php/php5.3.6/bin/:$PATH ```
Another way that works that may be a little cleaner with regard to PHP versions is to create an alias in your bash profile that points to the specific php binary that you want to run when you run things like composer or other cli tools. This has the benefit of avoiding some potential library and php.ini config compatibility issues with the installed version of php in OSX. For instance, if you want to point to php 5.4.1 in MAMP, edit your .bash\_profile file in your editor of choice (nano, vi, etc.): ``` # nano ~/.bash_profile ``` Add this below your PATH statement: ``` alias php=/Applications/MAMP/bin/php/php5.4.10/bin/php ``` Save and quit (CTRL+X in nano, :wq in vi). Quit Terminal. The next time you try to call php from the cli, you'll be using the 5.4.10 version installed with MAMP. Remember to update this path if you update MAMP with a more recent version of PHP.
How to run a PHP script from the command line with MAMP?
[ "", "macos", "mamp", "php", "" ]
I'm experimenting with building sites dynamically on the client side, through JavaScript + a JSON content server, the js retrieves the content, and builds the page client-side. Now, the content won't be indexed by Google this way. Is there a workaround for this? Like having a crawler version and a user version? Or having some sort of static archives? Has anyone done this already?
If the site is meant to be indexed by google then the "information" you want searchable and public should be available without javascript. You can always add the dynamic stuff later after the page loads with javascript. This will not only make the page indexable but will also make the page faster loading. On the other hand if the site is more of an application 'ala gmail' then you probably don't want google indexing it anyway.
You should always make sure that your site works without javascript. Make links that link to static versions of the content. Then add javascript click handlers to those links that block the default action from hapening and make the AJAX request. I.e. using jQuery: HTML: ``` <a href='static_content.html' id='static_content'>Go to page!</a> ``` Javascript: ``` $('#static_content').click(function(e) { e.preventDefault(); //stop browser from following link //make AJAX request }); ``` That way the site is usable for crawlers and users without javascript. And has fancy AJAX for people with javascript.
Enabling SEO on AJAX pages
[ "", "javascript", "ajax", "seo", "" ]
I wrote a program for linux using libxml2 for html parsing. Although it does its job, the html parser writes lots of various errors to stderr. Is it possible to disable stderr at all (or redirect it to /dev/null while not having to run it with a redirecting shell script)? I can live with having to write my own errors to stdout, I just want to get rid of these errors.
Use freopen to redirect to dev/null: ``` freopen("/dev/null", "w", stderr); ```
`freopen()`ing `stderr` has already been mentioned, which addresses your specific question. But since you're working with libxml2, you may want finer grained control of the error messages and not just redirect all stderr messages categorically. The error messages are there for a reason, you know. See [libxml2 documentation](http://xmlsoft.org/html/libxml-xmlerror.html) on how to use error handlers with libxml2. A good starting point is `xmlSetGenericErrorFunc()`
Is it possible to disable stderr in C++?
[ "", "c++", "linux", "libxml2", "stderr", "" ]
Under certain circumstances my desktop app using SharePoint web services ends up with DefaultNetworkCredentials having null values, and so the call fails. I need to then obtain the users credentials, but I haven't found a straightfoward way to do so. I'm considering implementing the solution outlined in <http://www.pinvoke.net/default.aspx/credui/CredUIPromptForCredentialsW.html> ... however, this still is going to require that I handle the password, which I'd really rather not do. I've looked, but haven't been able to find a more direct method that prompts the user and returns a NetworkCredential directly, without my having to store the password? Thanks, EDIT: It looks like I'm not going to find exactly what I'm looking for... I'll have to prompt the user myself when this happens. However, if I'm interpreting some of these answers correctly, it may be an error condition for the DefaultNetworkCredentials to be null like this in the first place. Is that the case? Is there a way to force the DefaultNetworkCredentials to populate, or is it really a simple cache that's just remembering the last domain/userid/password used for the target URI (that day? that application/session?).
I don't think you can avoid handling them for the first time. But, you an hook into the Credential Manager so that they will be cached from that point forward. [Here's an article on how to do that](http://msdn.microsoft.com/en-us/library/aa302353.aspx). It's heavy in p/invoke, but could give your users a more consistent experience.
Work on the underlying issue, the null credentials rather than nagging the user for information they have already entered. Unless you want them to be able to log into SharePoint differently from thier current account (a useful feature perhaps). .NET has code for dealing with credentials, so why second guess that by going out to external dll's and adding another dependancy to your app? I do not know enough about code security risks you have in your environment, but I would have thought that storing the credentials object in client memory only would be "safe enough" for most situations.
DefaultNetworkCredentials has null values. Need to prompt user... how?
[ "", "c#", "sharepoint", "defaultnetworkcredentials", "credui", "" ]
I am thinking about creating a screen saver. I have the whole thing, its graphics and the back-end kind of ready in my head. But I am not quite sure how to get the graphics out in code. What I would like is a slide show of images with a bit of movement (kind of like the slide show in media center) and some floating text and shapes on top. The shapes somehow translucent. I currently have a very simple static slideshow made in WinForms. Just a simple application that goes fullscreen and displays some images and pretends to fade them in and out in a hackish kind of way. But it is not very well made, and the performance is not very good. For example to prevent lag, I fade in a black square on top of the image, instead of fading in the actual image. Silly perhaps, but it kind of worked :p Anyways, I would like to do a better job. But not sure where to start. Is WPF a good solution for this? Or should I look into DirectX or OpenGL? Is this something that could be handled well with XNA, or is that too game spesific?
WPF is not a bad idea. It takes advantage of DirectX and hardware acceleration for its animations and effects. You will get better performance if you write this kind of stuff natively (against directx or opengl), but the cost of writing it will be much higher. It's quite possible you will not need that edge anyway. Have a look at hanselman's [baby smash](http://www.hanselman.com/babysmash/) (which is a full screen wpf app with animations) to get a grasp of what you can do with wpf. Note: I did write a slide show kind of thingy in WPF way back, the key to getting this to work smoothly is loading up the images in a background thread and [freezing it](http://msdn.microsoft.com/en-us/library/ms750509.aspx).
I guess XNA works well. There's a sample screensaver in C# Express, by the way.
C#: Creating a graphical screensaver
[ "", "c#", "wpf", "opengl", "graphics", "directx", "" ]
Lately I've been considering creating a sort of "toolbox" for myself in java. It would consist of standard algorithms and data structures that are frequently used, but a pain to implement. (I'm thinking graphs, trees, etc) What would be the best way to do this? I was thinking about either using generics or using an abstract class. This way I could have any object that wanted to use the methods simply provide a getGraphData() method or something similar. I think that generics might be better though because an abstract class would force me to inherit from it, which could become problematic.
This is called a library... General purpose stuff should be in the Java library. If some stuff that you want is missing, you might try additional libraries such as Google Collections. You might also want domain-specific libraries.
two ways to go about it: Way 1: 1. Create a class Graph 2. Create methods in the Graph class, each corresponding to an algorithm of yours. Way 2: 1. Create a class Graph (purely a data structure) 2. Create a class Algorithm 3. Subclass Algorithm to define each new algorithm of yours. Of course, it would best if you look at the STL algorithms and model your graph algorithms in a similar fashion. You could even open source your data structures and assocaited algorithms. This way the community can take care of newer algos, effeciency considerations, integration into/with existing libraries etc. jrh.
Making a personal programming toolbox
[ "", "java", "toolbox", "" ]
In my program I need to create sockets and bind them to listen HTTP port (80). The program works fine when I launch it from command line with sudo, escalating permissions to root. Running under XCode gives a 'permission denied' error on the call to binding function (asio::ip::tcp::acceptor::bind()). How can I do debugging under XCode? All done in C++ and boost.asio on Mac OS X 10.5 with XCode 3.1.2.
**Update**: For Xcode 4.5 and later, see [this answer](https://stackoverflow.com/a/14068416/100478) instead. --- The only way I'm aware of to do what you're asking is to run Xcode as root. ``` >> sudo /Developer/Applications/Xcode.app/Contents/MacOS/Xcode ``` Once you're running as root, anything processes launched from Xcode will also run as root. Note, though, that if you create or edit any files, they will be owned by root, which means that you'll have to `chown` them before you can edit them as your normal user first. I'd love a way for Xcode to say "Launch process as root", but as far as I know, no such functionality is available. Note that you can also run the application within the command-line debugger `gdb` to debug your application. Run ``` >> sudo gdb /path/to/my/application ``` Then you could keep Xcode open, modify at will, and debug your program within gdb. This is what I generally do. **EDIT**: Readers from the future: see the answer from Alexander Stavonin; it talks about how to do this. If you're okay with ssh keys and enabling the root user on your system, his answer is the way to go.
In Xcode 4.5 `Product`->`Edit Scheme`: Look in the *Info* tab under *Debug Process As* and choose the *root* option.
Debugging in XCode as root
[ "", "c++", "xcode", "debugging", "sockets", "root", "" ]
I have an C# application that needs to list a directory ( Directory.GetFiles() ) and also to access one of the files returned. If I run the application locally it doesnt have problem access the network location or the local locations, if I run it from a network share then I get a security exception thrown when accessing the shares. I found out why this is happening: <http://blogs.msdn.com/shawnfa/archive/2003/06/20/57023.aspx> However the solutions seem... impractical unless I am misunderstanding it. 1) I can not use the code ( hardly an option ) 2) Sign the assemblies and then have whoever is going to use it configure .NET policies to allow it? ( This relies on the person whos going to use it to change one of their policies which I have no say in ??) 3) Change the policy to allow full trust for everything on localintranet ( Not recommended or even possible in my case ) Am I missing something here, none of those choices seem optimal for a stand alone application being pushed onto a network I have no say in. I would have thought doing something as relatively simple as running an application from a network share to list files in a directory wouldnt have required such crazy hoops to jump through to make it work. Anyone have any thoughts on what I could do in this situation?
These threads will answer you question, I think: * [Why does my .NET application crash when run from a network drive?](https://stackoverflow.com/questions/148879/why-does-my-net-application-crash-when-run-from-a-network-drive) * [Running a C# exe file](https://stackoverflow.com/questions/804132/running-a-c-exe-file/) This behaviour is changed in .NET Framework 3.5 SP1, where it defaults to allowing programs running off network shares. And yes, it does not feel very practical, but there is unfortunately not much to do about that...
I would deploy it as a ClickOnce app ("Publish" in VS2008 etc). ClickOnce can be located on a network share - you just run the .application instead of the .exe; this then works with none of the security issues with running it directly, and it'll work all the way back to .NET 2.0.
My .net application works on local machine but fails when used from a network location
[ "", "c#", ".net", "security", "" ]
I have a .Net application which renders graphics using GDI+ and/or XNA and I want to record the frames directly into a video (preferably an AVI, where I can include a codec like xvid etc). I've tried many of the solutions out there, and run into show stoppers with all of them. All of the FFMPeg based libs seem to be dedicated to transcoding an existing stream, not so much generating a new one from frames. There is a .Net lib called Splicer on codeplex, but from what I can tell it is more geared towards building a "slideshow" because it takes each frame and stores it on the HD. The directshow solutions behave the same way. Then there is the AVIFile wrapper, which is almost exactly what I need. The only problem is that when you start a new encoding it pops up (and sometimes UNDER!?) a dialog box. The dialog isn't a problem for normal use, but I also need this to run as a service, so mandatory UI is obviously a show stopper. Anyone know of another option that is relatively .Net friendly, or am I just asking too much?
I don't know which AVIFile wrapper you're using, but I believe AviFile is probably calling AVISaveOptions to get an initialized AVICOMPRESSOPTIONS struct. You can just initialize AVICOMPRESSOPTIONS yourself. Most members in AVICOMPRESSOPTIONS are pretty easy. lpParms and cbParms contain a block (cbParms = length of block) of binary codec configuration data. You can get this data calling ICGetState. It should be a fairly simple change to your native AVIFile and your wrapper should still work. Have a look at this [sample](http://cgs.hpi.uni-potsdam.de/trac/vrs/browser/trunk/src/image/avimaker.cpp?rev=6115&format=txt) for how to init AVICOMPRESSOPTIONS.
Check out [this question](http://forums.xna.com/forums/p/29668/166902.aspx) on the XNA forums for some insight and considerations if you want to do this in XNA. In particular, this answer by the ZMan: > "There's nothing in XNA to help you > here - you need to be looking at other > windows APIs. You would use XNA to > capture the back buffer and then save > each frame out but there's many things > to be concerned about. Pulling each > frame from the back buffer instantly > creates some latency, compressing the > images (if you choose to compress on > the fly) is CPU heavy, saving to a > file adds latency. > > DirectShow is one API you can use to > do the compression - there's many > others. Off/MP4 etc. SOund recording > has DSound and I think DShow can use > DSound to grab the audio output too. > They are fairly specialist APIs so you > might want to seek out other forums."
Create Video, Frame by frame, from .Net
[ "", "c#", ".net", "video", "" ]
I want to use ADO.net to extract some data from an Excel file. This process is pretty well documented on the internet. My catch is that my file has been uploaded by a user, and so exists only as a byte array in memory. For security and performance reasons I would rather not write this file to disk. Is there a way of constructing a connection string that connects to a byte array? Or perhaps exposing that array as a file that is actually stored in memory (like a RAM disk I guess)?
You can't connect if it only exists in memory. OLE is also ruled out (though using Office Automation for a server application is poor design to begin with). The only way I can think of is to read the binary Excel data yourself - for example use SpreadSheetGear.Net with something like: ``` SpreadsheetGear.Factory.GetWorkbookSet().Workbooks.OpenFromStream(*stream*); ```
Like Rich B said in his answer, I do not think it is possible to connect in a standard ado.net way to an excel file that is just hanging around in memory. The simplest work-around would probably be to actually save the excel file to the disk, connect to it using the Jet engine with your connection string, and then when you are done performing all your tasks, get rid of the file. This may not be the ideal in terms of performance, but it is lacking that certain WTFiness which would cause you to pull your hair out.
Read an in-memory Excel file (byte array) with ADO.NET?
[ "", "c#", "excel", "ado.net", "connection-string", "" ]
What is the best way to achieve this exclusion matrix via query. There are fixed number of products in a table and idea is if a product is sold to a customer (represented by row), the other products (columns) may or may not be sold based on the rule matrix below. The aim is to get products code which are allowed to sold for any given sold product code. ``` ProductCode|MRLSPN|MRLSPPN|MRLSDF|MRLSPDF|LGS|LGP|HOBN|HODF|HVO|HVOF MRLSPN |No |No |No |No |No |Yes|No |No |No |No MRLSPPN |No |No |No |No |No |No |No |No |No |No MRLSDF |No |No |No |No |No |Yes|No |No |No |No MRLSPDF |No |No |No |No |No |No |No |No |No |No LGS |No |No |No |No |No |Yes|No |No |No |No LGP |Yes |No |Yes |No |No |No |No |No |No |No HOBN |No |No |No |No |Yes|Yes|No |No |No |No HODF |No |No |No |No |Yes|Yes|No |No |No |No HVO |Yes |Yes |Yes |Yes |Yes|Yes|Yes |Yes |No |No HVOF |Yes |Yes |Yes |Yes |Yes|Yes|Yes |Yes |No |No ``` Ready by row across columns.
Can you change your format from a matrix to an association table like Table AdditionalProducts: SoldProductCode AdditionalProductCode So your table would look like ``` SoldProdCode, Additional ProdCode MRLSPN, LGP MRLSDF, LGP ``` Now you can simply run a query to say ``` SELECT AdditionalProductCode FROM AdditionalProducts WHERE SoldProductcode='MRLSPN' ``` **Edit** Another benefit of this approach is that what if you give special discounts if you buy MRLSPN you get LGP at 10% off and if you buy MRLSDF you might get 15$ off. With this model you can extend the association table to include additional attributes. This may or may not apply to your model.
If you can guarantee no more than 32 columns, you can implement using an int (32 bits) as a bit-flag field. But a many-to-many relationship will be more flexible. Create a many-to-many mapping table, ProductCode2ProductCodeMapping ``` CREATE TABLE ProductCode2ProductCodeMapping ( ProductCodeId int, AllowedProductCodeId int ) ``` With a composite primary key using both those columns. Then insert a row for every product and related product. Then simply query as: ``` SELECT AllowedProductCodeId FROM ProductCode2ProductCodeMapping WHERE ProductCodeId = @myProductCodeId ``` If you don't have integer Id's for products you can either add them or use the char productCode instead (I'd prefer the former)
Best way to achieve exclusion matrix via query
[ "", "sql", "matrix", "sql-server-2000", "" ]
I'm trying to generate some code in a web service. But it's returning 2 errors: 1) List is a type but is used like a variable 2) No overload for method 'Customer' takes '3 arguments' ``` [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class wstest : System.Web.Services.WebService { [WebMethod] public List<Customer> GetList() { List<Customer> li = List<Customer>(); li.Add(new Customer("yusuf", "karatoprak", "123456")); return li; } } public class Customer { private string name; private string surname; private string number; public string Name { get { return name; } set { name = value; } } public string SurName { get { return surname; } set { surname = value; } } public string Number { get { return number; } set { number = value; } } } ``` How can i adjust above error?
The problem is at the line ``` List<Customer> li = List<Customer>(); ``` you need to add "new" ``` List<Customer> li = new List<Customer>(); ``` Additionally for the next line should be: ``` li.Add(new Customer{Name="yusuf", SurName="karatoprak", Number="123456"}); ``` **EDIT:** If you are using VS2005, then you have to create a new constructor that takes the 3 parameters. ``` public Customer(string name, string surname, string number) { this.name = name; this.surname = surname; this.number = number; } ```
This ``` List<Customer> li = List<Customer>(); ``` needs to be: ``` List<Customer> li = new List<Customer>(); ``` and you need to create a Customer constructor which takes the 3 arguments you want to pass. The default Customer constructor takes no arguments.
how to adjust "is a type but is used like a variable"?
[ "", "c#", ".net", "asp.net", "generics", "" ]
My guess is it just made parsing easier, but I can't see exactly why. So what does this have ... ``` do { some stuff } while(test); more stuff ``` that's better than ... ``` do { some stuff } while(test) more stuff ```
Because you're ending the statement. A statement ends either with a block (delimited by curly braces), or with a semicolon. "do this while this" is a single statement, and can't end with a block (because it ends with the "while"), so it needs a semicolon just like any other statement.
If you take a look at C++ grammar, you'll see that the iteration statements are defined as > **while (** *condition* **)** *statement* > > **for (** *for-init-statement condition*-opt **;** *expression*-opt **)** *statement* > > **do** *statement* **while (** *expression* **) ;** Note that only `do-while` statement has an `;` at the end. So, the question is why the `do-while` is so different from the rest that it needs that extra `;`. Let's take a closer look: both `for` and regular `while` end with a *statement*. But `do-while` ends with a controlling *expression* enclosed in `()`. The presence of that enclosing `()` already allows the compiler to unambiguously find the end of the controlling expression: the outer closing `)` designates where the expression ends and, therefore, where the entire `do-while` statement ends. In other words, the terminating `;` is indeed redundant. However, in practice that would mean that, for example, the following code ``` do { /* whatever */ } while (i + 2) * j > 0; ``` while *valid* from the grammar point of view, would really be parsed as ``` do { /* whatever */ } while (i + 2) *j > 0; ``` This is formally sound, but it is not really intuitive. I'd guess that for such reasons it was decided to add a more explicit terminator to the `do-while` statement - a semicolon. Of course, per @Joe White's answer there are also considerations of plain and simple consistency: all ordinary (non-compound) statements in C end with a `;`.
In C/C++ why does the do while(expression); need a semi colon?
[ "", "c++", "c", "language-design", "" ]
Using C#, I need to get all Firefox bookmarks for importing them into our database. How can I do this? I'm aware of the SO question, [Read FF 3 bookmarks in Java](https://stackoverflow.com/questions/81132/read-firefox-3-bookmarks), but the answers there all seem to revolve around Java database drivers, and I'm not sure that some of those answers aren't Java-specific. **My primary question is**, "How can I read Firefox bookmarks in C#?" Secondary questions: I see \%user profile%\application data\mozilla\firefox\profiles\bookmarkbackups\bookmarks-[date].json files -- can I just parse that? If so, are there any existing parsers for that? Rhetorical lamenting question: Why can't this be as easy as IE, where I just read the .url files in \%user profile%\favorites? Bah.
Use the SQLite driver for .Net and access the file **places.sqlite** it can be found at `Application Data/Mozilla/Firefox/Profiles/$this_varies/places.sqlite` on my computer. It should not be hard for you to locate on your target computers. Edit 1: Here is a snip of code that prints out urls from the database: ``` using System.Data.SQLite; // downloaded from http://sourceforge.net/projects/adodotnetsqlite namespace sqlite_test { class Program { static void Main(string[] args) { var path_to_db = @"C:\places.sqlite"; // copied here to avoid long path SQLiteConnection sqlite_connection = new SQLiteConnection("Data Source=" + path_to_db + ";Version=3;New=True;Compress=True;"); SQLiteCommand sqlite_command = sqlite_connection.CreateCommand(); sqlite_connection.Open(); sqlite_command.CommandText = "select * from moz_places"; SQLiteDataReader sqlite_datareader = sqlite_command.ExecuteReader(); while (sqlite_datareader.Read()) { // Prints out the url field from the table: System.Console.WriteLine(sqlite_datareader["url"]); } } } } ``` Edit 2: As tip. I really must recommend the SQLite Manager plugin for firefox. It's very useful for working with sqlite databases.
Surely it works the same way as suggested in the Java question, just get the [SQLite .NET provider](http://sqlite.phxsoftware.com/) and use that to access the FF database file.
Read Firefox bookmarks using C#
[ "", "c#", "firefox", "bookmarks", "favorites", "" ]
C++ provides a syntax for checked exceptions, for example: ``` void G() throw(Exception); void f() throw(); ``` However, the Visual C++ compiler doesn't check them; the throw flag is simply ignored. In my opinion, this renders the exception feature unusable. So my question is: ***is there a way to make the compiler check whether exceptions are correctly caught/rethrown?*** For example a Visual C++ plugin or a different C++ compiler. PS. I want the compiler to check whether exceptions are correctly caught, otherwise you end up in a situation where you have to put a catch around every single function call you make, *even if they explicitly state they won't throw anything*. **Update:** the Visual C++ compiler does show a warning when throwing in a function marked with throw(). This is great, but regrettably, the warning doesn't show up when you call a subroutine that might throw. For example: ``` void f() throw(int) { throw int(13); } void h() throw() { g(); } //no warning here! ```
Exception specifications are pretty useless in C++. It's not enforced that no other exceptions will be thrown, but merely that the global function `unexpected()` will be called (which can be set) Using exception specifications mainly boils down to deluding yourself (or your peers) into some false sense of security. Better to simply not bother.
What's funny is that Java has checked exceptions, and Java programmers hate those too. Exception specifications in C++ are useless for 3 reasons: **1. C++ exception specifications inhibit optimization.** With the exception possibly of throw(), compilers insert extra code to check that when you throw an exception, it matches the exception specification of functions during a stack unwind. Way to make your program slower. **2. C++ exception specifications are not compiler-enforced** As far as your compiler is concerned, the following is syntactically correct: ``` void AStupidFunction() throw() { throw 42; } ``` What's worse, nothing useful happens if you violate an exception specification. Your program just terminates! **3. C++ exception specifications are part of a function's signature.** If you have a base class with a virtual function and try to override it, the exception specifications must match exactly. So, you'd better plan ahead, and it's still a pain. ``` struct A { virtual int value() const throw() {return 10;} } struct B : public A { virtual int value() const {return functionThatCanThrow();} // ERROR! } ``` Exception specifications give you these problems, and the gain for using them is minimal. In contrast, if you avoid exception specifications altogether, coding is easier and you avoid this stuff.
Why aren't exceptions in C++ checked by the compiler?
[ "", "c++", "exception", "visual-c++", "" ]
Is there a perceptible difference between using `String.format` and String concatenation in Java? I tend to use `String.format` but occasionally will slip and use a concatenation. I was wondering if one was better than the other. The way I see it, `String.format` gives you more power in "formatting" the string; and concatenation means you don't have to worry about accidentally putting in an extra %s or missing one out. `String.format` is also shorter. Which one is more readable depends on how your head works.
I'd suggest that it is better practice to use `String.format()`. The main reason is that `String.format()` can be more easily localised with text loaded from resource files whereas concatenation can't be localised without producing a new executable with different code for each language. If you plan on your app being localisable you should also get into the habit of specifying argument positions for your format tokens as well: ``` "Hello %1$s the time is %2$t" ``` This can then be localised and have the name and time tokens swapped without requiring a recompile of the executable to account for the different ordering. With argument positions you can also re-use the same argument without passing it into the function twice: ``` String.format("Hello %1$s, your name is %1$s and the time is %2$t", name, time) ```
About performance: ``` public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); for(int i = 0; i < 1000000; i++){ String s = "Hi " + i + "; Hi to you " + i*2; } long end = System.currentTimeMillis(); System.out.println("Concatenation = " + ((end - start)) + " millisecond") ; start = System.currentTimeMillis(); for(int i = 0; i < 1000000; i++){ String s = String.format("Hi %s; Hi to you %s",i, + i*2); } end = System.currentTimeMillis(); System.out.println("Format = " + ((end - start)) + " millisecond"); } ``` The timing results are as follows: * Concatenation = 265 millisecond * Format = 4141 millisecond Therefore, concatenation is much faster than String.format.
Is it better practice to use String.format over string Concatenation in Java?
[ "", "java", "string", "concatenation", "string.format", "" ]
I am working on a (database-ish) project, where data is stored in a flat file. For reading/writing I'm using the `RandomAccessFile` class. Will I gain anything from multithreading, and giving each thread an instance each of `RandomAccessFile`, or will one thread/instance be just as fast? Is there any difference in reading/writing, as you can make instances that only do the reading, and can't write?
A fairly common question. Basically using multiple threads will not make your hard drive go any faster. Instead performing concurrent request can make it slower. Disk subsystems, esp IDE, EIDE, SATA, are designed to read/write sequentially fastest.
I now did a benchmark with the code below (excuse me, its in cpp). The code reads a 5 MB textfile with a number of threads passed as a command line argument. The results clearly show that **multiple threads always speed up a program**: **Update:** It came to my mind, that file caching will play quite a role here. So i made copies of the testdata file, rebooted and used a different file for each run. Updated results below (old ones in brackets). The conclusion remains the same. Runtime in Seconds Machine A (Dual Quad Core XEON running XP x64 with 4 10k SAS Drives in RAID 5) * 1 Thread: 0.61s (0.61s) * 2 Threads: 0.44s (0.43s) * 4 Threads: 0.31s (0.28s) (Fastest) * 8 Threads: 0.53s (0.63s) Machine B (Dual Core Laptop running XP with one fragmented 2.5 Inch Drive) * 1 Thread: 0.98s (1.01s) * 2 Threads: 0.67s (0.61s) (Fastest) * 4 Threads: 1.78s (0.63s) * 8 Threads: 2.06s (0.80s) Sourcecode (Windows): ``` // FileReadThreads.cpp : Defines the entry point for the console application. // #include "Windows.h" #include "stdio.h" #include "conio.h" #include <sys\timeb.h> #include <io.h> /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// int threadCount = 1; char *fileName = 0; int fileSize = 0; double GetSecs(void); /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// DWORD WINAPI FileReadThreadEntry(LPVOID lpThreadParameter) { char tx[255]; int index = (int)lpThreadParameter; FILE *file = fopen(fileName, "rt"); int start = (fileSize / threadCount) * index; int end = (fileSize / threadCount) * (index + 1); fseek(file, start, SEEK_SET); printf("THREAD %4d started: Bytes %d-%d\n", GetCurrentThreadId(), start, end); for(int i = 0;; i++) { if(! fgets(tx, sizeof(tx), file)) break; if(ftell(file) >= end) break; } fclose(file); printf("THREAD %4d done\n", GetCurrentThreadId()); return 0; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { if(argc <= 1) { printf("Usage: <InputFile> <threadCount>\n"); exit(-1); } if(argc > 2) threadCount = atoi(argv[2]); fileName = argv[1]; FILE *file = fopen(fileName, "rt"); if(! file) { printf("Unable to open %s\n", argv[1]); exit(-1); } fseek(file, 0, SEEK_END); fileSize = ftell(file); fclose(file); printf("Starting to read file %s with %d threads\n", fileName, threadCount); /////////////////////////////////////////////////////////////////////////// // Start threads /////////////////////////////////////////////////////////////////////////// double start = GetSecs(); HANDLE mWorkThread[255]; for(int i = 0; i < threadCount; i++) { mWorkThread[i] = CreateThread( NULL, 0, FileReadThreadEntry, (LPVOID) i, 0, NULL); } WaitForMultipleObjects(threadCount, mWorkThread, TRUE, INFINITE); printf("Runtime %.2f Secs\nDone\n", (GetSecs() - start) / 1000.); return 0; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// double GetSecs(void) { struct timeb timebuffer; ftime(&timebuffer); return (double)timebuffer.millitm + ((double)timebuffer.time * 1000.) - // Timezone needed for DbfGetToday ((double)timebuffer.timezone * 60. * 1000.); } ```
Will using multiple threads with a RandomAccessFile help performance?
[ "", "java", "performance", "multithreading", "file-io", "concurrency", "" ]
I wrote a Listener. Now I want to notify it, when a change occurs. Nothing special. Now I'm asking myself: Is there I standard class for Events that I can use, or do I have to write a new one by myself? I know there ara java.awt.Event and AWTEvent. But I am not working directly at GUI level here. Furthermore we are using Swing at GUI level. So I'm not shure if it is a good idea to mix Swing and AWT. Thx
Its ancient and simple, but you could use Observer/Obserable in java.util: > java.util > > public class Observable extends Object > > This class represents an observable > object, or "data" in the model-view > paradigm. It can be subclassed to > represent an object that the > application wants to have observed. > > An observable object can have one or > more observers. An observer may be any > object that implements interface > Observer. After an observable instance > changes, an application calling the > Observable's notifyObservers method > causes all of its observers to be > notified of the change by a call to > their update method. For more info, try <http://www.javaworld.com/javaworld/jw-10-1996/jw-10-howto.html>.
There's nothing special about events in Java. If your events are not GUI events, then it would be less confusing for you to use your own class and not mix them with `java.awt.Events`.
Is there an standard class for Events in Java?
[ "", "java", "" ]
How do I get a NameTable from an XDocument? It doesn't seem to have the NameTable property that XmlDocument has. EDIT: Judging by the lack of an answer I'm guessing that I may be missing the point. I am doing XPath queries against an XDocument like this... ``` document.XPathSelectElements("//xx:Name", namespaceManager); ``` It works fine but I have to manually add the namespaces I want to use to the XmlNamespaceManager rather than retrieving the existing nametable from the XDocument like you would with an XmlDocument.
You need to shove the XML through an XmlReader and use the XmlReader's NameTable property. If you already have Xml you are loading into an XDocument then make sure you use an XmlReader to load the XDocument:- ``` XmlReader reader = new XmlTextReader(someStream); XDocument doc = XDocument.Load(reader); XmlNameTable table = reader.NameTable; ``` If you are building Xml from scratch with `XDocument` you will need to call XDocument's `CreateReader` method then have something consume the reader. Once the reader has be used (say, by loading another XDocument, or better: some do-nothing sink which just causes the reader to run through the XDocument's contents) you can retrieve the NameTable.
I did it like this: ``` //Get the data into the XDoc XDocument doc = XDocument.Parse(data); //Grab the reader var reader = doc.CreateReader(); //Set the root var root = doc.Root; //Use the reader NameTable var namespaceManager = new XmlNamespaceManager(reader.NameTable); //Add the GeoRSS NS namespaceManager.AddNamespace("georss", "http://www.georss.org/georss"); //Do something with it Debug.WriteLine(root.XPathSelectElement("//georss:point", namespaceManager).Value); ```
How do I get a NameTable from an XDocument?
[ "", "c#", "xml", "xpath", "linq-to-xml", "" ]
I am trying to follow [this tutorial](http://www-lehre.inf.uos.de/~btenberg/misc/DB-Access-in-GWT-The-Missing-Tutorial.pdf) on how to connect to a database in GWT, but instead of creating a login program, I am trying to retrieve a GWT Visulation DataTable from my DB so that I can then create a Annotated TimeLine. I have gotten very far, but I hit the final wall I can't figure out. Unlike the tut, I am not returning a simple User class from the RPC, but a complex DataTable. The problem is that this DataTable must be serializable by GWT standards. Is there any easy way for accomplish this? I am using a RPC, instead of a Query system for security reasons. I don't want people to by able to look at my javascript and see my queries and such. Thank you. UPDATE: After going back to the problem I have found that DataTable is a JavaScriptObject and was probably never meant to be made on the server side. So new question, What is the best way to manually make DataTable into something serlizable and then what is the best way to remake it client side. Thanks Again!
Ok so I figured it out myself (sorta) so I thought I would post the answer here in case someone else happens to have the same problem later. The answer in short that is impossible. DataTable is a JSO object, and in GWT current release (1.6something) it can not serialize those types of objects. What I had to do was break down my data into a series of ArrayLists and hold those in a temperay Object. That object can then be serialized and sent to the client side. The problem with this is that you must then construct the DataTable object on the client side. If anyone else happens to come up with a better idea I would still be interested on finding out. Thanks. -Eric
I think you can do it on server side ``` String json = JsonRenderer.renderDataTable(yourDataTable, true, true); ``` and on client side use some thing like ``` public static native DataTable toDataTable(String json) /*-{ return new $wnd.google.visualization.DataTable(eval("(" + json + ")")); }-*/; ``` I think it should work
GWT Visualisation API DataTable Serialization
[ "", "java", "serialization", "gwt", "" ]
I'm finally wrapping my head around IoC and DI in C#, and am struggling with some of the edges. I'm using the Unity container, but I think this question applies more broadly. Using an IoC container to dispense instances that implement IDisposable freaks me out! How are you supposed to know if you should Dispose()? The instance might have been created just for you (and therefor you should Dispose() it), or it could be an instance whose lifetime is managed elsewhere (and therefor you'd better not). Nothing in the code tells you, and in fact this could change based on configuration!!! This seems deadly to me. Can any IoC experts out there describe good ways to handle this ambiguity?
[AutoFac](http://code.google.com/p/autofac/) handles this by allowing the creation of a nested container. When the container is finished with, it automatically disposes of all IDisposable objects within it. More [here](http://autofac.readthedocs.org/en/latest/lifetime/index.html). > .. As you resolve services, Autofac tracks disposable (IDisposable) components that are resolved. *At the end of the unit of work, you dispose of the associated lifetime scope and Autofac will automatically clean up/dispose of the resolved services.*
You definitely do not want to call Dispose() on an object that was injected into your class. You can't make the assumption that you are the only consumer. Your best bet is to wrap your unmanaged object in some managed interface: ``` public class ManagedFileReader : IManagedFileReader { public string Read(string path) { using (StreamReader reader = File.OpenRead(path)) { return reader.ReadToEnd(); } } } ``` That is just an example, I would use File.ReadAllText(path) if I were trying to read a text file into a string. Another approach is to inject a factory and manage the object yourself: ``` public void DoSomething() { using (var resourceThatShouldBeDisposed = injectedFactory.CreateResource()) { // do something } } ```
How do you reconcile IDisposable and IoC?
[ "", "c#", "inversion-of-control", "unity-container", "idisposable", "" ]
Can I do normal computations with iterators, i.e. just increment it by adding a number? As an example, if I want to remove the element `vec[3]`, can I just do this: ``` std::vector<int> vec; for(int i = 0; i < 5; ++i){ vec.push_back(i); } vec.erase(vec.begin() + 3); // removes vec[3] element ``` It works for me (g++), but I'm not sure if it is *guaranteed* to work.
It works if the iterator is a random access iterator, which vector's iterators are (see [reference](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator)). The STL function [`std::advance`](http://en.cppreference.com/w/cpp/iterator/advance) can be used to advance a generic iterator, but since it doesn't return the iterator, I tend use + if available because it looks cleaner. **C++11 note** Now there is [`std::next`](http://en.cppreference.com/w/cpp/iterator/next) and [`std::prev`](http://en.cppreference.com/w/cpp/iterator/prev), which *do* return the iterator, so if you are working in template land you can use them to advance a generic iterator and still have clean code.
A subtle point is that the `operator+` takes a `Distance`; i.e., a signed integer. If you increment the iterator by an unsigned, you may lose precision and run into a surprise. For example on a 64 bit system, ``` std::size_t n = (1 << 64) - 2; std::vector<double> vec(1 << 64); std::vector<double> slice(vec.begin() + n, vec.end()); ``` leads to implementation-defined behavior. With `g++` or `clang`, you can ask the compiler to warn you about such undesired conversions with the warning flag `-Wsign-conversion` that is not part of the canonical `-Wall` or `-Wextra`. A work-around is to work on the pointer directly ``` std::vector<double> slice(vec.data() + n, vec.data() + vec.size()); ``` It's not pretty but correct. In some occasions, you need to construct the iterator manually, for example ``` std::vector<double>::iterator fromHere{vec.data() + n}; vec.erase(fromHere, vec.end()); ```
Can I increment an iterator by just adding a number?
[ "", "c++", "iterator", "" ]
I'm preparing to write a COLLADA importer in Java. There aren't any pre-written importers, and even if there were I would probably be picky, so I believe this is best. I am going with COLLADA 1.4 because I do not need the 1.5 features, and many programs don't yet support it. I found the [spec](http://www.khronos.org/files/collada_spec_1_4.pdf) for it and plan on following it, but it is much easier to follow by example and reference the spec for additional information. So with all that... Can some of you who are experienced in COLLADA point me to some simple models that I can use to learn and test my importer as I write it? I will export a few with just geometry, but I need some with textures or materials, with skeletal and keyframe animation, etc. Any suggestions? Alternatively, I know that Blender can export COLLADA 1.4 and it can import most formats. If you have a really good suggestion for a site that has simple 3D models in another format that I will just import and export as COLLADA, that would be fine too! Thanks!
I know two decent places at least: * [Thingiverse tag: 3D](http://www.thingiverse.com/tag:3D) * [Google 3D Warehouse](https://3dwarehouse.sketchup.com/index.html) The google site has lots of collada files, thingiverse has more in the way of stl (sterio lithography) files.
Download Assimp the "Open Asset Import Library" from <http://assimp.sourceforge.net/main_downloads.html>. It has a whole bunch of Collada files (in test/models/Collada) that it uses for its test suites.
Sample COLLADA files for development of an importer?
[ "", "java", "3d", "file-format", "blender", "collada", "" ]
Are inner classes commonly used in Java? Are these the same as nested classes? Or have these been replaced in Java by something better? I have a book on version 5 and it has an example using an inner class, but I thought I read somewere that inner classes were "bad." I have no idea and was hoping for thoughts on it. Thank you.
Inner classes are frequently used, and something very similar - anonymous classes - are practically indispensable, as they are the closest thing Java has to closures. So if you can't remember where you heard that inner classes are bad, try to forget about it!
They're not "bad" as such. They can be subject to abuse (inner classes of inner classes, for example). As soon as my inner class spans more than a few lines, I prefer to extract it into its own class. It aids readability, and testing in some instances. There's one gotcha which isn't immediately obvious, and worth remembering. Any non-`static` inner class will have an implicit reference to the surrounding outer class (an implicit 'this ' reference). This isn't normally an issue, but if you come to serialise the inner class (say, using [XStream](http://xstream.codehaus.org)), you'll find that this can cause you unexpected grief.
Are inner classes commonly used in Java? Are they "bad"?
[ "", "java", "inner-classes", "" ]
You can create various Java code templates in Eclipse via *Window > Preferences > Java > Editor > Templates* e.g. `sysout` is expanded to: ``` System.out.println(${word_selection}${});${cursor} ``` You can activate this by typing `sysout` followed by `CTRL+SPACE` What useful Java code templates do you currently use? Include the name and description of it and why it's awesome. I am looking for an original/novel use of a template rather than a built-in existing feature. * Create Log4J logger * Get swt color from display * Syncexec - Eclipse Framework * Singleton Pattern/Enum Singleton Generation * Readfile * Const * Traceout * Format String * Comment Code Review * String format * Try Finally Lock * Message Format i18n and log * Equalsbuilder * Hashcodebuilder * Spring Object Injection * Create FileOutputStream
The following code templates will both create a logger and create the right imports, if needed. **SLF4J** ``` ${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)} private static final Logger LOG = LoggerFactory.getLogger(${enclosing_type}.class); ``` **Log4J 2** ``` ${:import(org.apache.logging.log4j.LogManager,org.apache.logging.log4j.Logger)} private static final Logger LOG = LogManager.getLogger(${enclosing_type}.class); ``` **Log4J** ``` ${:import(org.apache.log4j.Logger)} private static final Logger LOG = Logger.getLogger(${enclosing_type}.class); ``` [Source](http://matthew.mceachen.us/blog/simple-log4j-eclipse-template-346.html). **JUL** ``` ${:import(java.util.logging.Logger)} private static final Logger LOG = Logger.getLogger(${enclosing_type}.class.getName()); ```
Some additional templates here: [Link I](http://fahdshariff.blogspot.com/2011/08/useful-eclipse-templates-for-faster.html) - [Link II](http://fahdshariff.blogspot.com/2008/11/eclipse-code-templates.html) I like this one: **readfile** ``` ${:import(java.io.BufferedReader, java.io.FileNotFoundException, java.io.FileReader, java.io.IOException)} BufferedReader in = null; try { in = new BufferedReader(new FileReader(${fileName})); String line; while ((line = in.readLine()) != null) { ${process} } } catch (FileNotFoundException e) { logger.error(e) ; } catch (IOException e) { logger.error(e) ; } finally { if(in != null) in.close(); } ${cursor} ``` **UPDATE**: The Java 7 version of this template is: ``` ${:import(java.nio.file.Files, java.nio.file.Paths, java.nio.charset.Charset, java.io.IOException, java.io.BufferedReader)} try (BufferedReader in = Files.newBufferedReader(Paths.get(${fileName:var(String)}), Charset.forName("UTF-8"))) { String line = null; while ((line = in.readLine()) != null) { ${cursor} } } catch (IOException e) { // ${todo}: handle exception } ```
Seeking useful Eclipse Java code templates
[ "", "java", "eclipse", "templates", "ide", "code-generation", "" ]
I have the following code: ``` public class DeserializeAndCompare { public static List<string> IntoXML() { List<string> PopList = new List<string>(); XmlSerializer serializer = new XmlSerializer(PopList.GetType()); string k = FileToolBox.position0; FileStream filestreamer = new FileStream(k.ToString(), FileMode.Open); PopList = (List<string>)serializer.Deserialize(filestreamer); filestreamer.Close(); return PopList; } } ``` I keep hitting an error with the line: PopList = (List)serializer.Deserialize(filestreamer); The error: InvalidOperationException was unhandled, There is an error in XML document(1,1). In this line: FileStream filestreamer = new FileStream(k, FileMode.open); I am trying to reference the 0th position of an array that holds strings. I'm basically going thru my directory, finding any files with a .xml extension and holding the filename paths in an array. Here is the code for my array: ``` public static class FileToolBox { public static string position0; public static void FileSearch() { //string position0; //array holding XML file names string[] array1 = Directory.GetFiles(@"s:\project", "*.xml"); Array.Sort(array1); Array.Reverse(array1); Console.WriteLine("Files:"); foreach (string fileName in array1) { Console.WriteLine(fileName); } position0 = array1[0]; } public static string Position0 { get { return position0; } set { position0 = value; } } } ``` Am i missing something here? How do i get rid of this error? Thanks in advance for the help.
Your XML file is not well formed, use a tool like XML Spy, XML notepad or open it up in IE and it will give you the error and the line it is on. You most likely have invalid characters like & somewhere in the file
That error is specifically indicating that the XML file being read is malformed. You should start by posting your XML. Also, try opening the XML in Firefox, because it may point out the problem with the XML as well.
Error in my XML?
[ "", "c#", "xml-serialization", "" ]
I am writing an application where I have a form with a panel. I have noticed that when I add another form to the panel, that the added form's keyboard shortcuts stop working. I am using the following code : ``` MainMenu m = new MainMenu(); m.TopLevel = false; m.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; m.Dock = System.Windows.Forms.DockStyle.Fill; pnl.Controls.Add(m); m.Visible = true; pnl.ResumeLayout(); ``` Is there anyway to make the keyboard shortcuts work? Regards
I found out that it was due to focus issues. I have since converted my forms to user controls and the problems have gone away.
My first guess (and it's totally a guess) is that you need to pass the parent/owner when constructing the child object, rather than just assigning parent ... could you show us that part of your code? Also, just glancing over your code, it seems strange to, for a MainMenu, set Dock to Fill....
keyboard shortcuts do not work when adding a form to a panel c#
[ "", "c#", ".net", "winforms", "keyboard-shortcuts", "" ]
I know how to get CPU usage and memory usage for a process, but I was wondering how to get it on a per-thread level. If the best solution is to do some P-Invoking, then that's fine too. Example of what I need: ``` Thread myThread = Thread.CurrentThread; // some time later in some other function... Console.WriteLine(GetThreadSpecificCpuUsage(myThread)); ```
Here's an example which does what you want <http://www.codeproject.com/KB/system/processescpuusage.aspx>
As said, memory use cannot be answered since that is an attribute of the process as a whole, but CPU use: ``` Process p = Process.GetCurrentProcess(); // getting current running process of the app foreach (ProcessThread pt in p.Threads) { // use pt.Id / pt.TotalProcessorTime / pt.UserProcessorTime / pt.PrivilegedProcessorTime } ```
How can I get CPU usage and/or RAM usage of a *THREAD* in C# (managed code)?
[ "", "c#", "performance", "multithreading", "memory-management", "cpu-usage", "" ]
I can use XDocument to build the following file which **works fine**: ``` XDocument xdoc = new XDocument ( new XDeclaration("1.0", "utf-8", null), new XElement(_pluralCamelNotation, new XElement(_singularCamelNotation, new XElement("id", "1"), new XElement("whenCreated", "2008-12-31") ), new XElement(_singularCamelNotation, new XElement("id", "2"), new XElement("whenCreated", "2008-12-31") ) ) ); ``` **However**, I need to build the XML file by **iterating through a collection** like this: ``` XDocument xdoc = new XDocument ( new XDeclaration("1.0", "utf-8", null)); foreach (DataType dataType in _dataTypes) { XElement xelement = new XElement(_pluralCamelNotation, new XElement(_singularCamelNotation, new XElement("id", "1"), new XElement("whenCreated", "2008-12-31") )); xdoc.AddInterally(xelement); //PSEUDO-CODE } ``` There is **Add**, **AddFirst**, **AddAfterSelf**, **AddBeforeSelf**, but I could get none of them to work in this context. **Is an iteration with LINQ like this possible?** # Answer: I took Jimmy's code suggestion with the root tag, changed it up a bit and it was exactly what I was looking for: ``` var xdoc = new XDocument( new XDeclaration("1.0", "utf-8", null), new XElement(_pluralCamelNotation, _dataTypes.Select(datatype => new XElement(_singularCamelNotation, new XElement("id", "1"), new XElement("whenCreated", "2008-12-31") )) ) ); ``` Marc Gravell posted a better answer to this [on this StackOverflow question](https://stackoverflow.com/questions/1032314/how-can-i-change-this-stringbuilder-to-xml-code-to-linq-to-xml/1032363#1032363).
You need a root element. ``` var xdoc = new XDocument( new XDeclaration("1.0", "utf-8", null), new XElement("Root", _dataTypes.Select(datatype => new XElement(datatype._pluralCamelNotation, new XElement(datatype._singlarCamelNotation), new XElement("id", "1"), new XElement("whenCreated", "2008-12-31") )) ) ); ```
If I'm not mistaken, you should be able to use XDocument.Add(): ``` XDocument xdoc = new XDocument ( new XDeclaration("1.0", "utf-8", null)); foreach (DataType dataType in _dataTypes) { XElement xelement = new XElement(_pluralCamelNotation, new XElement(_singularCamelNotation, new XElement("id", "1"), new XElement("whenCreated", "2008-12-31") )); xdoc.Add(xelement); } ```
How to build an XDocument with a foreach and LINQ?
[ "", "c#", "xml", "linq", "" ]
Is something like this possible: ``` SELECT DISTINCT COUNT(productId) WHERE keyword='$keyword' ``` What I want is to get the number of unique product Ids which are associated with a keyword. The same product may be associated twice with a keyword, or more, but i would like only 1 time to be counted per product ID
use ``` SELECT COUNT(DISTINCT productId) from table_name WHERE keyword='$keyword' ```
I would do something like this: ``` Select count(*), productid from products where keyword = '$keyword' group by productid ``` that will give you a list like ``` count(*) productid ---------------------- 5 12345 3 93884 9 93493 ``` This allows you to see how many of each distinct productid ID is associated with the keyword.
Using DISTINCT and COUNT together in a MySQL Query
[ "", "mysql", "sql", "" ]
I've just inherited this code in PHP which seems to do some kind of web service call to googles api. I'm not quite an expert on PHP and there is a few syntax questions I have specifically relating to the following line $soapClients = &APIlityClients::getClients(); I understand the double "::" as indicating that APIlityClients is a static class but I'm not sure what the "&" in front of APIlityClients means.
When you use an ampersand in front of a variable in PHP, you're creating a reference to that variable. ``` $foo = 'bar'; $baz = &$foo; echo $foo //bar echo $baz //bar $foo = 'foobazbar'; echo $foo //foobazbar echo $baz //foobazbar ``` Prior to PHP5, when you created an object from a class in PHP, that object would be passed into other variables **by value**. The object was NOT a reference, as is standard in most other object oriented (Java, C#, etc.) languages. However, by instantiating a class with an ampersand in front of it, you could create a reference to the returned object, and it would behave like an object in other languages. This was a common technique prior to PHP5 to achieve OOP like effects and/or improve performance.
It is PHP's version of getting a reference to something rather than copying its value. So in this case the `&` would retrieve a reference to the return value of `APIlityClients::getClients()` rather than a copy of the return value itself.
what does "&" mean in front of classes in php?
[ "", "php", "" ]
``` import sys print (sys.platform) print (2 ** 100) input('press Enter to exit') ``` Suppose I wanted to use the number 1 as the button that must be pressed to exit. How would I go about doing this?
Something like this will do what you want: ``` while(raw_input('Press "1" to exit.') != '1'): pass ```
Something like this? <http://mail.python.org/pipermail/python-list/1999-October/014262.html> Not so clean, but doable.
How can I tell if a certain key was pressed in Python?
[ "", "python", "" ]
I'm making a simple Guess-The-Number game with a GUI. I need to wait on a loop waiting for the user to input a number in a text box and press "OK". How do I wait for an event inside a loop? Note: I don't want message boxes. This is done in the main window, hence the need to wait for input. **EDIT:** I should have explained myself better. I know that there's a loop inside the GUI. What I want is *another* loop inside a method. Maybe there's a better way to do this. I could code stuff inside the button's event handler, now that I think about it. Although I'd need global variables. Whataver, I'll think about it, but I hope my question is clearer now. **EDIT 2:** Sorry that my question wasn't clear and the edit didn't do much help. First of all, the code is too big to be posted here. I'd probably have to post a screenshot of the GUI, so it wouldn't be of much use. Basically, I have two fields, "Max number" and "Number of allowed guesses". The user enters these two and clicks "Play". A new panel becomes available, with a text box and a "Guess" button. The user enters a guess, and the program checks to see if it's correct. The purpose of the second infinite loop is to avoid global variables. See, each time the user clicks "Play", the game has to generate a new random number as the correct guess. If everything is done inside a method, no problem. But if the "Guess" button's event handler is called multiple times, the number has to be stored as an instance variable of the Form. Sure, it's not big deal, but I think the number should be a property of the method directing the current game, not of the Form. I'd also have to keep track of the remaining number of guesses outside of the method. Again, it's no big deal. I just want to avoid globals if I can. Again, I'm sorry that my question wasn't too clear. I'm kind of tired, and I didn't feel like writing too much. If this still isn't clear, then don't bother. I'll think of something.
Jason Down's suggestion is wise, create a new `GuessingGame` class and add it to your project. I know you're worried about "global variables" (which everyone is taught in school *never* to use unless you absolutely have to), but think about your design specifications for a minute. > But if the "Guess" button's event handler is called multiple times, the number has to be stored as an instance variable of the Form. Sure, it's not big deal, but I think the number should be a property of the method directing the current game, not of the Form. As an alternative, store an instance of your `GuessingGame` class in the form. This is not a global variable! You said so yourself, the point of the game is keep track of the guesses and generate new numbers to guess every time "Play" is clicked. If you store an instance of the game in the form then open another form (e.g. a Help or About box), then the game's instance would not be available (thus, not global). The `GuessingGame` object is going to look something like: ``` public class GuessingGame { private static Random _RNG = new Random(); private bool _GameRunning; private bool _GameWon; private int _Number; private int _GuessesRemaining; public int GuessesRemaining { get { return _GuessesRemaining; } } public bool GameEnded { get { return !_GameRunning; } } public bool GameWon { get { return _GameWon; } } public GuessingGame() { _GameRunning = false; _GameWon = false; } public void StartNewGame(int numberOfGuesses, int max) { if (max <= 0) throw new ArgumentOutOfRangeException("max", "Must be > 0"); if (max == int.MaxValue) _Number = _RNG.Next(); else _Number = _RNG.Next(0, max + 1); _GuessesRemaining = numberOfGuesses; _GameRunning = true; } public bool MakeGuess(int guess) { if (_GameRunning) { _GuessesRemaining--; if (_GuessesRemaining <= 0) { _GameRunning = false; _GameWon = false; return false; } if (guess == _Number) { _GameWon = true; return true; } else { return false; } } else { throw new Exception("The game is not running. Call StartNewGame() before making a guess."); } } } ``` This way, all the data related to the game is encapsulated within the class. Hooking up the events is easy in the codebehind of the form: ``` GuessingGame game = new GuessingGame(); private void btnPlay_Click(object sender, EventArgs e) { int numberOfGuesses = Convert.ToInt32(txtNumberOfGuesses.Text); int max = Convert.ToInt32(txtMax.Text); game.StartNewGame(numberOfGuesses, max); } private void btnGuess_Click(object sender, EventArgs e) { int guess = Convert.ToInt32(txtGuess.Text); bool correct = game.MakeGuess(guess); if (correct) lblWin.Visible = true; if (game.GameEnded) { // disable guess button, show loss label } } ```
C# automatically loops infinitely waiting for events until your form is closed. You just need to respond to the button click event.
C# WinForms: Waiting for a button press inside an infinite loop
[ "", "c#", "events", "infinite-loop", "" ]
if the title seems too vague.. uhm i wanted to display every variable that i used to generate a page along with their variable names and values, is it possible and how? ``` foreach($_SESSION as $varname => $value) { print "<b>".$varname."</b> = $value <br/>"; } ``` ^the above sample is what i use to display all session variables, what if i need to display the variables i set to display the page? are they registered also in some form of an array or should i also echo them individually?
You can use [`get_defined_vars()`](http://php.net/get_defined_vars) which will give you an array of all variables declared in the scope that the function is called including globals like `$_SESSION` and `$_GET`. I would suggest printing it like so: ``` echo '<pre>' . print_r(get_defined_vars(), true) . '</pre>'; ```
The easiest way to do this is with [get\_defined\_vars()](http://au.php.net/get_defined_vars). **From the Documentation** > This function returns a multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables, within the scope that get\_defined\_vars() is called. Producing a var\_dump of this array will provide you with an extensive list. ``` var_dump( get_defined_vars() ); ```
in php is there a way to dump "all" variable names with their corresponding value?
[ "", "php", "debugging", "" ]
I'm trying to calculate the sum of an array of decimal values in PHP, but for some reason it keeps rounding to integers. for example: ``` $oldArray = array(0.00,1000.11,988.92,978.22,964.01,953.07,948.82,917.26,902.56,913.21,904.08,898.86,892.79); $myVar = 0.0; for($k=1;$k<10;$k++) { $myVar += $oldArray[$k]; } print_r($myVar); ``` $oldArray is actually populated with decimal values from an SQL query (the length of $oldarray is about several hundred, but I want the first 10. In the above example, I'm expecting $myVar to be a decimal, but it turns out to be just an integer. I tried setting $myVar = 0.0000 before the for loop, I tried $myVar += $oldArray[$k] + 0.0000, etc but nothing seems to work. What am I doing wrong? How do I explicitly set $myVar to be a decimal?
Given that this seems impossible to reproduce, to me it sounds like a problem with your PHP environment itself. Check php.ini for a setting called "precision", and make sure it's set to the default of 14 significant figures. I can't imagine why this would be changed, but it would definitely have an impact.
You can try using [array\_sum()](https://www.php.net/manual/en/function.array-sum.php) instead and use (float) to cast the values. Additionally I would make sure that the values in the array are in the correct format (1.45 and not 1,45). HTH. **Update** Btw. you can use "is\_float()" to check every parameter in the array.
PHP - Summing an array of decimal values
[ "", "php", "floating-point", "decimal", "sum", "" ]
I know how to deploy an applet using `applet`, `object`, `embed` tags and `JavaScript`, but I'm after the best approach (in terms of end user experience). Sun suggests using [the applet tag](http://java.sun.com/javase/6/docs/technotes/guides/plugin/developer_guide/using_tags.html#applet), and a [mixed embed / object tag](http://java.sun.com/javase/6/docs/technotes/guides/plugin/developer_guide/using_tags.html#mixed) on the same page. What I am considering is the following: 1. Cross-browser support. 2. Fallback to download page if incorrect Java version is found (eg pre 1.5). 3. Loading page for both Java VM start period and while the Jar is downloaded (ideally a custom splash screen with a progress bar). Questions have been asked before: [how to deploy](https://stackoverflow.com/questions/985754/how-to-deploy-a-java-applet-for-todays-browsers-applet-embed-object), [check for 1.6](https://stackoverflow.com/questions/719712/how-can-i-check-if-i-have-that-java-6-plugin-2-for-applets-installed), and [Plugin framework](https://stackoverflow.com/questions/383510/is-there-any-plugin-framework-for-java-applets). None of these fully answer my question. I am also not considering web start or Java FX. My current solution is to include an additional small test applet compiled for Java 1.1. If Java pre-1.5 is found it redirects the page to the failure page. If no Java is found the page asks the user to visit java.com. This works acceptably, but is poor because it requires an additional applet and doesn't show anything while the VM is starting.
See [PulpCore's solution](http://code.google.com/p/pulpcore/wiki/Deployment) (license: [BSD](http://www.opensource.org/licenses/bsd-license.php)). An example: [the Milpa game](http://www.pulpgames.net/milpa/)... now, that's Rolls-Royce applet deployment if I ever saw it. And -- absolutely agreed, Sun's Deployment Toolkit sorely needs to handle disabled Java -- it seems to ignore that entirely, currently.
After much struggling with old and outdated information all over the web it seems like there's actually a really easy way to deploy applets - just let Sun write the correct tags for you! ``` <script src="http://java.com/js/deployJava.js"></script> <script> var attributes = { code:'java2d.Java2DemoApplet.class', archive:'Java2Demo.jar', width:710, height:540 }; var parameters = { fontSize:16 }; var version = '1.6' ; // whichever minimum version you want to target, null works also deployJava.runApplet(attributes, parameters, version); </script> ``` Worked like a charm, cross-browser, for me, with auto redirection to download page if java's not installed. More info here: <http://java.sun.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html#deplToolkit>
What is the Rolls-Royce way to deploy a Java applet?
[ "", "java", "applet", "cross-browser", "" ]
I am populating a DataGridView control on a Windows Form (C# 2.0 not WPF). My goal is to display a grid that neatly fills all available width with cells - i.e. no unused (dark grey) areas down the right and sizes each column appropriately according to the data it contains, **but** also allows the user to resize any of the columns to their liking. I am attempting to achieve this by setting the AutoSizeMode of each column to be **DataGridViewAutoSizeColumnMode.AllCells** except for one of the columns which I set to **DataGridViewAutoSizeColumnMode.Fill** in order to ensure the entire area of the grid is neatly filled with data. (I don't mind that when the user attempt to resize this column it springs back to a size that ensures the horizontal space is always used.) However, as I mentioned, once loaded I would like to allow the user to resize the columns to suit their own requirements - in setting these AutoSizeMode values for each column it appears the user is then unable to then resize those columns. I've tried not setting the AutoSizeMode of all the columns which does allow resizing BUT doesn't set the initial size according to the data the cells contain. The same result occurs when changing the grid's AutoSizeMode back to "Not Set" after loading the data. Is there a setting I'm missing here which allows automatic setting of default column widths AND user resizing or is there another technique I must use when populating the DataGridView control?
This trick works for me: ``` grd.DataSource = DT; // Set your desired AutoSize Mode: grd.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; grd.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; grd.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; // Now that DataGridView has calculated it's Widths; we can now store each column Width values. for (int i = 0; i <= grd.Columns.Count - 1; i++) { // Store Auto Sized Widths: int colw = grd.Columns[i].Width; // Remove AutoSizing: grd.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; // Set Width to calculated AutoSize value: grd.Columns[i].Width = colw; } ``` **In the Code above:** You set the Columns `AutoSize` Property to whatever `AutoSizeMode` you need. Then (Column by Column) you store each column Width value (from `AutoSize` value); Disable the `AutoSize` Property and finally, set the Column Width to the Width value you previously stored.
Maybe you could call ``` dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.Fill); ``` After setting datasource. It will set the width and allow resize. More on MSDN [DataGridView.AutoResizeColumns Method (DataGridViewAutoSizeColumnsMode)](http://msdn.microsoft.com/en-us/library/ms158594.aspx).
How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?
[ "", "c#", "winforms", "datagridview", "" ]
I have a custom jQuery script that works fine in all bowsers but one (Explorer 6, 7, 8?). The purpose of the code is to allow a user to add multiple form fields to their form (if the user want more than one phone number or more than one web address). It is written so that any "A" tag with a class containing "add" is bound to the jQuery function. The error I am getting is as follows: ``` /////////////////////////////// Line: 240 Char: 5 Error: 'this.id.3' is null or not an object Code: 0 /////////////////////////////// ``` HTML of form: (please note that I am aware that the form tags are not here, this is a small portion of a larger form. ``` <ul> <li> <ul> <li class="website"> <input id="website1_input" name="website[1][input]" type="text" value="www.test.org"/> <input type="checkbox" id="website1_delete" name="website[1][delete]" class="element radio" value="1" /> <label for="website1_delete">Delete</label> </li> </ul> <a href="#" id="addWebsite">add another website</a> </li> </ul> ``` And now the jQuery: There should be on a page a ul containing at least one li. All the lis should have a certain class like "phone" or "address" After the /ul There should be a link with a matching id, like "addPhone" or "addAddress". The href attribute should be "#". ``` function makeAddable(theClass) { $('#add' + theClass[0].toUpperCase() + theClass.substr(1)).click(function() { var numItems = $('.' + theClass).length; var newItem = $('.' + theClass).eq(numItems - 1).clone(); newItem.find('input[type=text]').val(''); numItems++; // number in the new IDs // keep ids unique, linked to label[for], and update names // id & for look like: phone1_type, phone1_ext, phone13_p1, etc. // names look like: phone[1][type], phone[1][ext], phone[13][p1], etc. newItem.find('[id^=' + theClass + ']').each(function(i) { var underscoreIndex = this.id.indexOf('_'); var idNum = this.id.substring(theClass.length, underscoreIndex); this.id = this.id.replace(idNum, numItems); }); newItem.find('[for^=' + theClass + ']').each(function(i) { var jqthis = $(this); var forAttr = jqthis.attr('for'); var underscoreIndex = forAttr.indexOf('_'); var idNum = forAttr.substring(theClass.length, underscoreIndex); forAttr = forAttr.replace(idNum, numItems); jqthis.attr('for', forAttr); }); newItem.find('[name^=' + theClass + ']').each(function(i) { var jqthis = $(this); var nameAttr = jqthis.attr('name'); var bracketIndex = nameAttr.indexOf(']'); var idNum = nameAttr.substring(theClass.length + 1, bracketIndex); nameAttr = nameAttr.replace(idNum, numItems); jqthis.attr('name', nameAttr); }); $(this).prev('ul').append(newItem); return false; }); } // Automatically enable all <a href="#" id="addSomething"> links $(function() { $('a[href=#][id^=add]').each(function(i) { makeAddable( this.id[3].toLowerCase() + this.id.substr(4) ); }); }); ```
``` this.id.charAt(3).toLowerCase() ```
Change this... ``` this.id[3] ``` To this... ``` this.id.substr(3, 1); ```
jQuery error, only with Explorer
[ "", "javascript", "jquery", "" ]