Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have solution that builds without errors or warnings. I created a class diagram in VS 2008 that shows one of my classes. I then right clicked on the class and choose create instance, and the it's parameter less constructor. I provide name for the new instance and then click OK. It then just shows an "Object Test Bench" error "Create Instance Failed", and in the details in only shows "0x80004005". Anyone have any idea what is going on? **Update** I figured it out. The project is a plugin for another program so if I go to the debug tab of the project settings the "Start Action" is set to run that program. When I changed that to "Start Project" and ensured the "Enable the Visual Studio hosting process" was check it worked". **Update 2** Ok just kidding, still doesn't work. Now I don't get the error for the first object, but the Object Test bench window never opens. At that point if I try to create any other instance by right clicking on any class in the class diagram the constructor method for any class is checked on the menu and it doesn't do anything if I click it. If I close visual studio I get another "Create Instance Failed" box but this time the details portion says "An expression evaluation is already in progress."
So are you saying that visual studio crashes, or your app crashes? If its visual studio then the normal advice applies: reinstall it. Having said that, try everything else you can think of first, because its a bit of a painful last resort. Also, look in your event viewer: Start->Run->eventvwr->Application and see if you can find this error, then post the details. By the sounds of it, its a visual studio error because errors in your c# app should throw exceptions rather than ugly hex error codes.
That is indeed a database error. One can reproduce the error in the NerdDinner example MVC app: 1. Generate a new Class Diagram 2. Drag the Dinner model class onto it 3. Then right-click >> create instance >> parameter-less constructor Dinner() I believe this error is happening because the class silently depends on things like a connection string in web.config and other things intrinsic to the the web host, which don't exist at design-time in the Class Diagram tool. Are you trying to use the Class Diagram tool on a Web Application project? It appears Microsoft is dead-ending the Object Test Bench due to lack of interest: <https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=423741>
0x80004005 Create instance failed
[ "", "c#", "visual-studio-2008", "" ]
``` $(document).ready(function () { $('#createGallery').hide(); $("#newGallery").click(function () { $("#createGallery").show('slow'); }); $("#gallerySelect > option").not("#newGallery").click(function () { $("#createGallery").hide('slow'); }); }); ``` I can't figure out why. Seems easy enough. my HTML is in HAML. But its easy to understand if you don't know what HAML is. My HAML reads : ``` #createGallery %span{ :style => "color:#1B75BC; font-size: 15px;" } new gallery %br %form{ :action => ""} %input{ :name => "tabname", :type => "text", :rows => "1", :cols => "30", :style => "height: 15px; width: 260px; margin-right: 40px;"} %span{ :style => "color:#1B75BC; font-size: 15px;" } gallery %form{ :action => ""} %select#gallerySelect{ :name => "Choose Gallery", :style => "width:260px" } %option{ :selected => "selected", :value => "QuickFact" } Choose Gallery %option{ :value => "QuickFact"} My Interior Design %option#newGallery{ :value => "QuickFact" } New Gallery %br ```
I don't believe that OPTION elements have click events. You'll want to attach the click handler to the SELECT element, and then check the option that was chosen.\ (disclaimer: air-coded) ``` $(document).ready(function(){ $('#createGallery').hide(); $("#gallerySelect").click(function () { if (this.options[this.selectedIndex].id == 'newGallery') { $("#createGallery").show('slow'); } else { $("#createGallery").hide('slow'); } }); }); ```
It would help to get the HTML for the current page, as well as to know a little more about the problem. * Which version of IE is having the problem? * Is it just the hiding / showing of of #createGAllery that isn't working, or is the click event not firing at all? * What does `alert($("#gallerySelect > option").not("#newGallery").length);` or `alert($("#gallerySelect > option").length);` return?
Simple jQuery Hide/Show does not work in IE
[ "", "javascript", "jquery", "internet-explorer", "cross-browser", "show-hide", "" ]
I have a WPF ListView with a column that has dates in it. I would like a way to custom sort the dates (by date value, rather than string value). Is there a way to do this? Right now I am using list.Items.SortDescriptions to sort using another column, but I would like to change this to sort on the date column instead. Thanks.
Have you tried that ? ``` ICollectionView view = CollectionViewSource.GetDefaultView(listView.ItemsSource); view.SortDescriptions.Add(new SortDescription("Date", ListSortDirection.Descending)); ``` EDIT: You can also have a look at [this attached property](http://www.thomaslevesque.com/2009/03/27/wpf-automatically-sort-a-gridview-when-a-column-header-is-clicked/)
If you're finding that the way WPF is sorting by default isn't what you intended, you can provide a custom sorter to the default view: ``` ListCollectionView view = (ListCollectionView)CollectionViewSource.GetDefaultView(listView.ItemsSource); view.CustomSort = new DateValueSorter(); listView.Items.Refresh(); ``` Where DateValueSorter is a class that implements the IComparer interface and sorts according to the date value and produces the ordering you are looking for.
Sort ListView by Date
[ "", "c#", "wpf", "xaml", "listview", "" ]
I have a textbox that should disallow entering any special characters. The user can enter : 1. A-Z 2. a-z 3. 0-9 4. Space How can I make the `KeyDown` event to do this?
``` private void _txtPath_KeyDown(object sender, KeyEventArgs e) { if ((e.Key < Key.A) || (e.Key > Key.Z)) e.Handled = true; } ```
Handling the KeyDown or KeyPress events is one way to do this, but programmers usually forget that a user can still copy-and-paste invalid text into the textbox. A somewhat better way is to handle the TextChanged event, and strip out any offending characters there. This is a bit more complicated, as you have to keep track of the caret position and re-set it to the appropriate spot after changing the box's Text property. Depending on your application's needs, I would just let the user type in whatever they want, and then flag the textbox (turn the text red or something) when the user tries to submit.
Allow only alphanumeric in textbox
[ "", "c#", ".net", "wpf", "regex", "alphanumeric", "" ]
I am migrating from Visual Studio 6 to Visual Studio 2008 and I have a function of a component I am using named `SetDefaultPrinter`. Unfortunately there is a windows library function now, [`SetDefaultPrinter`](http://msdn.microsoft.com/en-us/library/2ccwwdct%28VS.85%29.aspx), with the same name. And the macro associated with it is getting in the way of me using my function. This is my workaround I have to call my function: ``` #undef SetDefaultPrinter pNova->SetDefaultPrinter(); #ifdef UNICODE #define SetDefaultPrinter SetDefaultPrinterW #else #define SetDefaultPrinter SetDefaultPrinterA #endif // !UNICODE ``` Is there a less ugly way around this? And no, I do not have control over that external component to change the name of the function.
This is why C++ added namespaces; too bad the Windows definitions can't use them. In another source module, where you do NOT include windows.h or any other Windows include files, generate a stub function to call your clashing function. ``` void MySetDefaultPrinter(CNova * pNova) { pNova->SetDefaultPrinter(); } ```
You could use a wrapper around the external component. This is sometimes called the ["Adapter" pattern](http://en.wikipedia.org/wiki/Adapter_pattern). ``` // header file class NovaWrapper { Nova *_nova; public: void setDefaultPrinter(); }; // implementation file - this file does not include windows.h - you need to make sure it // does not have visibility of the "bad" SetDefaultPrinter macro void NovaWrapper::setDefaultPrinter() { _nova->SetDefaultPrinter(); } ``` Now, modify your client code to use NovaWrapper instead of the underlying instance.
Preproccessor ignore
[ "", "c++", "visual-studio", "winapi", "c-preprocessor", "" ]
Is there an easy way to convert all the columns of the current row of a SqlDataReader to a dictionary? ``` using (SqlDataReader opReader = command.ExecuteReader()) { // Convert the current row to a dictionary } ``` Thanks
You can use LINQ: ``` return Enumerable.Range(0, reader.FieldCount) .ToDictionary(reader.GetName, reader.GetValue); ```
Easier than this?: ``` // Need to read the row in, usually in a while ( opReader.Read ) {} loop... opReader.Read(); // Convert current row into a dictionary Dictionary<string, object> dict = new Dictionary<string, object>(); for( int lp = 0 ; lp < opReader.FieldCount ; lp++ ) { dict.Add(opReader.GetName(lp), opReader.GetValue(lp)); } ``` I'm still not sure why you would need this particular transformation from one type of collection to another.
SqlDataReader - How to convert the current row to a dictionary
[ "", "c#", "sql-server", "linq", "sqldatareader", "" ]
> **Possible Duplicate:** > [error using CArray](https://stackoverflow.com/questions/864864/error-using-carray) Duplicate : [error using CArray](https://stackoverflow.com/questions/864864/error-using-carray) --- so, i am trying to use CArray like this : ``` CArray<CPerson,CPerson&> allPersons; int i=0; for(int i=0;i<10;i++) { allPersons.SetAtGrow(i,CPerson(i)); i++; } ``` but when compiling my program, i get this error : ``` "error C2248: 'CObject::CObject' : cannot access private member declared in class 'CObject' c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtempl.h" ``` I don't even understand where this is coming from. HELP !
Write a constructor for your class (CPerson) and make it public. it should solve the problem.
The problem is that you're constructing a CObject on the stack. Somewhere in your program you're attempting to pass a reference to a CArray object but you accidentally left out the "&" in the function prototype. For example: ``` void DoFoo(CArray cArr) { // Do something to cArr... } ``` ^^^ The code above will cause the error you're having. ``` void DoFoo(CArray & cArr) { // Do something to cArr... } ``` ^^^ The code above will not cause the problem.
"error C2248: 'CObject::CObject' : cannot access private member declared in class 'CObject'
[ "", "c++", "mfc", "" ]
COM objects usually have deterministic destruction: they are freed when the last reference is released. How is this handled in C# - COM Interop? The classes don't implement `IDisposable`, so I see no way to trigger an explicit IUnknown::Release. A casual test shows that unreferenced COM objects get collected lazily (i.e. the garbage collector is triggering the release). What should I do for OCM objects that need to be released aggresively? (e.g. holding large or shared critical ressources)? Original problem: We have a C# application heavily using a COM library, and it is leaking like mad. It seems that the problems is "between" the C++ and the C# code (we have access to both), but we can't nail it down.
You can manipulate COM interop references using the System.Runtime.InteropServices.Marshal class. Specifically you may want to have a look at [Marshal.ReleaseComObject](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.releasecomobject.aspx).
We've suffered from this quite a lot. It's best not to try to load too many interop references into the .Net runtime. Also, you can use the `Marshal.ReleaseComObject` API if you need to release something right away. Another good method is to refactor your client code to use typesafe wrappers around the interop code - if you have a known reference in your code to each and every interop RCW, this increases the chance that the interop reference will be GCed in a timely fashion. The main problem this seeks to avoid is the one of "too many dots": ``` foo.bar.quux.xyzzy.groo(); // where foo, bar, quux and xyzzy are all COM references ``` Each of the objects between dots in the above code is effectively leaked (probably not really in the long run) since we have an implicit reference to the instance. You would need to create named references to each of the instances in order to have a good chance to clean them up: ``` Foo foo; Bar bar=foo.bar; Quux quux=bar.quux; Xyzzy xyzzy=quux.xyzzy; xyzzy.groo(); ``` Now possibly use the runtime to release the reference: ``` ReleaseComObject(xyzzy); // etc... ```
C# + COM Interop, deterministic release
[ "", "c#", "com", "interop", "" ]
I'm using C# in ASP.NET version 2. I'm trying to open an image file, read (and change) the XMP header, and close it back up again. I can't upgrade ASP, so WIC is out, and I just can't figure out how to get this working. Here's what I have so far: ``` Bitmap bmp = new Bitmap(Server.MapPath(imageFile)); MemoryStream ms = new MemoryStream(); StreamReader sr = new StreamReader(Server.MapPath(imageFile)); *[stuff with find and replace here]* byte[] data = ToByteArray(sr.ReadToEnd()); ms = new MemoryStream(data); originalImage = System.Drawing.Image.FromStream(ms); ``` Any suggestions?
How about this kinda thing? ``` byte[] data = File.ReadAllBytes(path); ... find & replace bit here ... File.WriteAllBytes(path, data); ``` Also, i really recommend against using System.Bitmap in an asp.net process, as it leaks memory and will crash/randomly fail every now and again (even MS admit this) *Here's the bit from MS about why System.Drawing.Bitmap isn't stable:* <http://msdn.microsoft.com/en-us/library/system.drawing.aspx> "Caution: Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions."
[Part 1 of the XMP spec 2012, page 10](http://www.adobe.com/devnet/xmp.html) specifically talks about how to edit a file in place without needing to understand the surrounding format (although they do suggest this as a last resort). The embedded XMP packet looks like this: ``` <?xpacket begin="■" id="W5M0MpCehiHzreSzNTczkc9d"?> ... the serialized XMP as described above: ... <x:xmpmeta xmlns:x="adobe:ns:meta/"> <rdf:RDF xmlns:rdf= ...> ... </rdf:RDF> </x:xmpmeta> ... XML whitespace as padding ... <?xpacket end="w"?> ``` > In this example, ‘■’ represents the > Unicode “zero width non-breaking space > character” (U+FEFF) used as a > byte-order marker. The (XMP Spec 2010, Part 3, Page 12) also gives specific byte patterns (UTF-8, UTF16, big/little endian) to look for when scanning the bytes. This would complement Chris' answer about reading the file in as a giant byte stream.
Modifying XMP data with C#
[ "", "c#", "asp.net", "image-processing", "xmp", "" ]
I wish to allow users to be able to view records from my database by following a URL. I am guessing its not a good idea to have this sort of URL where the identifier of the record to be viewed is the record auto increment ID! ``` http://www.example.com/$db_record_id ``` The above is giving info away unnecessarily. Is this really true? Wouldn't creating my own ID for each row pose the same problem? Is there a better way to solve my problem. Environment: LAMP (PHP) Thanks all
If I were you, I'd use an Integer Primary Key (auto ident) on your table and also add a GUID with a unique constraint & index on it, defaulted to `UUID()` Then rig your page up to take a GUID on the URL and use that to search your table.
You are giving out two pieces of info: * easily predictable url's of records * easy to find out how many records are in the set in total Are these things a problem for your application, then use something else You could use GUID's for the Db key, but that could have potential performance impacts in large datasets.
Bad idea to have two unique IDs in database table?
[ "", "php", "mysql", "" ]
How do I make a template specialization that takes 2 parameters versus the normal 1? I was building a pointer class and now I thought about extending to make an array but if I try something like this: ``` template<class T,int s> class pointer{}; template<class T> class pointer{}; class mama{}; int main(){ pointer<mama> m; } ``` It gives me an error. Template... redeclared with 1 parameter. I need it specialized because `pointer<mama,10>` has size() and operator[] while `pointer<mama>` doesn't, it has operator-> and \*.
You could make a general template for the array case: ``` template <class TElem, int size = 0> class pointer { // stuff to represent an array pointer }; ``` Then a partial specialization: ``` template <class TElem> class pointer<TElem, 0> { // completely different stuff for a non-array pointer }; ``` By defining a specialized version for the case where size=0, you can actually give that a totally different implementation, but with the same name. However, it might be clearer just to give it a different name.
You have class template redeclaration in your code which will lead to a compile-time error. You can have default template arguments and template template parameters. ``` template<class T,int s=10> class pointer{}; class mama{}; int main(){ pointer<mama> m; } ``` > I need it specialized because pointer has size() and operator[] while pointer doesn't, it has operator-> and \*. It looks as if you need a different design for your class. I am not sure if template specialization is the way to go. From the looks of your problem, you really should be thinking of specializing based on traits.
Same class with 2 or 1 template parameter
[ "", "c++", "templates", "specialization", "" ]
I'm trying to implement something like Rails dynamic-finders in Python (for webapp/GAE). The dynamic finders work like this: * Your Person has some fields: name, age and email. * Suppose you want to find all the users whose name is "Robot". The Person class has a method called "find\_by\_name" that receives the name and returns the result of the query: ``` @classmethod def find_by_name(cls, name): return Person.gql("WHERE name = :1", name).get() ``` Instead of having to write a method like that for each attribute, I'd like to have something like Ruby's method\_missing that allows me to do it. So far I've seen these 2 blog posts: <http://blog.iffy.us/?p=43> and <http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm> but I'd like to hear what's the "most appropiate" way of doing it.
There's really no need to use GQL here - it just complicates matters. Here's a simple implementation: ``` class FindableModel(db.Model): def __getattr__(self, name): if not name.startswith("find_by_"): raise AttributeError(name) field = name[len("find_by_"):] return lambda value: self.all().filter(field, value) ``` Note that it returns a Query object, which you can call .get(), .fetch() etc on; this is more versatile, but if you want you can of course make it just return a single entity.
You could use a 'find\_by' method and keywords, like Django does: ``` class Person (object): def find_by(self, *kw): qspec = ' AND '.join('%s=%s' % kv for kv in kw.items()) return self.gql('WHERE ' + qspec) person.find_by(name='Robot') person.find_by(name='Robot', age='2') ``` Down this road you may end up designing your own query syntax. Take a look at what Django does...
Dynamic Finders and Method Missing in Python
[ "", "python", "google-app-engine", "web-applications", "" ]
I have a html template that I want to retrieve from the resources file in a VS 2005 C# windows form application. I've created a folder called /html/ within the project, which has one file in it called template.html. I've added the file to my resources. I see its name just as template, and it's filepath is the fully qualified filename (c:/.../project/html/template.html). It is saved as TEXT rather than binary. I've tried many methods to extract this file, but each time I get a null returned. What am I missing? ``` Type t = GetType(); Assembly a = Assembly.GetAssembly(t); string file = "html.template.html"; // I've tried template and template.html string resourceName = String.Concat(t.Namespace, ".", file); Stream str = a.GetManifestResourceStream(resourceName); if (str == null) // It fails here - str is always null. { throw new FileLoadException("Unrecoverable error. Template could not be found"); } StreamReader sr = new StreamReader(str); htmlTemplate = sr.ReadToEnd(); ```
Have you tried looking in [Reflector](http://www.red-gate.com/products/reflector/) at your output assembly to verify that the resource name is actually what you expect it to be?
Reflector helped in finding out what the problem is, thank you. This is what I needed to have: ``` string template = Properties.Resources.template; ``` Couldn't be easier really. All the other stuff above was completely unnecessary.
How to retrieve a text file from the resource file in C# VS.2005
[ "", "c#", "visual-studio-2005", "resources", "embedded-resource", "" ]
I'm currently using Spring+Hibernate+MySQL for a project I'm working on. I realized that a have quite a few tables which never change. They are static, no insert or updates can ever occur on these tables, and so can be considered immutable. All accesses to these tables are via lazy loading (can be made eager) of entity collections and hql queries. I'm wondering for such a case what would be the best approach performance-wise for handling such a scenario. I have the basics in place, read only ehcache, query caching and the transactions set to read-only (does this do anything at all for Mysql?). What other things can I look at? Which ISOLATION modes, PROPAGATION modes are best? Should I be looking at other caching solutions? Or should I simply do away with all this and just load the data once into a series of hashmaps (this hopefully will be a last resort)? Another possible (far-fetched?) solution would be to have some in-memory/no-transaction database and have hibernate connect to it. Do such db engines exist? I'd appreciate any pointers, experience you guys have had!
Setup second level cahce's for all the entities ( check hibernate documentation for various configuration/mapping details for caching) ,configure query cache and mark them as immutable in the mapping / use read-only sessions, this would make hibernate not check for modifications for these entities when doing "transactional write-behind" and session flushing. This is a very common scenario and this is all you should have to do . You shouldn't have to deal with rolling out your own in memory hashmap cache ( second level caches like echache offer you several storage alternative), that what second level cache would do for you. Transaction less DB access doesn't offer you anything , performance wise , so I wouldn't worry about it and let hibernate deal with it .
I've dealt with exactly this sort of thing before, with enumeration tables of data that doesn't change, and frankly, the simplest thing to do was just to set the tables to eager loading and be done with it. The optimization that you may get from anything else is relatively small unless the tables are VERY large. Not to be dismissive, but your time is likely better spent optimizing another part of your system. That said, if your tables are particularly large, you might want to consider another method of dereferencing the data that they contain; if the table data is large and truly never changes, you may want to consider another way of populating the object tree other than using Hibernate; it may be beneficial to simply create a class for the enumeration and manage the association of that reference on your own (i.e., without Hibernate).
Best Spring/Hibernate configuration for never changing tables
[ "", "java", "mysql", "performance", "hibernate", "spring", "" ]
C#: What takes up more memory? A string or bytes? Let's say I have a line that reads "My Text", in which form would that line use up more memory, as a byte or a string?
The byte array. This will store your text as ASCII (1 byte per character) characters, whereas a .NET string uses Unicode which are larger. However remember that .NET strings are probably more useful and in a large application the difference probably won't make a huge difference. (note also that if you just use ASCII characters in your .NET string then the characters will still only be 1 byte each)
It depends on the character encoding of the byte array. You can convert any string into an array of bytes, but you have to choose the encoding; there is no single standard or correct encoding. What used to be called ASCII is no use outside of the English speaking world. In most encodings, "My Text" would be 7 bytes long. But throw in some European accented characters, or Japanese characters, and those (if they can be represented at all) may be more than one or two bytes each. In some encodings, with some text strings, the byte-array representation may be larger than the internal Unicode representation used by `System.String`.
C#: What takes up more memory? A string or bytearray?
[ "", "c#", ".net", "string", "arrays", "" ]
I'm trying to join some data together from 2 tables, but on several columns. here's an example: > **Source** table > > ID | Desc| AAAA| BBBB| > > **Table2** table > > ID | Text| ID1 | ID2 | ID3 | where ID1, ID2 and ID3 in **Table2** are ID's from the **Source** table I'd like to do a query which yields the results: ``` Table2.Text, Source.Desc(ID1), Source.AAAA(ID1), Source.Desc(ID2), Source.AAAA(ID2), Source.Desc(ID3), Source.AAAA(ID3) ``` I'd guess this would be a join, but i can't get the syntax right... or would I be better off with a Union?
If not all the Source tables are populated in the Table2, this will still give you partial results: ``` SELECT t.Desc, s1.Desc, s1.AAAAA, s2.Desc, s2.AAAAA, s3.Desc, s3.AAAA FROM Table2 t LEFT OUTER JOIN Source s1 ON t.ID1 = s1.ID LEFT OUTER JOIN Source s2 ON t.ID2 = s2.ID LEFT OUTER JOIN Source s3 ON t.ID3 = s2.ID WHERE t.ID=@YourIDHere ```
You could just use multiple joins, couldn't you? For example: ``` SELECT tb.Desc, s1.Desc, s1.AAAAA, s2.Desc, s2.AAAAA, s3.Desc, s3.AAAA FROM Table2 tb INNER JOIN Source s1 ON tb.ID1 = s1.ID INNER JOIN Source s2 ON tb.ID2 = s2.ID INNER JOIN Source s3 ON tb.ID3 = s2.ID ```
SQL query to join several columns
[ "", "sql", "syntax", "join", "union", "" ]
How can I create an InputStream object from a XML Document or Node object to be used in xstream? I need to replace the ??? with some meaningful code. Thanks. ``` Document doc = getDocument(); InputStream is = ???; MyObject obj = (MyObject) xstream.fromXML(is); ```
``` ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Source xmlSource = new DOMSource(doc); Result outputTarget = new StreamResult(outputStream); TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget); InputStream is = new ByteArrayInputStream(outputStream.toByteArray()); ```
If you are using Java without any Third Party Libraries, you can create `InputStream` using below code: ``` /* * Convert a w3c dom node to a InputStream */ private InputStream nodeToInputStream(Node node) throws TransformerException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Result outputTarget = new StreamResult(outputStream); Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); t.transform(new DOMSource(node), outputTarget); return new ByteArrayInputStream(outputStream.toByteArray()); } ```
how to create an InputStream from a Document or Node
[ "", "java", "xml", "xstream", "" ]
My purpose is to chose between CruiseControl and Hudson as continuous integration tool for java desktop application. I have seen lots of reading comparing Hudson and CruiseControl. In terms of features and ease of use, Hudson seems the best. But in terms of robustness, reliability with heavy configuration and finally in the long term, is this still true ?
My vote goes to Hudson. * **robustness**: I have never seen Hudson crash, although minor bugs did surface between releases but were squashed impressively fast. Also, it's being used by [Netbeans](http://deadlock.netbeans.org/hudson/), [JBoss](http://hudson.jboss.org/hudson/), [Eclipse](https://build.eclipse.org/hudson/), [Apache](http://hudson.zones.apache.org/hudson/) - I'd say it's pretty robust to handle those workloads; * **reliability with heavy configuration**: I'm not sure what you mean here. It is extremely configurable; * **in the long term**: there is a strong community behind Hudson, [the lead committer quotes 120 developers contributing to the codebase](http://weblogs.java.net/blog/kohsuke/archive/2009/04/hudson_hits_130.html), I'd say go for Hudson and never look back.
We were using CruiseControl to build our libraries and applications. We were using it for C++ and Python development, not Java. Recently we switched to Hudson with very good results. The main features we liked were: * Stop a process * Use slaves, that is, in one place we can manage the build of multiple platforms * Easy plugins download, installation and usage.
Choosing between Hudson and CruiseControl for the long term
[ "", "java", "continuous-integration", "hudson", "cruisecontrol", "" ]
I am trying to limit traffic to my website so that people trying to screenscrape mass amounts of data will be blocked after a while. I am supposed to do this based on the IPs of incoming requests. I believe I have the IP-limiting functionality written but, I'm stumped on how I can test it. I need to be able to change my IP address many times, to simulate valid traffic. I also need to test >20 different IPs, so a proxy solution for each one will not work for me. I am testing the code on my local machine (running Ubuntu) so I can change my server settings (Apache) if I need to for this test. I'm behind a corporate network so I cannot change MAC address/ARP settings to be "re-assigned" a new IP. I was hoping for some sort of localhost IP-changing type thing, so I could take advantage of the fact that the server and client were the same machine. Also, I was trying to avoid changing the code before it is rolled out to production servers, but that may be the best way to do it. How can I set this up?
Well, what you could do is instead of actually checking the IP do something like this: ``` $ip = '1337.1337.1337.1337'; ``` Instead of: ``` $ip = $_SERVER['REMOTE_ADDR'] ``` And then go on to do your IP checking code. So then when you are done you could make your $ip variable code look like this: ``` //$ip = '1337.1337.1337.1337'; $ip = $_SERVER['REMOTE_ADDR'] ``` So you can easily turn on and off the "debug switch" EDIT: Or even make the IP dynamic: ``` $ips = Array('192.168.1.220', '120.843.592.86', '256.865.463.563'); $ip = $ips[rand(1,count($ips)-1)]; ```
You can easily do that by running the following command on linux: ifconfig eth0:0 127.0.0.2 ifconfig eth0:1 127.0.0.3 etc... (creating fake local interfaces) You may have to configure apache to listen on those ips if you're not listening on 0.0.0.0 (all interfaces), then you can directly access those IPs. If you want to use other ips, you can easily do that too, but remember to remove them once your tests are done. This will only work from your local machine, to your local machine.
IP address spoofing/changing for testing on local machine
[ "", "php", "http", "ip", "" ]
I'm handling the `dblclick` event on a span in my web app. A side effect of a double click is that it selects text on the page. How can I prevent this selection from happening?
``` function clearSelection() { if(document.selection && document.selection.empty) { document.selection.empty(); } else if(window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); } } ``` You can also apply these styles to the span for all non-IE browsers and IE10: ``` span.no_selection { user-select: none; /* standard syntax */ -webkit-user-select: none; /* webkit (safari, chrome) browsers */ -moz-user-select: none; /* mozilla browsers */ -khtml-user-select: none; /* webkit (konqueror) browsers */ -ms-user-select: none; /* IE10+ */ } ```
To prevent text selection ONLY after a double click: You could use `MouseEvent#detail` property. For `mousedown` or `mouseup` events, it is 1 plus the current click count. ``` document.addEventListener('mousedown', function(event) { if (event.detail > 1) { event.preventDefault(); // of course, you still do not know what you prevent here... // You could also check event.ctrlKey/event.shiftKey/event.altKey // to not prevent something useful. } }, false); ``` ``` Some dummy text ``` See <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail>
Prevent text selection after double click
[ "", "javascript", "selection-object", "" ]
I'm getting an image in a byte array format from the controller, How can I display this in the view? in the simplest way.
Create a controller for displaying images with a Show action that takes the id of the image to display from the database. The action should return a FileResult that contains the image data with the appropriate content type. ``` public class ImageController : Controller { public ActionResult Show( int id ) { var imageData = ...get bytes from database... return File( imageData, "image/jpg" ); } } ``` In your view, construct the image and use the image id to construct a path for the image using the controller and action. ``` <img src='<%= Url.Action( "show", "image", new { id = ViewData["imageID"] } ) %>' /> ```
The accepted answer of using this: ``` <img src='<%= Url.Action( "show", "image", new { id = ViewData["imageID"] } ) %>' ``` is fine, but outdated for mvc 4. The updated syntax should now read: ``` <img src='@Url.Action( "show", "image", new { id = ViewData["imageID"] })' /> ``` Also, I find that when I need this functionality I'm already passing other data to the view so it's nice to use the Model instead of the ViewData. ``` public class MyModel { public string SomeData {get;set;} public int FileId {get; set;} } ``` From your controller: ``` public ActionResult Index() { MyEntity entity = fetchEntity(); MyModel model = new MyModel { SomeData = entity.Data, FileId = entity.SomeFile.ID }; return View(model); } ``` Finally from your view: ``` <img src='@Url.Action("show", "image", new { id = Model.FileId })' /> ``` The "Show" method on the controller for the accepted answer will work but I would change the hardcoded "image/jpg" to use File.ContentType - you can store this along with the byte[] so you don't need to guess if users are uploading their own images.
Display image from database in asp mvc
[ "", "c#", "asp.net-mvc", "" ]
If you schedule a SQL Server job to run every X number of minutes, and it does not finish the previous call before the # of minutes is up, will it skip the run since it is already running, or will it run two instances of the job doing the same steps?
The SQL Server agent checks whether the job is already running before starting a new iteration. If you have long running job and its schedule comes up, it would be skipped until the next interval. You can try this for yourself. If you try to start a job that's already running, you will get an error to that effect.
I'm pretty sure it will skip it if it is running.
Will a SQL Server Job skip a scheduled run if it is already running?
[ "", "sql", "sql-server", "scheduled-tasks", "sql-server-agent", "" ]
I have a table that exists in an Oracle database, but doesn't show on my list of tables in the tool SQL Developer. However, if I go to SQL\*Plus, and do a ``` select table_name from user_tables; ``` I get the table listed. If I type ``` desc snp_clearinghouse; ``` it shows me the fields. I'd like to get the create statement, because I need to add a field. I can modify the table to add the field, but I still need the create statement to put into our source control. What pl/sql statement is used to get the create statement for a table?
From [Get table and index DDL the easy way](http://www.dba-oracle.com/oracle_tips_dbms_metadata.htm): ``` set heading off; set echo off; Set pages 999; set long 90000; spool ddl_list.sql select dbms_metadata.get_ddl('TABLE','DEPT','SCOTT') from dual; select dbms_metadata.get_ddl('INDEX','DEPT_IDX','SCOTT') from dual; spool off; ```
Same as above but generic script found here [gen\_create\_table\_script.sql](http://www.akadia.com/services/scripts/gen_create_table_script.sql) ``` -- ############################################################################################# -- -- %Purpose: Generate 'CREATE TABLE' Script for an existing Table in the database -- -- Use: SYSTEM, SYS or user having SELECT ANY TABLE system privilege -- -- ############################################################################################# -- set serveroutput on size 200000 set echo off set feedback off set verify off set showmode off -- ACCEPT l_user CHAR PROMPT 'Username: ' ACCEPT l_table CHAR PROMPT 'Tablename: ' -- DECLARE CURSOR TabCur IS SELECT table_name,owner,tablespace_name, initial_extent,next_extent, pct_used,pct_free,pct_increase,degree FROM sys.dba_tables WHERE owner=upper('&&l_user') AND table_name=UPPER('&&l_table'); -- CURSOR ColCur(TableName varchar2) IS SELECT column_name col1, DECODE (data_type, 'LONG', 'LONG ', 'LONG RAW', 'LONG RAW ', 'RAW', 'RAW ', 'DATE', 'DATE ', 'CHAR', 'CHAR' || '(' || data_length || ') ', 'VARCHAR2', 'VARCHAR2' || '(' || data_length || ') ', 'NUMBER', 'NUMBER' || DECODE (NVL(data_precision,0),0, ' ',' (' || data_precision || DECODE (NVL(data_scale, 0),0, ') ',',' || DATA_SCALE || ') '))) || DECODE (NULLABLE,'N', 'NOT NULL',' ') col2 FROM sys.dba_tab_columns WHERE table_name=TableName AND owner=UPPER('&&l_user') ORDER BY column_id; -- ColCount NUMBER(5); MaxCol NUMBER(5); FillSpace NUMBER(5); ColLen NUMBER(5); -- BEGIN MaxCol:=0; -- FOR TabRec in TabCur LOOP SELECT MAX(column_id) INTO MaxCol FROM sys.dba_tab_columns WHERE table_name=TabRec.table_name AND owner=TabRec.owner; -- dbms_output.put_line('CREATE TABLE '||TabRec.table_name); dbms_output.put_line('( '); -- ColCount:=0; FOR ColRec in ColCur(TabRec.table_name) LOOP ColLen:=length(ColRec.col1); FillSpace:=40 - ColLen; dbms_output.put(ColRec.col1); -- FOR i in 1..FillSpace LOOP dbms_output.put(' '); END LOOP; -- dbms_output.put(ColRec.col2); ColCount:=ColCount+1; -- IF (ColCount < MaxCol) THEN dbms_output.put_line(','); ELSE dbms_output.put_line(')'); END IF; END LOOP; -- dbms_output.put_line('TABLESPACE '||TabRec.tablespace_name); dbms_output.put_line('PCTFREE '||TabRec.pct_free); dbms_output.put_line('PCTUSED '||TabRec.pct_used); dbms_output.put_line('STORAGE ( '); dbms_output.put_line(' INITIAL '||TabRec.initial_extent); dbms_output.put_line(' NEXT '||TabRec.next_extent); dbms_output.put_line(' PCTINCREASE '||TabRec.pct_increase); dbms_output.put_line(' )'); dbms_output.put_line('PARALLEL '||TabRec.degree); dbms_output.put_line('/'); END LOOP; END; / ```
How to get Oracle create table statement in SQL*Plus
[ "", "sql", "oracle", "sqlplus", "" ]
Hopefully this is easy to explain, but I have a lookup transformation in one of my SSIS packages. I am using it to lookup the id for an emplouyee record in a dimension table. However my problem is that some of the source data has employee names in all capitals (ex: CHERRERA) and the comparison data im using is all lower case (ex: cherrera). The lookup is failing for the records that are not 100% case similar (ex: cherrera vs cherrera works fine - cherrera vs CHERRERA fails). Is there a way to make the lookup transformation ignore case on a string/varchar data type?
There isn't a way I believe to make the transformation be case-insensitive, however you could modify the SQL statement for your transformation to ensure that the source data matches the case of your comparison data by using the LOWER() string function.
Set the CacheType property of the lookup transformation to Partial or None. The lookup comparisons will now be done by SQL Server and not by the SSIS lookup component, and will no longer be case sensitive.
How can I get SSIS Lookup transformation to ignore alphabetical case?
[ "", "sql", "sql-server", "ssis", "lookup", "business-intelligence", "" ]
As the title asks. My understanding of a deque was that it allocated "blocks". I don't see how allocating more space invalidates iterators, and if anything, one would think that a deque's iterators would have more guarantees than a vector's, not less.
The C++ standard doesn't specify how deque is implemented. It isn't required to allocate new space by allocating a new chunk and chaining it on to the previous ones, all that's required is that insertion at each end be amortized constant time. So, while it's easy to see how to implement deque such that it gives the guarantee you want[\*], that's not the only way to do it. [\*] Iterators have a reference to an element, plus a reference to the block it's in so that they can continue forward/back off the ends of the block when they reach them. Plus I suppose a reference to the deque itself, so that `operator+` can be constant-time as expected for random-access iterators -- following a chain of links from block to block isn't good enough.
What's more interesting is that `push_back` and `push_front` will **not** invalidate any **references** to a deque's elements. Only iterators are to be assumed invalid. The standard, to my knowledge, doesn't state why. However if an iterator were implemented that was aware of its immediate neighbors - as a list is - that iterator would become invalid if it pointed to an element that was both at the edge of the deque and the edge of a block.
Why does push_back or push_front invalidate a deque's iterators?
[ "", "c++", "stl", "iterator", "deque", "" ]
I'm using django for a web-magazine with subscriber-content. when a user purchases a subscription, the site will create a validation key, and send it to the user email address. The validation key would be added to a list of "valid keys" until it is used. What is the best method for creating a simple yet unique key? Can someone suggest a standard python library for key-creation/validation/ect? This might be a very simple question, but I'm very new. ;)
As other posters mentioned, you are looking for a GUID, of which the most popular implemntation UUID (see [here](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)) . Django extensions (see [here](http://code.google.com/p/django-command-extensions/)) offer a UUID field just for this purpose.
I'd recommend using a GUID. They are quickly becoming industry standard for this kind of thing. See how to create them here: [How to create a GUID/UUID in Python](https://stackoverflow.com/questions/534839/how-to-create-a-guid-in-python)
method for creating a unique validation key/number
[ "", "python", "django", "validation", "" ]
I could write my own algorithm to do it, but I feel there should be the equivalent to [ruby's humanize](http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html#M001339) in C#. I googled it but only found ways to humanize dates. Examples: * A way to turn "Lorem Lipsum Et" into "Lorem lipsum et" * A way to turn "Lorem lipsum et" into "Lorem Lipsum Et"
As discussed in the comments of [@miguel's answer](https://stackoverflow.com/questions/913090/how-to-capitalize-the-first-character-of-each-word-or-the-first-character-of-a-w/913102#913102), you can use [`TextInfo.ToTitleCase`](http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx) which has been available since .NET 1.1. Here is some code corresponding to your example: ``` string lipsum1 = "Lorem lipsum et"; // Creates a TextInfo based on the "en-US" culture. TextInfo textInfo = new CultureInfo("en-US",false).TextInfo; // Changes a string to titlecase. Console.WriteLine("\"{0}\" to titlecase: {1}", lipsum1, textInfo.ToTitleCase( lipsum1 )); // Will output: "Lorem lipsum et" to titlecase: Lorem Lipsum Et ``` It will ignore casing things that are all caps such as "LOREM LIPSUM ET" because it is taking care of cases if acronyms are in text so that "IEEE" (Institute of Electrical and Electronics Engineers) won't become "ieee" or "Ieee". However if you only want to capitalize the first character you can do the solution that is over [here](http://channel9.msdn.com/forums/TechOff/252814-Howto-Capitalize-first-char-of-words-in-a-string-NETC/)… or you could just split the string and capitalize the first one in the list: ``` string lipsum2 = "Lorem Lipsum Et"; string lipsum2lower = textInfo.ToLower(lipsum2); string[] lipsum2split = lipsum2lower.Split(' '); bool first = true; foreach (string s in lipsum2split) { if (first) { Console.Write("{0} ", textInfo.ToTitleCase(s)); first = false; } else { Console.Write("{0} ", s); } } // Will output: Lorem lipsum et ```
There is another elegant solution : Define the function `ToTitleCase` in an **static** class of your projet ``` using System.Globalization; public static string ToTitleCase(this string title) { return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(title.ToLower()); } ``` And then use it like a string extension anywhere on your project: ``` "have a good day !".ToTitleCase() // "Have A Good Day !" ```
How to capitalize the first character of each word, or the first character of a whole string, with C#?
[ "", "c#", "string", "humanize", "" ]
I have a table A ``` name num ------------ A 1 B 0 C 3 ``` B ``` num marks --------------- 1 90 3 40 ``` Query: ?? Result: ``` name marks -------------- A 90 C 40 B 90 B 40 ``` So number "0" in table A corresponds to all num column values. Is there a way this query can be written I know to get this ``` name marks -------------- A 90 C 40 ``` we can do this ``` select A.name, B.marks from A,B where A.num = B.num; ``` Edit: In this case 0 maps to num values 1 and 3
How about: ``` SELECT A.name, B.marks FROM A, B WHERE A.num = 0 OR A.num = B.num ```
``` select a.name, b.marks from a join b on a.num = b.num union all select a.name, b.marks from a, b where a.num = 0 ``` You *may* find this works better than a where clause with a "OR". Although, to be honest, you may not, there's no real way to get round having to scan the entirety of A and B one way or another. But it's often helpful to query planners for you to split up "OR" conditions into unions. EDIT: Just wanted to expand on this a bit. The reason it may be advantageous to do this is if the two parts of the unions benefit from being done in quite different ways. For instance, the second part could start by finding all rows in a with (num=0), whereas the first part is maybe more suitable for doing a full scan of a and index lookups/hash lookups into b, or merging indices on a(num) and b(num). I'll also say that this query arises from dubious design. You can't have a foreign key constraint from a(num) onto b(num), even though it would make sense to, because (a.num=0) would not match any rows in b. If you added rows in b with (num=0,marks=90) and (num=0,marks=40) then your query could be written easily with a simple inner join. While it's true this means maintaining two rows for each possible mark, that can be done using a trigger that detects inserts with a non-zero value for num, and does an additional insert with num=0. I suppose there are pros and cons to each approach. But I really really like putting fkey constraints in databases, and not having them in a case like this would make me nervous-- what happens if a record in a gets a num that isn't in b? what happens if a row in b gets deleted?
Writing SQL query where a value maps to all possible values
[ "", "sql", "" ]
Can any ony kindly explain that how we can take serial data as input from parallel port using c#. Or the serial communication through parallel port.
I really wouldn't transmit your data this way as you are heading for a world of pain. Far better to use a serial to USB IC such as the excellent ones made by [FTDI](http://www.ftdichip.com/). In simple terms these take your TTL serial data send it via USB. Thanks to the FTDI drivers the data appears as a virtual serial port which your program can read from in the usual way. Hope this helps. Ian
It is not clear from your question if you are looking for a software or hardware solution. AN external serial to paralell converter (hardware) provides the simpliest solution. If you are looking for a software only solution, you want to do "[bit banging](http://en.wikipedia.org/wiki/Bit-banging)". Unfortunately this requires precise timing, something which may be extremely difficult in managed code. This sort of program is typically implimented in a lower level language such as assembler or C where one has direct access to the hardware. Here is another [article](http://www.ganssle.com/articles/auart.htm) specifically addressing the use of the paralell port for serial communications.
Serial input through Parallel port
[ "", "c#", "" ]
I am working on a project that by default loads content via AJAX. I want it to check if the user (or SE bot) has JS disabled, and if so display the content statically via PHP. Is there a way to do this? I don't think noscript tag would work here, as the page would be empty to the non JS users or bots. Also doing a redirect to a different page it doesn't make sense to me, as the links to the original page will not be taken into consideration by search engines and will not be able to index that page as they will be redirected.
What about [unobtrusive JS](http://en.wikipedia.org/wiki/Unobtrusive_JavaScript)? You could make the plain html page the default and then use JS to hide or replace the clunky bits with your fancy AJAX controls. You end up with only one page per view which dynamically upgrades itself. URLs are safe to pass around too.
There isn't really a way to automatically change to a different page when the user DOESN'T have JavaScript. What I'd do is to display the non-JS version as default but hava a script on each page that redirects to the AJAX version and sets a cookie so that from then on all pages display the AJAX version right away. Oh, and better keep a noscript tag with a link to the non-AJAX version around in case anything goes wrong, such as someone who already has the cookie disabling JavaScript.
Write content from server if JavaScript is not enabled
[ "", "javascript", "" ]
I've used exceptions in Java and like the way it won't let you call a method unless you catch or throw the exceptions that it might throw. I'm looking for something similar in PHP. I realise PHP is more dynamic than Java, and doesn't even let you define the exceptions that it throws, but what is the closest I can get? We document our methods using PHP Doc, so something that triggered an E\_WARNING if you called a method without the correct try/catch block, or threw an exception without the correct @thows comment, would be perfect.
There's no way to do it in PHP itself. You will have to parse PHP and figure it out yourself. Try writing [phc plugin](http://www.phpcompiler.org/) for this.
I think you can simply reproduce this behavior in PHP using exception handlers and reflection. ``` class YourException extends Exception { public function __toString() { return __CLASS__; } } class MyObject { public function __construct(){} /** * @throws MyException */ public function myMethod() { return 'foo'; } } try { $o = new MyObject(); $o->myMethod(); } catch(YourException $e) { $method = new ReflectionMethod('MyObject', 'myMethod'); $method->getDocComment(); $throws = // Get the @throws comment (foreach, regexp, whatever); if($e === $throws) { // do something } } ``` [Setting your own exception handler.](http://php.net/set_exception_handler) [Grab and analyse the comments with Reflection mechanism (see getDocComment)](http://php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionclass)
Ensuring all exceptions are considered when using PHP
[ "", "php", "exception", "" ]
I have a large .NET C# application with a memory leak. Using ants memory profiler, I can see that there are multiple versions of same user controls in memory and the garbage collector is not collecting them. There is output caching on the web forms but no output caching on the actual user controls. Is there a reason why the user controls are not being disposed? How can I identify why and what is keeping them from being disposed of by garbage collector?
Basically an object will not get collected if someone holds at least one reference to it. Look and find who's holding the reference. ANTS Profiler or .NET Memory Profiler (SciTech) will give good insight.
There are a lot of reasons why a user control isn't garbage collected. Look at the code itself, are you instantiating objects (such as record sets) which implement IDisposable that you aren't actually disposing of?
why are user controls not collected by Gargabe Collector?
[ "", "c#", ".net", "memory", "memory-leaks", "garbage-collection", "" ]
Suppose a user of your website enters a date range. ``` 2009-1-1 to 2009-1-3 ``` You need to send this date to a server for some processing, but the server expects all dates and times to be in UTC. Now suppose the user is in Alaska. Since they are in a timezone quite different from UTC, the date range needs to be converted to something like this: ``` 2009-1-1T8:00:00 to 2009-1-4T7:59:59 ``` Using the JavaScript `Date` object, how would you convert the first "localized" date range into something the server will understand?
> The `toISOString()` method returns a string in simplified extended ISO > format ([ISO 8601](http://en.wikipedia.org/wiki/ISO_8601)), which is always 24 or 27 characters long > (`YYYY-MM-DDTHH:mm:ss.sssZ` or `±YYYYYY-MM-DDTHH:mm:ss.sssZ`, > respectively). The timezone is always zero UTC offset, as denoted by > the suffix "`Z`". Source: [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) The format you need is created with the `.toISOString()` method. For older browsers (ie8 and under), which don't natively support this method, the shim can be found [here](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toISOString): This will give you the ability to do what you need: ``` var isoDateString = new Date().toISOString(); console.log(isoDateString); ``` For Timezone work, [moment.js and moment.js timezone](http://momentjs.com/) are really invaluable tools...especially for navigating timezones between client and server javascript.
Simple and stupid ``` var date = new Date(); var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()); console.log(new Date(now_utc)); console.log(date.toISOString()); ```
How to convert a Date to UTC?
[ "", "javascript", "date", "utc", "" ]
I am working on an ASP.NET application using LinqToSQL. When the page loads I run a query and save the results into a variable... `var tasks = query expression`. I then save this into a session variable `Session["Tasks"] = tasks`... Is it possible to cast this session object back to its original var state, so I can run methods such as `Count()`, `Reverse()` and so on? Thanks
`var` is just short-hand for type inference... the real question here is: what is the underlying type? If it involves an *anonymous* type (i.e. new {...}, or a `List<>` there-of), then there is no **elegant** way (although it can be done in a hacky way). In short; don't use anonymous types in this scenario... Note that a query expression such as `IQueryable<T>` is not *data* - it is a *query* - to store the data (for a cache) you'd need to use `.ToList()` / `.ToArray()` etc. **Important**: you shouldn't store a **query expression** in session; at best (in-memory session provider) that will keep the data-context alive; at worst (database etc session provider) it won't work, as a data-context isn't serializable. Storing *results* from a query is fine; but otherwise, rebuild the query expression per-request. In which case, you might be able to use (for example): ``` var tasksQuery = from task in ctx.Tasks where task.IsActive orderby task.Created select task; // this is IQueryable<Task> Session["Tasts"] = tasksQuery.ToArray(); // this is Task[] ... var tasks = (Task[]) Session["Tasts"]; // this is Task[] ```
var is not a type, it just tells C# you figure out the type. ``` string s = "Hello world!"; ``` and ``` var s = "Hello world!"; ``` are equivalent and give back the same s. You are probably missing ``` using System.Linq ``` or some other that adds the extension methods you are looking for.
C# casting back to var type?
[ "", "c#", ".net", "asp.net", "linq", "" ]
What can you guys recommend to use with Java? Only requirement is it should be open source, or has not too expensive academic licence .
The VisualVM which comes with jdk6 has a basic profiler inside it. VisualVM is provided with the jdk, so if you have the jdk6 installed, you likely have it installed as well. <https://visualvm.github.io/>
you've got a list [here](http://java-source.net/open-source/profilers) (listing them below, in-case link gets broken) > * JMemProf > * JMP > * DrMem > * JTreeProfiler > * NetBeans Profiler > * JAMon API > * JBoss Profiler > * MessAdmin > * InfraRED > * TomcatProbe > * Java Interactive Profiler (JIP) > * Profiler4j > * Stopwatch > * JMeasurement > * DJProf > * TIJmp > * Allmon > * Appspy > * EurekaJ > * japex > * OKTECH Profiler > * Perf4j
Open Source Java Profilers
[ "", "java", "profiler", "" ]
How can I get all classes within a namespace in C#?
You will need to do it "backwards"; list all the types in an assembly and then checking the namespace of each type: ``` using System.Reflection; private Type[] GetTypesInNamespace(Assembly assembly, string nameSpace) { return assembly.GetTypes() .Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)) .ToArray(); } ``` Example of usage: ``` Type[] typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyNamespace"); for (int i = 0; i < typelist.Length; i++) { Console.WriteLine(typelist[i].Name); } ``` --- For anything before .Net 2.0 where `Assembly.GetExecutingAssembly()` is not available, you will need a small workaround to get the assembly: ``` Assembly myAssembly = typeof(<Namespace>.<someClass>).GetTypeInfo().Assembly; Type[] typelist = GetTypesInNamespace(myAssembly, "<Namespace>"); for (int i = 0; i < typelist.Length; i++) { Console.WriteLine(typelist[i].Name); } ```
You'll need to provide a little more information... Do you mean by using Reflection. You can iterate through an assemblies Manifest and get a list of types using ``` System.Reflection.Assembly myAssembly = Assembly.LoadFile(""); myAssembly.ManifestModule.FindTypes() ``` If it's just in Visual Studio, you can just get the list in the intellisense window, or by opening the Object Browser (CTRL+W, J)
How can I get all classes within a namespace?
[ "", "c#", ".net", "reflection", "namespaces", "" ]
Is there any good alternative to the html5-element canvas to paint shapes like hexagons using javascript, that works cross-browser (including the horrible IE6)? I have been using jQuery and jQuery maphighlight for this, but it doesn't give me enough possibilities to manipulate the shapes and colors after it's first rendered. Am I missing some features in jQuery maphighlight, or are there any other plugin for either jQuery or mootools, that can provide me with this painting capabilities?
You should take a look at RaphaelJS. It is a JavaScript, cross-browser wrapper library around Canvas, SVG, and VML (an IE-only vector markup language that predates SVG, used in IE6). Using RaphaelJS, you can generate a very wide range of vector graphics using JS that is compatible with a very broad range of browsers. <http://raphaeljs.com/> RaphaelJS is also very compatible with jQuery, and follows a lot of the same call-chaining that you see in jQuery. The two make a great pair.
There's also the famous canvas painter. <http://caimansys.com/painter/>
Painting shapes in Javascript
[ "", "javascript", "jquery", "jquery-plugins", "mootools", "raphael", "" ]
when using @transactional do i need to use jpatemplate/hibernatetemplate ?
No, you don't. Spring has a built-in transaction manager that can be used for simple transactions, e.g. if you don't need to track transactions across more than one DataSource. The configuration should be as simple as this: ``` <tx:annotation-driven transaction-manager="txManager"/> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> ``` Where the bean named "dataSource" is some DataSource bean configured elsewhere in your XML file. However if you're using JPA or Hibernate, it would be a good idea to use the JPATransactionManager or HibernateTransactionManager, respectively. If you really wanted to you could also use JTA, which is Sun's standard transaction implementation. I think the spring class is called JTATransactionManager. Using transaction managers other than Spring's out-of-the-box one (the one defined in the XML config above) will give you the ability to use transactions across multiple DataSources.
The answer depends on the what version of Hibernate you are using. With later versions the simple answer is no you don't need the templates. See here for a comprehensive discussion: <http://blog.springsource.com/2007/06/26/so-should-you-still-use-springs-hibernatetemplate-andor-jpatemplate/>
when using @transactional do i need to use jpatemplate/hibernatetemplate?
[ "", "java", "spring", "" ]
I have an aspx that has the following javascript function being ran during the onload event of the body. ``` <body onload="startClock();"> ``` However, I'm setting the aspx up to use a master page, so the body tag doesn't exist in the aspx anymore. How do I go about registering the startClock function to run when the page is hit and still have it use a masterpage?
If you don't want to explicitly assign window.onload or use a framework, consider: ``` <script type="text/javascript"> function startClock(){ //do onload work } if(window.addEventListener) { window.addEventListener('load',startClock,false); //W3C } else { window.attachEvent('onload',startClock); //IE } </script> ``` <http://www.quirksmode.org/js/events_advanced.html>
Insert this anywhere in the body of the page: ``` <script type="text/javascript"> window.onload = function(){ //do something here } </script> ```
Hook a javascript event to page load
[ "", "javascript", "master-pages", "asp.net", "onload-event", "" ]
I want to run this piece of code ``` Bitmap grayImage = (Bitmap)img.Clone(); for (int x = 0; x < arr.GetLength(0); x++) { for (int y = 0; y < arr.GetLength(1); y++) { int col = arr[x, y]; Color grau = Color.FromArgb(col, col, col); grayImage.SetPixel(x, y, grau); } } ``` if I run the code I get an exception in this line: grayImage.SetPixel(x, y, grau); Here are the Exception Details: System.Runtime.InteropServices.ExternalException wurde nicht behandelt. Message="A generic error occurred in GDI+." Source="System.Drawing" ErrorCode=-2147467259 StackTrace: at System.Drawing.Bitmap.SetPixel(Int32 x, Int32 y, Color color) at Metalldetektor.Bild.ArrToPic(Int32[,] arr, Image img) in D:\Documents\Visual Studio 2008\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Bild.cs:line 44 at Metalldetektor.Form1.button2\_Click(Object sender, EventArgs e) in D:\Documents\Visual Studio 2008\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 58 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at Metalldetektor.Program.Main() in D:\Documents\Visual Studio 2008\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Program.cs:line 19 at System.AppDomain.\_nExecuteAssembly(Assembly assembly, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: I don't know what to do so please help!
I had a similar problem in the past where my cloned bitmap had some artifacts. After researching this problem for a while, I stumbled upon [this thread](http://www.gamedev.net/community/forums/topic.asp?topic_id=501121) which helped. Try replacing your Clone() ``` Bitmap grayImage = (Bitmap)img.Clone(); ``` with this: ``` Bitmap grayImage = new Bitmap(img); ```
I don't know about the bug, but this might be a case for LockBits... I'll see if I can whip up an example. Here's a simplified example writing an array of data to an ARGB bitmap: ``` // fake data int[,] data = new int[100, 150]; int width = data.GetLength(0), height= data.GetLength(1); for (int x = 0; x < width; x++) for (int y = 0; y < height; y++) data[x, y] = x + y; // process it into a Bitmap Bitmap bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb); BitmapData bd = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); unsafe { byte* root = (byte*)bd.Scan0; for (int y = 0; y < height; y++) { byte* pixel = root; for (int x = 0; x < width; x++) { byte col = (byte)data[x, y]; pixel[0] = col; pixel[1] = col; pixel[2] = col; pixel[3] = 255; pixel += 4; } root += bd.Stride; } } bmp.UnlockBits(bd); bmp.Save("foo.bmp"); // or show on screen, etc ``` This approach should be a *lot* faster than `SetPixel`.
c# external Exception in GDI+
[ "", "c#", "image", "exception", "gdi+", "bitmap", "" ]
When I attach an HTML file to an email and then email it to my iphone, I can view the file perfectly. However, none of the javascript in the file seems to run - not even simple stuff like showing / hiding divs triggered by "onClick" events. Is there any way to make javascript run on attached files in the iphone mail application?
JavaScripts is supported in MobileSafari browser but not in the mail. I think that to run JavaScript in the way you want you'd have to open the website in the browser. Cannot think of any other way of doing it.
No. Like just about every e-mail client still in existence, JavaScript etc. will be blocked. Including JS code may actually prevent your e-mails from being delivered - `<script>` tags will likely raise a warning flag in most anti-spam filters.
iphone mail won't display javascript in attached html files?
[ "", "javascript", "iphone", "html", "email", "attachment", "" ]
My platform is windows vista 32, with visual c++ express 2008 . for example: if i have a file contains 4000 bytes, can i have 4 threads read from the file at same time? and each thread access a different section of the file. thread 1 read 0-999, thread 2 read 1000 - 2999, etc. please give a example in C language.
If you don't write to them, no need to take care of sync / race condition. Just open the file with shared reading as different handles and everything would work. (i.e., you must open the file in the thread's context instead of sharing same file handle). ``` #include <stdio.h> #include <windows.h> DWORD WINAPI mythread(LPVOID param) { int i = (int) param; BYTE buf[1000]; DWORD numread; HANDLE h = CreateFile("c:\\test.txt", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); SetFilePointer(h, i * 1000, NULL, FILE_BEGIN); ReadFile(h, buf, sizeof(buf), &numread, NULL); printf("buf[%d]: %02X %02X %02X\n", i+1, buf[0], buf[1], buf[2]); return 0; } int main() { int i; HANDLE h[4]; for (i = 0; i < 4; i++) h[i] = CreateThread(NULL, 0, mythread, (LPVOID)i, 0, NULL); // for (i = 0; i < 4; i++) WaitForSingleObject(h[i], INFINITE); WaitForMultipleObjects(4, h, TRUE, INFINITE); return 0; } ```
There's not even a big problem *writing* to the same file, in all honesty. By far the easiest way is to just memory-map the file. The OS will then give you a void\* where the file is mapped into memory. Cast that to a char[], and make sure that each thread uses non-overlapping subarrays. ``` void foo(char* begin, char*end) { /* .... */ } void* base_address = myOS_memory_map("example.binary"); myOS_start_thread(&foo, (char*)base_address, (char*)base_address + 1000); myOS_start_thread(&foo, (char*)base_address+1000, (char*)base_address + 2000); myOS_start_thread(&foo, (char*)base_address+2000, (char*)base_address + 3000); ```
Multiple threads reading from the same file
[ "", "c++", "c", "file-io", "" ]
How can I make a table sortable using javascript without loading data via AJAX? More specifically, I'm looking for a solution that gives me the following: * Works on a plain old HTML table * Makes columns sortable using a natural comparison * Is agnostic of server-side technology (should be portable regardless of whether the tables are being rendered by JSP, PHP, etc) * Implemented preferably as an extension to JQuery, which I'm already using in the specific project I'd like to immediately apply this to. I'm open to suggestions involving another javascript framework such as YUI, but it will need to play nice with JQuery. What I'm not looking for: * A solution which requires me to populate the data via an AJAX call. I'd like to apply this in a project that has a number of plain old HTML tables for things like search results that I'd like to quickly make sortable without rewriting any server-side code. * Paging. * Filtering. * The ability to specify arbitrary comparison logic. I'm purposefully omitting our technology stack for the specific project I'm working on for now, but will include it if people feel that it is absolutely necessary. Again, I'm most interested in solutions that don't involve anything on the server. There are a ton of projects written in all sorts of languages that could use a little love in this area. **Regarding the issue of similar, existing questions on Stack Overflow** I've done some poking around, and the closest question I can find to mine is [this one](https://stackoverflow.com/questions/192608/jquery-scrollable-sortable-filterable-table). My requirements are a little different, however, and so I decided to ask a new question.
The jquery plugin [tablesorter](http://tablesorter.com/docs/) works very nicely.
Updated link (note this is not <https://github.com/SortableJS/Sortable>): Try [sortable](https://github.com/hubspot/sortable).
How can I make an HTML table sortable with javascript without loading data via AJAX?
[ "", "javascript", "jquery", "html", "sorting", "html-table", "" ]
I have a class : Schedule. ``` public class Schedule { private int locationNum; private int cost; private String costReason; private Date weekOfChange; private Date dayOfChange; private String changeReason; // and all those getters and setters public Schedule(int locationNum, int cost, String costReason, Date weekOfChange, Date dayOfChange, String changeReason) throws ApplicationException { //change is all or nothing - all attributes are present or none if((weekOfChange!=null && dayOfChange!=null && changeReason!=null) || (weekOfChange==null && dayOfChange == null && changeReason == null)) { this.weekOfChange = weekOfChange; this.dayOfChange = dayOfChange; this.changeReason = changeReason; } else { throw new ApplicationException();} //similary another if block to ensure that if cost is specified //then there exists the corresponding reason code for it. } } ``` So far, I am liking my Schedule class. However, I am not done with the checks, I would have to do some other checks: * is the locationNum a valid store number in the database. * is changeReason text one of those 6 different changeReason codes in the database. * etc etc.... Typically, I would not write these in Schedule class, coz obviously, I cannot invoke DAOs from this class. So, I would have a business layer and some kind of validator class, accepting an object of type Schedule and performing a bunch of database validations in sequence and collecting errors for display / whatever. Now, here are my questions: 1. If you were to treat Schedule as a POJO and argue that an object is not responsible for validating itself - I would have to move all of the code in the constructor to the business layer's validator class. But, if I were to do this, isn't Schedule anemic? Is this what they call violation of Single Responsibility principle? 2. Lets presume I moved the code I have in my constructor to a business layer class so that all kinds of validations are now in my busines layer. Lets assume that someone changes dayOfChange to NULL in my datastore and now I am loading objects from my database. Now, with this kind of an object, my application can break, wouldn't it? coz I would have written code assuming that validation rules are met. I guess my question is getting confusing, but the point I am trying to make is that in this context I would rather have these checks done in constructor to ensure integrity of the data hidden by Schedule class. 3. How is it done usually? What is the best practice? Appreciate your involvement in this discussion.
If you really have "all those getters *and* setters" then you need to validate your class better than in the constructor. If the invariants of your class are such that all weekOfChange, dayOfChange and changeReason must be null or not all must be not null your setters are quickly going to put your class in an invalid state. Do you mean to have setters or do you mean your class to be immutable? Before worrying about were validation should go maybe do an analysis of your class. Look at all its valid states and invariants for given states. Then you will understand whether your class should be mutable or immutable. Where you have mutually dependant covariants (like weekOfChange, dayOfChannge and changeReason it makes sense to package them into there own class and use composition in the Schedule class. This will put the "rules" about these things fields in a single place and simplify the Schedule. The same with other collaborating fields (like cost and cost reason). Then Schedule is composed of to self validating classes. If both these are immutable and Schedule is immutable also you have your self a much easier domain. So, to answer your question: it is better that a class defines its states and invariants and exposes only the minimum to its collaborators where practical. The responsibility for the internal state of Schedule should rest with Schedule and with just a little more design it can do with relative ease. So you have ``` class Schedule { private Change change; private Cost cost; private Location location; public Schedule(Location location, Cost cost, Change change) { this.change = change; this.cost = cost; this.location = location; } } ``` And colloborators like ``` public class Change { private Date weekOfChange; //shoudln't these two fields be one, a date is a date after all?? private Date dayOfChange; //shoudln't these two fields be one?? private String changeReason; public Change(Date weekOfChange Date dayOfChange, String changeReason) { this.weekOfChange = weekOfChange; ...etc. } } ``` Though I would strongly advise you protect your classes invariants with defensive copying of any mutable values that are passed in by client code.
> If you were to treat Schedule as a > POJO and argue that an object is not > responsible for validating itself - I > would have to move all of the code in > the constructor to the business > layer's validator class. But, if I > were to do this, isn't Schedule > anemic? Is this what they call > violation of Single Responsibility > principle? [POJO](http://en.wikipedia.org/wiki/Plain_Old_Java_Object) only means that you don't have to derive from a particular class or use a byte code enhancer to get desired functionality like OR mapping. It does NOT mean that the objects should be anemic with no functionality. > Now, with this kind of an object, my > application can break, wouldn't it? > coz I would have written code assuming > that validation rules are met. I guess > my question is getting confusing, but > the point I am trying to make is that > in this context I would rather have > these checks done in constructor to > ensure integrity of the data hidden by > Schedule class. Who says you cannot call rules defined in a separate class from the constructor of your Schedule class? If it needs access to non-public fields, you could make them package-private and have the rules class in the same package - or pass them as parameters to the rule. > How is it done usually? What is the > best practice? Whether or not you move validation rules to separate classes should depend on your application's needs, not on misunderstood buzzwords. *Good* reasons to have separate rule classes would be: * The rules are so many and so complex that putting them all into the Schedule class would make it too big. * You do not always want to apply all the rules. * The rules can be reused to operate on different classes that are not necessarily in the same inheritance hierarchy (i.e. they work through an interface).
Business rules - where do they go in OOP?
[ "", "java", "validation", "oop", "business-logic", "" ]
I know how to reload a regular Python module within a regular Python interpreter session. This question documents how to do that pretty well: [How do I unload (reload) a Python module?](https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module) For some reason, I am having trouble doing that within Django's "manage.py shell" interpreter session. To recreate my issue, start the basic Django tutorial found here: [Writing your first Django app, part 1](http://docs.djangoproject.com/en/dev/intro/tutorial01/) After creating the "polls" application and "Poll" class, start up the interpreter via "manage.py shell" and import the "polls" app into it. ``` import polls.models as pm ``` Create a new "Poll" object: ``` p = pm.Poll() ``` All is well and good so far. Now go back to your source and add any arbitrary method or attribute. For example, I've added: ``` def x(self): return 2+2 ``` Now go back to the interpreter and "reload" the module: ``` reload(pm) ``` Now try to use your new method or attribute: ``` p1 = pm.Poll() p1.x() ``` You'll get this message: ``` 'Poll' object has no attribute 'x' ``` What gives? I've also tried rerunning the import command, importing the module using different syntax, deleting all references to any "Poll" objects or to the "Poll" class. I've also tried this with both the IPython interpreter and with the plain Python (v2.6) interpreter. Nothing seems to work. Using the same techniques with an arbitrary Python module in a regular interpreter session works perfectly. I just can't seem to get it to work in Django's "shell" session. By the way, if it makes any difference, I'm doing this on a Ubuntu 9.04 machine.
Well, I think I have to answer to this. The problem is that Django caches its models in a singleton (singleton like structure) called AppCache. Basically, to reload Django models you need to first reload and re-import all the model modules stored in the AppCache. Then you need to wipe out the AppCache. Here's the code for it: ``` import os from django.db.models.loading import AppCache cache = AppCache() curdir = os.getcwd() for app in cache.get_apps(): f = app.__file__ if f.startswith(curdir) and f.endswith('.pyc'): os.remove(f) __import__(app.__name__) reload(app) from django.utils.datastructures import SortedDict cache.app_store = SortedDict() cache.app_models = SortedDict() cache.app_errors = {} cache.handled = {} cache.loaded = False ``` I've put all of this in a separate file called reloadmodels.py in the root directory of my Django site. Using IPython I can reload everything by running: ``` %run ~/mysite/reloadmodels.py ```
**My solution on 2016 (in future it may be changed)** 1.Install django\_extension 2.Add next settings: ``` SHELL_PLUS = 'ipython' IPYTHON_ARGUMENTS = [ '--ext', 'autoreload', ] ``` 3.Run shell ``` ./manage.py shell_plus ``` ## **See results:** **model example** ``` class Notification(models.Model): ........ @classmethod def get_something(self): return 'I am programmer' ``` In shell ``` In [1]: Notification.get_something() Out[1]: 'I am programmer' ``` Made changes on model ``` @classmethod def get_something(self): return 'I am Python programmer' ``` In shell ``` # shell does not display changes In [2]: Notification.get_something() Out[2]: 'I am programmer' ``` In shell. This is a magic ``` # configure extension of ipython In [3]: %autoreload 2 ``` In shell ``` # try again - all worked In [4]: Notification.get_something() Out[4]: 'I am Python programmer' ``` Made changes again ``` @classmethod def get_something(self): return 'I am full-stack Python programmer' ``` In shell ``` # all worked again In [5]: Notification.get_something() Out[5]: 'I am full-stack Python programmer' ``` Drawback: 1. Need manually run code > %autoreload 2 since django\_extension 1.7 has not support for run arbitrary code. May be in future release it has this feature. Notes: 1. Django 1.10 2. Python 3.4 3. django\_extension 1.7.4 4. Based (primary) on <https://django-extensions.readthedocs.io/en/latest/shell_plus.html> and <http://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html> 5. Caution. It is may be produce an error, if you try change a code where used super().
How do you reload a Django model module using the interactive interpreter via "manage.py shell"?
[ "", "python", "django", "" ]
How can i bundle a stripped down JVM to run just my application? i would like to strip down the JVM so that i can include it in my application. I know that exe wrappers can do this but what i would like to know is how? so that i can script it and create bundles for multiple OS's not just Windows.
Even though it might be possible to strip down the JRE distribution from a technical perspective, please have a close look at the license agreement. For Java 6 it states: *[...] Sun grants you a non-exclusive, non-transferable, limited license without fees to reproduce and distribute the Software, provided that (i) you distribute the Software complete and unmodified and only bundled as part of, and for the sole purpose of running, your Programs [...]* {Supplemental License Terms, (B)} I'd read it like that: you're only allowed to distribute a **complete** (Sun) JRE 6 (or JDK 6).
You may considerably **[reduce the download size of java applications](http://www.excelsior-usa.com/java-download-size.html)** while maintaining compliance with the license.
bundling jvm with the application
[ "", "java", "jvm", "bundle", "" ]
I was seeing some strange behavior in a multi threading application which I wrote and which was not scaling well across multiple cores. The following code illustrates the behavior I am seeing. It appears the heap intensive operations do not scale across multiple cores rather they seem to slow down. ie using a single thread would be faster. ``` class Program { public static Data _threadOneData = new Data(); public static Data _threadTwoData = new Data(); public static Data _threadThreeData = new Data(); public static Data _threadFourData = new Data(); static void Main(string[] args) { // Do heap intensive tests var start = DateTime.Now; RunOneThread(WorkerUsingHeap); var finish = DateTime.Now; var timeLapse = finish - start; Console.WriteLine("One thread using heap: " + timeLapse); start = DateTime.Now; RunFourThreads(WorkerUsingHeap); finish = DateTime.Now; timeLapse = finish - start; Console.WriteLine("Four threads using heap: " + timeLapse); // Do stack intensive tests start = DateTime.Now; RunOneThread(WorkerUsingStack); finish = DateTime.Now; timeLapse = finish - start; Console.WriteLine("One thread using stack: " + timeLapse); start = DateTime.Now; RunFourThreads(WorkerUsingStack); finish = DateTime.Now; timeLapse = finish - start; Console.WriteLine("Four threads using stack: " + timeLapse); Console.ReadLine(); } public static void RunOneThread(ParameterizedThreadStart worker) { var threadOne = new Thread(worker); threadOne.Start(_threadOneData); threadOne.Join(); } public static void RunFourThreads(ParameterizedThreadStart worker) { var threadOne = new Thread(worker); threadOne.Start(_threadOneData); var threadTwo = new Thread(worker); threadTwo.Start(_threadTwoData); var threadThree = new Thread(worker); threadThree.Start(_threadThreeData); var threadFour = new Thread(worker); threadFour.Start(_threadFourData); threadOne.Join(); threadTwo.Join(); threadThree.Join(); threadFour.Join(); } static void WorkerUsingHeap(object state) { var data = state as Data; for (int count = 0; count < 100000000; count++) { var property = data.Property; data.Property = property + 1; } } static void WorkerUsingStack(object state) { var data = state as Data; double dataOnStack = data.Property; for (int count = 0; count < 100000000; count++) { dataOnStack++; } data.Property = dataOnStack; } public class Data { public double Property { get; set; } } } ``` This code was run on a Core 2 Quad (4 core system) with the following results: One thread using heap: 00:00:01.8125000 Four threads using heap: 00:00:17.7500000 One thread using stack: 00:00:00.3437500 Four threads using stack: 00:00:00.3750000 So using the heap with four threads did 4 times the work but took almost 10 times as long. This means it would be twice as fast in this case to use only one thread?????? Using the stack was much more as expected. I would like to know what is going on here. Can the heap only be written to from one thread at a time?
The answer is simple - run outside of Visual Studio... I just copied your entire program, and ran it on my quad core system. Inside VS (Release Build): ``` One thread using heap: 00:00:03.2206779 Four threads using heap: 00:00:23.1476850 One thread using stack: 00:00:00.3779622 Four threads using stack: 00:00:00.5219478 ``` Outside VS (Release Build): ``` One thread using heap: 00:00:00.3899610 Four threads using heap: 00:00:00.4689531 One thread using stack: 00:00:00.1359864 Four threads using stack: 00:00:00.1409859 ``` Note the difference. The extra time in the build outside VS is pretty much all due to the overhead of starting the threads. Your work in this case is too small to really test, and you're not using the high performance counters, so it's not a perfect test. Main rule of thumb - always do perf. testing outside VS, ie: use Ctrl+F5 instead of F5 to run.
Aside from the debug-vs-release effects, there is something more you should be aware of. ***You cannot effectively evaluate multi-threaded code for performance in 0.3s.*** The point of threads is two-fold: effectively model parallel work in code, and effectively exploit parallel resources (cpus, cores). You are trying to evaluate the latter. Given that thread start overhead is not vanishingly small in comparison to the interval over which you are timing, your measurement is immediately suspect. In most perf test trials, a significant warm up interval is appropriate. This may sound silly to you - it's a computer program fter all, not a lawnmower. But warm-up is absolutely imperative if you are really going to evaluate multi-thread performance. Caches get filled, pipelines fill up, pools get filled, GC generations get filled. The steady-state, continuous performance is what you would like to evaluate. For purposes of this exercise, the program behaves like a lawnmower. You could say - *Well, no, I don't want to evaluate the steady state performance.* And if that is the case, then I would say that your scenario is very specialized. Most app scenarios, whether their designers explicitly realize it or not, need continuous, steady performance. If you truly need the perf to be good only over a single 0.3s interval, you have found your answer. But be careful to not generalize the results. If you want general results, you need to have reasonably long warm up intervals, and longer collection intervals. You might start at 20s/60s for those phases, but here is the key thing: you need to vary those intervals until you find the results converging. YMMV. The valid times vary depending on the application workload and the resources dedicated to it, obviously. You may find that a measurement interval of 120s is necessary for convergence, or you may find 40s is just fine. But (a) you won't know until you measure it, and (b) you can bet 0.3s is not long enough.
Is the Managed heap not scalable to multi-core systems
[ "", "c#", ".net", "" ]
I'm having some issues with a jQuery AJAX call. My code works fine when I request a page with no javascript in it, but when I have script tags in my code, things start to get weird. It seems that any script tags referencing external URLs cause the browser to redirect. In firefox, the page goes blank. In safari, the page clears and loads with the content of the AJAX response. In both browsers, the URL doesn't change. To be specific about my problem; I have a tab control in which I'm trying to embed the walkscore widget. Since it's pretty heavy on the client side, I only want to actually load it once the user clicks the tab it's in. The walkscore AJAX page looks like this: ``` <script type="text/javascript"> var ws_address = "1 Market St, San Francisco"; var ws_width = "500"; </script> <script type="text/javascript" src="http://www.walkscore.com/tile/show-tile.php?wsid=MY_WSID"> </script> ``` Is there some restriction on script tags referencing external sites on AJAX calls? Is there any nice way around this? **-- Edit --** OK I've been playing with it for a bit and have narrowed down the problem a little. Let me try give a better explanation at the same time: I have two files, index.html and walkscore.html **index.html** ``` function widget() { var widget = $('#walkscore'); $.get('/walkscore.html', function(data) { $('#loading').slideUp(function() { widget.html(data); loaded[name] = true; widget.slideDown(); }); }); } ``` **walkscore.html** - as shown in the top code block In index.html, I have a link that calls the widget function. Whenever I click this link, the whole page is replaced by the output of the js file. It happens regardless of the domain the js file is from. It only seems to happen with js files that have document.write in them. It behaves in exactly the same way when I use the $.getScript function, even when it's in index.html **-- Edit --** It seems it has everything to do with the document.write. I made a copy of the walkscore javascript and replaced all occurrences of document.write with jquery.html, and it seems to work properly. I'm (obviously) a js noob. Is this the expected behavior of document.write? How come it doesn't do it when I include the script on a page load?
It happens because of the document.write call. Here's some info on what's going on: **Writing After A Page Has Been Loaded** If document.write() is invoked after a page has finished loading, the entire static (non-script generated) content of a page will be replaced with the write method's parameter. This scenario is most often played out when the write method is invoked from an event handler - whether the method is in a function called by the event handler or alone inside the handler - because event handlers are triggered after a page has finished loading. This is important to know because static content replacement is not always the desired result. Another common scenario for content overwite has to do with writing content to a new window. In this case, the overwrite of blank page is the goal. ([source](http://jennifermadden.com/javascript/writeMethod.html)) The solution I went with was to eliminate the document.write commands, and replace the content of a div instead. If you're loading an external script, and have no control over it, you can replace the document.write function with your own. It's discussed here: <http://www.webxpertz.net/forums/showthread.php?threadid=11658> Hope that helps someone out there!
Load script separately from html content, you can use $.getScript( ).
Browser refresh on AJAX with script tags in the response
[ "", "javascript", "jquery", "ajax", "" ]
I have some experience in AJAX development, mostly on .NET and MooTools. However, I want to learn more and see what others out there thought about the various other options available. I am looking more for advice about the front end. The back end, I will most probably be coding it in .NET using c# and WCF services. Please feel free to provide me as much information as you can. Also, I would appreciate any links to resources. **List of Options (feel free to add)** * Write my own Javascript * Use a framework like MooTools, JQuery, etc. Which one is better? * Use Google Web Toolkit. Am I tying myself to the limitations of GWT? Or are there not limitations? * ASP.NET AJAX * WPF (Will this run on non-IE browsers?) * Flash (it'll be a pain to learn action script) Thanks Jaspreet
Writing your own Javascript often means reinventing the wheel when it comes to trying to attain cross-browser compatibility. Frameworks such as jQuery and MooTools take care of much of that grunt work for you. Personally, I would suggest picking a Javascript framework or using GWT, but really it's just a matter of personal preference at that point, much like choosing a programming language. Pick that one that is best for your purposes, or that you're most familiar with.
I'd go with jQuery. jQuery will be bundled with the next version of Visual Studio. Google uses jQuery. jQuery has the largest user-base of any of the frameworks out there.. And speaking of not re-inventing the wheel: jQuery also has the largest plugin-repository of any of the frameworks out there.. Including its own official UI library which is in constant development. .. And if you're a fan of books; there's 3-4 books about the framework out currently. Oh, yeah! Check out [Douglas Crockford's website](http://crockford.com/) for great vanilla JavaScript tips and tricks. Just my two cents :)
Best Technologies for AJAX Web Development
[ "", "javascript", "wpf", "ajax", "flash", "" ]
Does anyone have any tips for debugging exceptions in a C# object initializer block? The object initializer syntax is basically all or nothing, which can make it especially difficult to troubleshoot inside of a LINQ query. Short of breaking the object creation out to a separate method, is there anything I can do to see which property setter is throwing an exception?
Disabling the option to step over property setters [Step over properties and operators (Managed Only)] can allow you to step into the property setters. Otherwise, the best option is often to just break it out and debug it outside of the LINQ statement. You can wrap your initialization parameters into an anonymous type in linq, and construct your object(s) outside of your linq statement for debugging purposes.
Have you set up VS to break when an exception is thrown? (the default is to break only on unhandled exceptions). Debug | Exceptions, and check "thrown". That alone is probably not an answer to your question, but it might help with the debugging. Beyond that, you could temporarily break your code out of the initializer block (just for debugging), and then if you want, you can reinstate the initializer block once you have the code working.
Debugging a C# Object Initializer
[ "", "c#", "linq", "object", "initializer", "" ]
This has been bugging me today after checking the source out on a site. I use PHP output in my templates for dynamic content. The templates start out in html only, and are cleanly indented and formatted. The PHP content is then added in and indented to match the html formating. ``` <ul> <li>nav1</li> <li>nav2</li> <li>nav3</li> </ul> ``` Becomes: ``` <ul> <?php foreach($navitems as $nav):?> <li><?=$nav?></li> <?php endforeach; ?> </ul> ``` When output in html, the encapsulated PHP lines are dropped but the white space used to format them are left in and throws the view source formatting all out of whack. The site I mentioned is cleanly formatted on the view source output. Should I assume they are using some template engine? Also would there be any way to clean up the kind of templates I have? with out manually removing the whitespace and sacrificing readability on the dev side?
That's something that's bugging me, too. The best you can do is using tidy to postprocess the text. Add this line to the start of your page (and be prepared for [output buffering](http://de.php.net/manual/en/function.ob-start.php) havoc when you encounter your first PHP error with output buffering on): ``` ob_start('ob_tidyhandler'); ```
You can't really get clean output from inlining PHP. I would strongly suggest using some kind of templating engine such as [Smarty](http://www.smarty.net/). Aside from the clean output, template engines have the advantage of maintaining some separation between your code and your design, increasing the maintainability and readability of complex websites.
How to keep PHP 'View Source' html output clean
[ "", "php", "html", "browser", "" ]
I have used OO programming languages and techniques years ago (primarily on C++) but in the intervening time haven't done much with OO. I'm starting to make a small utility in C#. I could simply program it all without using good OO practice, but it would be a good refresher for me to apply OO techniques. Like database normalization levels, I'm looking for a checklist that will remind me of the various rules of thumb for a 'good' object oriented program - a concise yes/no list that I can read through occasionally during design and implementation to prevent me from thinking and working procedurally. Would be even more useful if it contained the proper OO terms and concepts so that any check item is easily searchable for further information. **What should be on a checklist that would help someone develop good OO software?** Conversely, what 'tests' could be applied that would show software is not OO?
Sounds like you want some basic yes/no questions to ask yourself along your way. Everyone has given some great "do this" and "think like that" lists, so here is my crack at some simple yes/no's. Can I answer yes to all of these? * Do my classes represent the nouns I am concerned with? * Do my classes provide methods for actions/verbs that it can perform? Can I answer no to all of these? * Do I have global state data that could either be put into a singleton or stored in class implementations that work with it? * Can I remove any public methods on a class and add them to an interface or make them private/protected to better encapsulate the behavior? * Should I use an interface to separate a behavior away from other interfaces or the implementing class? * Do I have code that is repeated between related classes that I can move into a base class for better code reuse and abstraction? * Am I testing for the type of something to decide what action to do? If so can this behavior be included on the base type or interface that the code in question is using to allow more effect use of the abstraction or should the code in question be refactored to use a better base class or interface? * Am I repeatedly checking some context data to decided what type to instantiate? If so can this be abstracted out into a factory design pattern for better abstraction of logic and code reuse? * Is a class very large with multiple focuses of functionality? If so can I divide it up into multiple classes, each with their own single purpose? * Do I have unrelated classes inheriting from the same base class? If so can I divide the base class into better abstractions or can I use composition to gain access to functionality? * Has my inheritance hierarchy become fearfully deep? If so can I flatten it or separate things via interfaces or splitting functionality? * I have worried way too much about my inheritance hierarchy? * When I explain the design to a rubber ducky do I feel stupid about the design or stupid about talking to a duck? Just some quick ones off the top of my head. I hope it helps, OOP can get pretty crazy. I didn't include any yes/no's for more advanced stuff that's usually a concern with larger apps, like dependency injection or if you should split something out into different service/logic layers/assemblies....of course I hope you at least separate your UI from your logic.
* **Objects *do* things. (Most important point in the whole of OOP!)** Don't think about them as "data holders" - send them a message to do something. What verbs should my class have? The "Responsibility-Driven Design" school of thinking is brilliant for this. (See *Object Design: Roles, Responsibilities, and Collaborations*, Rebecca Wirfs-Brock and Alan McKean, Addison-Wesley 2003, ISBN 0201379430.) * For each thing the system must do, **come up with a bunch of concrete scenarios describing how the objects talk to each other to get the job done**. This means thinking in terms of interaction diagrams and acting out the method calls. - Don't start with a class diagram - that's SQL-thinking not OO-thinking. * **Learn Test-Driven Development.** *Nobody* gets their object model right up front but if you do TDD you're putting in the groundwork to make sure your object model does what it needs to and making it safe to refactor when things change later. * **Only build for the requirements you have now** - don't obsess about "re-use" or stuff that will be "useful later". If you only build what you need right now, you're keeping the design space of things you could do later much more open. * **Forget about inheritance when you're modelling objects.** It's just one way of implementing common code. When you're modelling objects just pretend you're looking at each object through an interface that describes what it can be asked to do. * **If a method takes loads of parameters or if you need to repeatedly call a bunch of objects to get lots of data, the method might be in the wrong class.** The best place for a method is right next to most of the fields it uses in the same class (or superclass ...) * **Read a Design Patterns book for your language.** If it's C#, try "Design Patterns in C#" by Steve Metsker. This will teach you a series of tricks you can use to divide work up between objects. * **Don't test an object to see what type it is and then take action based on that type** - that's a code smell that the object should probably be doing the work. It's a hint that you should call the object and ask it to do the work. (If only some kinds of objects do the work, you can simply have "do nothing" implementations in some objects... That's legitimate OOP.) * **Putting the methods and data in the right classes makes OO code run faster (and gives virtual machines a chance to optimise better) - it's not just aesthetic or theoretical.** The Sharble and Cohen study points this out - see <http://portal.acm.org/citation.cfm?doid=159420.155839> (See the graph of metrics on "number of instructions executed per scenario")
What should be on a checklist that would help someone develop good OO software?
[ "", "c#", "oop", "" ]
I am familiar with the generalities of genetic programming but am wondering where i might find something that shows me details of implementing genetic programming. I use C# and .NET 3.5, and I would like to put to use genetic programming for things like pathfinding, and generally just want to see what it can do. EDIT: I should probably clarify what I'm looking for: I'm interested in what sort of data structures would be used to store the syntax trees, how a breeding operation might be performed, that sort of thing.
Here is a quick rewrite of one of [C++ HelloWorld](http://www.generation5.org/content/2003/gahelloworld.asp "C++ HelloWorld") examples that helped me learn genetic programming: ``` using ga_vector = List<ga_struct>; class ga_struct { public ga_struct(string str, uint fitness) { Str = str; Fitness = fitness; } public string Str { get; set; } public uint Fitness { get; set; } } class Program { private const int GA_POPSIZE = 2048; private const int GA_MAXITER = 16384; private const float GA_ELITRATE = 0.10f; private const float GA_MUTATIONRATE = 0.25f; private const float GA_MUTATION = 32767 * GA_MUTATIONRATE; private const string GA_TARGET = "Hello world!"; private static readonly Random random = new Random((int)DateTime.Now.Ticks); static void Main(string[] args) { ga_vector popAlpha = new ga_vector(); ga_vector popBeta = new ga_vector(); InitPopulation(ref popAlpha, ref popBeta); ga_vector population = popAlpha; ga_vector buffer = popBeta; for (int i = 0; i < GA_MAXITER; i++) { CalcFitness(ref population); SortByFitness(ref population); PrintBest(ref population); if (population[0].Fitness == 0) break; Mate(ref population, ref buffer); Swap(ref population, ref buffer); } Console.ReadKey(); } static void Swap(ref ga_vector population, ref ga_vector buffer) { var temp = population; population = buffer; buffer = temp; } static void InitPopulation(ref ga_vector population, ref ga_vector buffer) { int tsize = GA_TARGET.Length; for (int i = 0; i < GA_POPSIZE; i++) { var citizen = new ga_struct(string.Empty, 0); for (int j = 0; j < tsize; j++) { citizen.Str += Convert.ToChar(random.Next(90) + 32); } population.Add(citizen); buffer.Add(new ga_struct(string.Empty, 0)); } } static void CalcFitness(ref ga_vector population) { const string target = GA_TARGET; int tsize = target.Length; for (int i = 0; i < GA_POPSIZE; i++) { uint fitness = 0; for (int j = 0; j < tsize; j++) { fitness += (uint) Math.Abs(population[i].Str[j] - target[j]); } population[i].Fitness = fitness; } } static int FitnessSort(ga_struct x, ga_struct y) { return x.Fitness.CompareTo(y.Fitness); } static void SortByFitness(ref ga_vector population) { population.Sort((x, y) => FitnessSort(x, y)); } static void Elitism(ref ga_vector population, ref ga_vector buffer, int esize) { for (int i = 0; i < esize; i++) { buffer[i].Str = population[i].Str; buffer[i].Fitness = population[i].Fitness; } } static void Mutate(ref ga_struct member) { int tsize = GA_TARGET.Length; int ipos = random.Next(tsize); int delta = random.Next(90) + 32; var mutated = member.Str.ToCharArray(); Convert.ToChar((member.Str[ipos] + delta)%123).ToString().CopyTo(0, mutated, ipos, 1); member.Str = mutated.ToString(); } static void Mate(ref ga_vector population, ref ga_vector buffer) { const int esize = (int) (GA_POPSIZE*GA_ELITRATE); int tsize = GA_TARGET.Length, spos, i1, i2; Elitism(ref population, ref buffer, esize); for (int i = esize; i < GA_POPSIZE; i++) { i1 = random.Next(GA_POPSIZE/2); i2 = random.Next(GA_POPSIZE/2); spos = random.Next(tsize); buffer[i].Str = population[i1].Str.Substring(0, spos) + population[i2].Str.Substring(spos, tsize - spos); if (random.Next() < GA_MUTATION) { var mutated = buffer[i]; Mutate(ref mutated); buffer[i] = mutated; } } } static void PrintBest(ref ga_vector gav) { Console.WriteLine("Best: " + gav[0].Str + " (" + gav[0].Fitness + ")"); } ``` There might be some minor errors but otherwise it looks it's working ok. Also it could be written better in spirit of C# but those are just details. :)
Roger Alsing's Mona Lisa project is a quite good example. <http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mona-lisa/> EDIT: The reason I like the example is because it rather small and easy to understand. Its a quick and easy way to grasp the concept of genetic programming.
Genetic Programming Implementation
[ "", "c#", "implementation", "genetic-programming", "" ]
I am wondering how to write the model, hbm.xml for table ``` Company ------- id(PK) name address typeid(fk) Type ---- id(PK) type class Company(){ int id; String name; String address; Type type; } class Type(){ int id; String type; } ``` (with get/set methods) How to write the hbm? I am using the hibernate 3.x.
Can you have multiple companies of the same type? Don't you really want a many to one relationship? How about something like this (adapted from the Hibernate docs from [here](http://docs.jboss.org/hibernate/stable/core/reference/en/html/assoc-unidirectional.html)): ``` <class name="Company" table="company"> <id name="id" column="id"> ... </id> .... <many-to-one name="type" class="Type" column="typeid" not-null="true"/> </class> <class name="Type"> <id name="id" column="id"> ... </id> </class> ```
the given situation is a many-to-one situation, because 1 type can be assigned to multiple companies
hibernate one-to-one or component?
[ "", "java", "hibernate", "" ]
I have my own hand-rolled PHP MVC framework for some projects that I'm working on. When I first created the framework, it was in the context of building an admin CMS. Therefore, there was a very nice one-to-one relationship between model, view, and controller. You have a single row in the DB, which maps to a single model. The controller loads the model and passes it to the view to be rendered (such as into an edit form). Nice, clean, and easy. However, now that I'm working on the front end of the site, things are getting sticky. A page isn't always a view of a single model. It might be a user directory listing with 20 users (each a User model). Furthermore, there might be metadata about the request, such as pagination (current page, total pages, number of results) and/or a search query. My question is, what is the cleanest way to pass all this data to the view? Some options I'm considering: * **Have the controller create an array and pass that to the view as a single parameter:** ``` class UserController{ public function renderView(){ // assume there's some logic to create models, get pagination, etc. $data = array() $data['models'] = $models; $data['currentPage'] = $current; $data['totalPages'] = $total; return $view->render($data); } } class UserView{ public function render($data){ // render the data } } ``` * **Create properties in the view class and have the controller populate them:** ``` class UserView{ public $models; public $currentPage; public $totalPages; } class UserController{ public function renderView(){ // assume there's some logic to create models, get pagination, etc. $view = new UserView(); $view->models = $models; $view->currentPage = $current; $view->totalPages = $total; return $view->render(); } } ``` * **Give the view some sort of generic HashMap or Collection object as a container which can hold any arbitrary number and name of data.** ``` class UserView{ public $collection = new Collection(); // works like a Java collection } class UserController{ public function renderView(){ // assume there's some logic to create models, get pagination, etc. $view = new UserView(); $view->collection->add($models,'models'); $view->collection->add($currentPage,'currentPage'); return $view->render(); } } ``` I know that technically any of the *could* work, but I'm unsure of the best choice, or if there's a better or more conventional choice that I'm missing.
I'm going to recommend the concept of [Fat Models, Skinny Controllers](http://www.google.com/search?q=fat+models+skinny+controllers) (or, [Fat Models Thin Controllers](http://www.google.com/search?q=fat+models+thin+controllers) if you prefer...) In otherwords, your model is too strict - tying your model to represent only something like a RowDataGateway is extremely limiting. In fact, I think good models hide the fact that you're reading the data from a database at all. Because, in reality, your data could be in text files, or from a web service, or whatever. If you treat your Model like nothing more than a glorified DBAL, you doom yourself to having tightly-coupled code in your controllers that just won't let you break away from the "data only comes from the database" way of thinking.
I've seen both of the first two methods implemented in popular MVC/templating frameworks. [django](http://www.djangoproject.com/) uses the first method, passing to the view a dictionary of variables which the view uses to fill the template. [smarty](http://smarty.net) uses the second method, creating a Smarty object and assigning values to each the properties in the container. Your third method seems to essentially be the same as the second, with minor architecture differences. Really, I guess I haven't said anything that you haven't thought of already. Basically, these are all sounds ideas, so implement whatever you feel you are most comfortable with.
Passing data from MVC Controller to View in PHP
[ "", "php", "model-view-controller", "view", "controller", "" ]
I was wondering if anybody knew exactly what permissions where needed on a database in SQL Server 2005+ so that when a person uses SQL Server Management Studio, they could then be able to at minimum see the Database Diagrams. I have tried giving the person db\_datareader, db\_datawriter, and db\_ddladmin, but to no avail. I have also tried giving them access in the Properties → Effective Permissions of the user. Under Effective Permissions, I could not find the database object type for "database diagrams" or anything like that to give the user access to. They are running SQL Server Management Studio (non-express version.) Any help would be great. FYI, I did not want to give them db\_owner access. EDIT: 1. As to one of the comments: Yes, the database is an SQL Server 2005 database. 2. As to one of the answers, moving the DB from production to development is not an option.
Giving admin rights is not the right approach, you need to be Database Owner for Database Diagrams, [check out this thread for more details](http://social.msdn.microsoft.com/Forums/en-US/sqlexpress/thread/8715f383-3e28-4910-93f9-5cca51d48380/).
First you need to set up Diagram Designer (you need to be db\_owner for that). Just expand the Diagrams node, and press 'Yes' to enable diagramming. After that all other db users can create diagrams and see **their own** diagrams. Only db\_owner can see other's diagrams. Also the db\_owner can change diagram owner to himself, but the original owner must be removed from database before doing that.
SQL Server Management Studio Display Database Diagrams (ER) Permissions
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
Asking this question with C# tag, but if it is possible, it should be possible in any language. Is it possible to implement a doubly linked list using Interlocked operations to provide no-wait locking? I would want to insert, add and remove, and clear without waiting.
A simple google search will reveal many lock-free doubly linked list papers. However, they are based on atomic CAS (compare and swap). I don't know how atomic the operations in C# are, but according to this website <http://www.albahari.com/threading/part4.aspx> C# operations are only guaranteed to be atomic for reading and writing a 32bit field. No mention of CAS.
Yes it's possible, here's my implementation of an STL-like [Lock-Free Doubly-Linked List](https://github.com/Qarterd/Honeycomb/blob/master/src/common/Honey/Thread/LockFree/List.h) in C++. [Sample code that spawns threads to randomly perform ops on a list](https://github.com/Qarterd/Honeycomb/blob/master/test/Test.cpp#L12) It requires a 64-bit compare-and-swap to operate without ABA issues. This list is only possible because of a [lock-free memory manager](https://github.com/Qarterd/Honeycomb/blob/master/src/common/Honey/Thread/LockFree/HazardMem.h). Check out the [benchmarks on page 12](http://docs.google.com/viewer?url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.140.5222%26rep%3Drep1%26type%3Dpdf). Performance of the list scales linearly with the number of threads as contention increases. The algorithm supports parallelism for disjoint accesses, so as the list size increases contention can decrease.
Is a lock (wait) free doubly linked list possible?
[ "", "c#", "thread-safety", "locking", "lock-free", "interlocked", "" ]
I'm trying to understand what's going on in the following code. When object-a is deleted, does it's shared\_ptr member variable object-b remains in memory because object-c holds a shared\_ptr to object-b? ``` class B { public: B(int val) { _val = val; } int _val; }; class A { public: A() { _b = new B(121); } boost::shared_ptr<B> _b; }; class C { public: C() { } void setRef( boost::shared_ptr<B> b) { _b = b; } boost::shared_ptr<B> _b; }; int main() { C c; { A *a = new A(); cout << "a._b.use_count: " << a->_b.use_count() << endl; c.setRef(a->_b); cout << "a._b.use_count: " << a->_b.use_count() << endl; delete a; } cout << c._b->_val << endl; } ```
The `A`-object will be cleaned up as soon as `a` is deleted at the end of its block. But the shared\_ptr it contains was subsequently copied, incrementing its reference count. Thus, the `B`-object will have a reference count of 2 after `c.setRef` (referenced by the `A`-object and by the `C`-object's `shared_ptr`). When `a` is deleted at the end of its block, then the reference count of the `B`-object drops to `1` again since only `c`'s shared\_ptr is referencing it now. After `c` is destroyed at the end of main, its `shared_ptr` will be destroyed too as part of `c`'s destruction, and now as the reference count drops to zero, the pointed-to `B` object will be deleted by `shared_ptr`. So, the reference counts of the `B`-object: ``` 0: before existence of a. 1: from start of lifetime of a until c.setRef 2: from c.setRef until copy of its parameter 3: from copy of c.setRef''s parameter until return of it 2: from return of c.setRef until end of a''s block 1: from end of a''s block until end of main 0: after main returned (object doesn''t exist anymore now) ```
No, when a is deleted, a->\_b (the pointer itself) will cease to exist. The **object** that a->\_b points to will continue to exist, because c.\_b still points to it.
boost::shared_ptr use_count
[ "", "c++", "pointers", "shared-ptr", "" ]
How do you remove a cookie in a Java servlet? I tried this: <http://www.jguru.com/faq/view.jsp?EID=42225> EDIT: The following now works successfully it appears to be the combination of: ``` response.setContentType("text/html"); ``` and ``` cookie.setMaxAge(0); ``` Before I was doing: ``` //remove single signon cookie if it hasn't been validated yet response.setContentType("text/html"); Cookie cookie = new Cookie(SSORealm.SSO_COOKIE_NAME, ""); cookie.setDomain(SSORealm.SSO_DOMAIN); cookie.setMaxAge(-1); cookie.setPath("/"); cookie.setComment("EXPIRING COOKIE at " + System.currentTimeMillis()); response.addCookie(cookie); ``` Which expires the cookie when the browser is closed as per [the documentation](http://docs.oracle.com/javaee/6/api/javax/servlet/http/Cookie.html#setMaxAge%28int%29). > A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted. The full working snippet to expire a cookie is: ``` //remove single signon cookie if it hasn't been validated yet response.setContentType("text/html"); Cookie cookie = new Cookie(SSORealm.SSO_COOKIE_NAME, ""); cookie.setDomain(SSORealm.SSO_DOMAIN); cookie.setMaxAge(0); cookie.setPath("/"); cookie.setComment("EXPIRING COOKIE at " + System.currentTimeMillis()); response.addCookie(cookie); ```
The MaxAge of -1 signals that you want the cookie to persist for the duration of the session. You want to set MaxAge to 0 instead. From the [API documentation](http://docs.oracle.com/javaee/6/api/javax/servlet/http/Cookie.html#setMaxAge%28int%29): > A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
In my environment, following code works. Although looks redundant at first glance, `cookies[i].setValue("");` and `cookies[i].setPath("/");` are necessary to clear the cookie properly. ``` private void eraseCookie(HttpServletRequest req, HttpServletResponse resp) { Cookie[] cookies = req.getCookies(); if (cookies != null) for (Cookie cookie : cookies) { cookie.setValue(""); cookie.setPath("/"); cookie.setMaxAge(0); resp.addCookie(cookie); } } ```
How do you remove a Cookie in a Java Servlet
[ "", "java", "servlets", "cookies", "" ]
I have a class with a read-only property defined. In my code I define this as a property with a getter only. I want to be able to send this object back and forth across a web service. When I call a "Get" method in the service, it would be populated with a value on the service side. Once I define this property, I don't want the consumer of the web service to be able to set/change this property. When I add a reference to this web service to a project, the object has the property serialized a few different ways depending on how I try to define the object on the service side: * **internal setter**: Creates the property in the WSDL. Visual Studio generates a class with both a getter & a setter for this property. * **no setter**: Does not create the property in the WSDL. Visual Studio then obviously does not define this property at all. * **Read-only public member variable** - Does not create the property in the WSDL. Again, Visual Studio will not do anything with this property since it doesn't know about it. Allowing the consumer of the web service to set a value for this property will not cause any harm. If the value is set, it is ignored on the web service side. I'd just prefer if the consumer can't change/set the property to begin. Is there any way to define a property as read-only? Right now we're using C#/.NET 2.0 for the web service, and (for now at least) we have control over all of the consumers of this service, so I can try changing configurations if needed, but I prefer to only change things on the web service and not the consumers.
Caveat, I am a Java guy so the first part of my answer focuses on what may be possible in C#. Firstly, with a custom serializer in Java, you can do almost anything you want, including directly setting values of a protected or private field using reflection so long as the security manager doesn't prevent this activity. I don't know if there are analogous components in C# for the security manager, field access, and custom serializers, but I would suspect that there are. Secondly, I think there is a fundamental difference in how you are viewing Web services and the Web service interface as part of your application. You are right-click generating the Web service interface from existing code - known as "code first". There are many articles out there about why WSDL first is the preferred approach. [This](http://webservices.xml.com/pub/a/ws/2003/07/22/wsdlfirst.html) one summarizes things fairly well, but I would recommend reading others as well. While you are thinking in terms of a shared code library between the client side and server side of your Web service and maintaining object structure and accessibility, there is no such guarantee once you publish an API as a Web service and don't have control over all of the consumers. The WSDL and XSD serve as a generic description of your Web service API and your server and client can be implemented using different data binding configurations, object classes, or languages. You should think of your Web service interface and the XML that you pass in and out of it as describing the semantics of the exchange, but not necessarily the syntax of the data (your class structure) once it is internalized (deserialized) in your client or server. Furthermore, it is advisable to decouple your transport related structures from your internal business logic structures lest you find yourself having to refactor both your server implementation, your Web service API, and your (and other's) client implementations all at the same time.
I can be wrong, but I think the problem here is how serialization works - in order to deserialize an object the serializer creates an empty object and then sets all the properties on this object - thats why you need a setter for the properties to be included in serialization. The client code has the same "interface" to the object as the deserializer.
Is it possible to create read only elements in SOAP web services?
[ "", "c#", "web-services", "soap", "c#-2.0", "" ]
I have the following XML file with **"page" nodes** which I want to read into **"PageItem" objects** in my application. Most of the XML nodes I save as string/int/DataTime property which works fine. But **what is the best way to store the XML child nodes of the "content" node in a property of a PageItem object** so that I can parse it later within the application? Should I store it as a string and later read in the string as XML or is there a more efficient way to store the XML child nodes as a property? ``` <?xml version="1.0" encoding="utf-8" ?> <pages> <page> <id>1</id> <whenCreated>2007-01-19T00:00:00</whenCreated> <itemOwner>edward</itemOwner> <publishStatus>published</publishStatus> <correctionOfId>0</correctionOfId> <idCode>contactData</idCode> <menu>mainMenu</menu> <title>Contact Data</title> <description>This is contact data page.</description> <accessGroups>loggedInUsers,loggedOutUsers</accessGroups> <displayOrder>10</displayOrder> <content> <form idcode="customers" query="limit 5; category=internal"/> <form idcode="customersDetail" query="limit 10; category=internal"/> </content> </page> <page> <id>2</id> <whenCreated>2007-01-29T00:00:00</whenCreated> <itemOwner>edward</itemOwner> ... ``` I read this XML file into **PageItem** objects: ``` public class PageItem : Item { public string IdCode { get; set; } public string Title { get; set; } public string Description { get; set; } public string Menu { get; set; } public string AccessGroups { get; set; } public int DisplayOrder { get; set; } public List<XmlNode> Content { get; set; } //PSEUDO-CODE ``` with this code: ``` var pageItems = from pageItem in xmlDoc.Descendants("page") orderby (int)pageItem.Element("displayOrder") select new Models.PageItem { Id = (int)pageItem.Element("id"), WhenCreated = (DateTime)pageItem.Element("whenCreated"), ItemOwner = pageItem.Element("itemOwner").Value, PublishStatus = pageItem.Element("publishStatus").Value, CorrectionOfId = (int)pageItem.Element("correctionOfId"), IdCode = pageItem.Element("idCode").Value, Menu = pageItem.Element("menu").Value, Title = pageItem.Element("title").Value, Description = pageItem.Element("description").Value, AccessGroups = pageItem.Element("accessGroups").Value, DisplayOrder = (int)pageItem.Element("displayOrder"), Content = pageItem.Element("content").DescendantNodes() //PSEUDO-CODE }; ```
Use this property:- ``` public XElement Content { get; set; } //PSEUDO-CODE ``` and assign like this:- ``` Content = pageItem.Element("content") ```
Have you tried XmlSerializer? ``` public string Serialize(PageItem obj) { XmlSerializer formatter = new XmlSerializer(typeof(PageItem)); MemoryStream ms = new MemoryStream(); formatter.Serialize(ms, obj); ms.Position = 0; StreamReader sr = new StreamReader(ms); return sr.ReadToEnd(); } public PageItem Deserialize(string serializedObject) { XmlSerializer formatter = new XmlSerializer(typeof(PageItem)); MemoryStream ms = serializedObject.ToMemoryStreamFromUTF8(); return ((PageItem)formatter.Deserialize(ms)); } ```
What is the best way to pass around XML in a .NET application?
[ "", "c#", "xml", "" ]
we build newsletter module, and send email to members. The environment is LAMP. Are there any way to know whether member open the mail ? i hear about put image if 'php' source , what is the best way?
A common way to check if an email has been read is a [web beacon](http://en.wikipedia.org/wiki/Web_beacons), which is usually a small 1x1px invisible image that is loaded from your server, which can track when the image has been loaded and therefore the email has been read. This is not guaranteed to work, however, since many email clients block images in their emails or your readers could be using text-only email clients.
Ultimately there is obviously no fool-proof way to get notifications, because there is no guaranteed way of getting the email client to respond back in some fashion; the email client can be set up to just interpret the incoming email as ASCII text and nothing more, and there is nothing you can do about that. However; in most cases if you are emailing to users that are expecting an email, odds are that HTML rendering and inline images are probably turned on for your source address, so using an inline IMG tag and monitoring access to the referenced file (obviously using some per-user unique ID in the reference) should give you the best you are going to get. Regardless you'll never be able to make the assumption that if you do not get a notification back that that means the user has **not** seen the email.
Are there any way to know whether user open mail?
[ "", "php", "email", "lamp", "" ]
I'm trying to invoke a webservice from a console application, and I need to provide the client with a `System.Net.NetworkCredential` object. Is it possible to create a `NetworkCredential` object for the user that started the application without prompting for username/password?
If the web service being invoked uses windows integrated security, creating a `NetworkCredential` from the current `WindowsIdentity` should be sufficient to allow the web service to use the current users windows login. However, if the web service uses a different security model, there isn't any way to extract a users password from the current identity ... that in and of itself would be insecure, allowing you, the developer, to steal your users passwords. You will likely need to provide some way for your user to provide their password, and keep it in some secure cache if you don't want them to have to repeatedly provide it. Edit: To get the credentials for the current identity, use the following: ``` Uri uri = new Uri("http://tempuri.org/"); ICredentials credentials = CredentialCache.DefaultCredentials; NetworkCredential credential = credentials.GetCredential(uri, "Basic"); ```
You can get the user name using [System.Security.Principal.WindowsIdentity.GetCurrent()](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.getcurrent.aspx) but there is not way to get current user password!
Getting NetworkCredential for current user (C#)
[ "", "c#", "web-services", "authentication", "" ]
> **Possible Duplicate:** > [In C arrays why is this true? a[5] == 5[a]](https://stackoverflow.com/questions/381542/in-c-arrays-why-is-this-true-a5-5a) Is the possibility of both array[index] and index[array] a compiler feature or a language feature. How is the second one possible?
The compiler will turn ``` index[array] ``` into ``` *(index + array) ``` With the normal syntax it would turn ``` array[index] ``` into ``` *(array + index) ``` and thus you see that both expressions evaluate to the same value. This holds for both C and C++.
From the earliest days of C, the expression `a[i]` was simply the address of a[0] added to i (scaled up by the size of a[0]) and then de-referenced. In fact, all these were equivalent: ``` a[i] i[a] *(a+i) ``` > ==== > > The only thing I'd be concerned about is the actual de-referencing. Whilst they all produce the same *address*, de-referencing may be a concern if the types of `a` and `i` are different. > > For example: ``` int i = 4; long a[9]; long x = a[i]; //get the long at memory location X. long x = i[a]; //get the int at memory location X? ``` > I haven't actually tested that behavior but it's something you may want to watch out for. If it does change what gets de-referenced, it's likely to cause all sorts of problems with arrays of objects as well. > > ==== **Update:** You can probably safely ignore the bit above between the `=====` lines. I've tested it under Cygwin with a short and a long and it seems okay, so I guess my fears were unfounded, at least for the basic cases. I still have no idea what happens with more complicated ones because it's not something I'm ever likely to want to do.
C++ array[index] vs index[array]
[ "", "c++", "c", "arrays", "" ]
I want to check if an object `o` is an instance of the class `C` or of a subclass of `C`. For instance, if `x` is of class `Point` I want `x.instanceOf(Point.class)` to be `true` and also `x.instanceOf(Object.class)` to be `true`. I want it to work also for boxed primitive types. For instance, if `x` is an `Integer` then `x.instanceOf(Integer.class)` should be `true`. Is there such a thing? If not, how can I implement such a method?
[Class.isInstance](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isInstance(java.lang.Object)) does what you want. ``` if (Point.class.isInstance(someObj)){ ... } ``` Of course, you shouldn't use it if you could use `instanceof` instead, but for reflection scenarios it often comes in handy.
> I want to check if an object o is an > instance of the class c or of a > subclass of c. For instance, if p is > of class Point I want > x.instanceOf(Point.class) Um... What? What are o, p and x? > I want it to work also for primitive > types. For instance, if x is an > integer then > x.instanceOf(Integer.class) and also > x.instanceOf(Object.class) should be > true. No. It shouldn't even compile. Primitives are not objects, and you cannot call methods on them. Anyway, there are three things, one of which can definitely achieve what you want (they differ somewhat in where exactly the apply: * The `instanceof` operator if you know the class at compile time. * [Class.isInstance()](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isInstance(java.lang.Object)) if you want to check an object's class against a class not known at compile time. * [Class.isAssignableFrom()](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isAssignableFrom(java.lang.Class)) if you want to check the assignability given two class objects.
Is there something like instanceOf(Class<?> c) in Java?
[ "", "java", "reflection", "instanceof", "" ]
Looking at the signatures for the Func and Converter delegates, ``` public delegate TResult Func<T, TResult>(T arg); public delegate TOutput Converter<TInput, TOutput>(TInput input); ``` I'm struggling to see the difference between the two. Surely, if we rename the generic type arguments, they essentially amount to the same thing? Can anyone explain why they both exist, please?
There is no difference. The reason for their existence is historical. `Converter<T1,T2>` was already available in .NET 2.0, but a whole range of `Func<>` delegate types were added later on. For consistency, `Func<T,TResult>` was added, but it did the same thing as `Converter<T1,T2>`.
There are lots of delegate types that are *effictively* the same - for example: * `ThreadStart` * `MethodInvoker` * `Action` all have the same `void Foo()` signature. Historically, the names were chosen by the specific use; but with LINQ and looking forwards, it seems clearer to focus on the signature - hence in .NET 3.5 they introduced things like `Func<...>` and `Action<...>` (*families* of delegates) Unfortunately, they aren't really compatible at the variance level, so if you are using both you'll often have to shim between them. Which is a pain...
What's the difference between Func<T, TResult> and Converter<TInput, TOutput>?
[ "", "c#", "delegates", "" ]
I've got a very weird bug on our test machine. The error is: `System.TypeLoadException: Method 'SetShort' in type 'DummyItem' from assembly 'ActiveViewers (...)' does not have an implementation.` I just can't understand why. `SetShort` is there in the `DummyItem` class, and I've even recompiled a version with writes to the event log just to make sure that it's not a deployment/versioning issue. The weird thing is that the calling code doesn't even call the `SetShort` method.
**NOTE** - If this answer doesn't help you, please take the time to scroll down through the other answers that people have added since. **Really short answer** Delete all your `bin` and `obj` directories and rebuild everything. The versions of the dlls don't match. **Short answer** This can happen if you add a method to an interface in one assembly, and then to an implementing class in another assembly, but you rebuild the implementing assembly without referencing the new version of the interface assembly. In this case, DummyItem implements an interface from another assembly. The SetShort method was recently added to both the interface and the DummyItem - but the assembly containing DummyItem was rebuilt referencing the previous version of the interface assembly. So the SetShort method is effectively there, but without the magic sauce linking it to the equivalent method in the interface. **Long answer** If you want to try reproducing this, try the following: 1. Create a class library project: InterfaceDef, add just one class, and build: ``` public interface IInterface { string GetString(string key); //short GetShort(string key); } ``` 2. Create a second class library project: Implementation (with separate solution), copy InterfaceDef.dll into project directory and add as file reference, add just one class, and build: ``` public class ImplementingClass : IInterface { #region IInterface Members public string GetString(string key) { return "hello world"; } //public short GetShort(string key) //{ // return 1; //} #endregion } ``` 3. Create a third, console project: ClientCode, copy the two dlls into the project directory, add file references, and add the following code into the Main method: ``` IInterface test = new ImplementingClass(); string s = test.GetString("dummykey"); Console.WriteLine(s); Console.ReadKey(); ``` 4. Run the code once, the console says "hello world" 5. Uncomment the code in the two dll projects and rebuild - copy the two dlls back into the ClientCode project, rebuild and try running again. TypeLoadException occurs when trying to instantiate the ImplementingClass.
In addition to what the asker's own answer already stated, it may be worth noting the following. The reason this happens is because it is possible for a class to have a method with the same signature as an interface method without implementing that method. The following code illustrates that: ``` public interface IFoo { void DoFoo(); } public class Foo : IFoo { public void DoFoo() { Console.WriteLine("This is _not_ the interface method."); } void IFoo.DoFoo() { Console.WriteLine("This _is_ the interface method."); } } Foo foo = new Foo(); foo.DoFoo(); // This calls the non-interface method IFoo foo2 = foo; foo2.DoFoo(); // This calls the interface method ```
TypeLoadException says 'no implementation', but it is implemented
[ "", "c#", ".net", "fusion", "typeloadexception", "" ]
Currently, the only information I have is a one-line error message in the browser's status-bar. Do you know how I could get a stack-trace for example ?
[This article is a bit old](http://java.sun.com/j2se/1.5.0/docs/guide/plugin/developer_guide/debugger.html) but is still relevant (including a section entitled "How to Debug Applets in Java Plug-in"). Edit: perhaps a better way to get stacktraces is to use the [Java plugin console](http://java.sun.com/j2se/1.5.0/docs/guide/deployment/deployment-guide/console.html). If you hit "t" in that window, you'll see the following: > Prints out all the existing thread > groups. The first group shown is Group > main. ac stands for active count; it > is the total number of active threads > in a thread group and its child thread > groups. agc stands for active group > count; it is the number of active > child thread groups of a thread group. > pri stands for priority; it is the > priority of a thread group. Following > Group main, other thread groups will > be shown as Group , where name > is the URL associated with an applet. > Individual listings of threads will > show the thread name, the thread > priority, alive if the thread is alive > or destroyed if the thread is in the > process of being destroyed, and daemon > if the thread is a daemon thread. The other command that I've used most often from that console is the trace level from 0-5: > This sets the trace-level options as described in the next section, [Tracing and Logging.](http://java.sun.com/j2se/1.5.0/docs/guide/deployment/deployment-guide/tracing_logging.html#tracing) From that page, you'll see that the levels look like this: > * 0 — off > * 1 — basic > * 2 — network, cache, and basic > * 3 — security, network and basic > * 4 — extension, security, network and basic > * 5 — LiveConnect, extension, security, network, temp, and basic These tools can all be fairly useful as you're trying to unravel what in the world has gotten into the head of your applets. I know that they've worked for me.
Aside from the obvious use of the Java console and the applet viewer, starting from Java 6 update 7, you can use the [VisualVM](http://java.sun.com/javase/6/docs/technotes/guides/visualvm/index.html) that comes with the JDK (JDK\_HOME/bin/visualvm). It allows you to view the stack traces of each thread and even view all object instances. AppletViewer is very handy, you can do a "Run as / Java Applet" from Eclipse to run, or "Debug As / Java Applet" to debug your applet classes. However, sometimes to debug some security related stuff the browser plugin environment is just too different from appletviewer. Here's what you can do to effectively debug applets in the browser: **1) Obtain debugging info for the binaries** Backup the .jar files from JRE\_HOME/lib (Download and) Install a JDK for the same version as your JRE. Copy the .jar files from JDK\_HOME/jre/lib to JRE\_HOME/lib The files inside the JDK were compiled with the debugging information included (source-code line number information, variable names, etc) and the JRE files don't have this information. Without this you won't be able to meaningfully step into core class code in your debugger. **2) Enable debugging for the Java Plug-in** Go to the Java Control Panel / Java / Java Runtime Settings / View / User / Runtime Parameters And add the options to enable debugging. Something like this: ``` -Djava.compiler=NONE -Xnoagent -Xdebug -Xrunjdwp:transport=dt_socket,address=2502,server=y,suspend=n ``` The interesting options are the port (using 2502 here, you can use pretty much any free port, just write it down for later) and the suspend - if you need to debug the applet startup, classloading, etc, set this to "y". That way when you access an applet page, the browser will appear to freeze as the JVM immediately gets suspended waiting for a debugger to connect. **3) Use your favorite IDE to Remotely debug the Java Plug-in** In Eclipse, for instance, choose Run / Debug Configurations ... / Remote Java Application Click on the "New" button. Make sure connection type is "Socket Attach", choose localhost as the host if your browser is local, and the port you chose earlier (2502 in the example). You might have to inlude the src.zip in your JDK on the sources tab to have the Java core class sources available. Save the configuration, and once your browser is running the plug-in (with the JVM suspended or not) run the remote debugger to connect to the plug-in JVM, with a project containing your applet sources open.
How do you debug Java Applets?
[ "", "java", "debugging", "applet", "" ]
I'm referring to [this Nimbus reference](http://jasperpotts.com/blogfiles/nimbusdefaults/nimbus.html). I tried to set global Font to be slightly larger: ``` UIManager.put("defaultFont", new Font(Font.SANS_SERIF, 0, 16)); ``` ...works only for the menu but **nothing** else (buttons, labels). I tried to change labels and buttons fonts with ``` UIManager.put("Button.font", new Font(Font.SANS_SERIF, 0, 16)); UIManager.put("Label.font", new Font(Font.SANS_SERIF, 0, 16)); ``` but the font **remains**. The only thing that worked for me was **deriving** a font: ``` someButton.setFont(someButton.getFont().deriveFont(16f)); ``` But this is not an option, since this must be done for **each** element manually. Note, that deriving a font for UIManager **doesn't work** either: ``` UIManager.put("Label.font", UIManager.getFont("Label.font").deriveFont(16f)); ``` I tested everything under Linux and Windows: same behavior. *I just can't understand how an API can be so messy. If a method is called setFont(..) then **I expect it** to set the font. If this method fails to set the font in any thinkable circumstances, then it should be deprecated.* **EDIT:** The problem not only applies to Nimbus, but also to the default LAF.
This **works** with JDK6 and JDK7. **Copy+paste and have fun ;)** Note: for JDK6, change `javax.swing.plaf.nimbus` to `com.​sun.​java.​swing.​plaf.​nimbus`. ## Code ``` import java.awt.*; import java.lang.reflect.*; import javax.swing.*; import javax.swing.plaf.nimbus.*; public class Main { public static void main(String[] args) throws InterruptedException, InvocationTargetException { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(new NimbusLookAndFeel() { @Override public UIDefaults getDefaults() { UIDefaults ret = super.getDefaults(); ret.put("defaultFont", new Font(Font.MONOSPACED, Font.BOLD, 16)); // supersize me return ret; } }); new JFrame("Hello") { { setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new FlowLayout(FlowLayout.LEFT)); setSize(500, 500); setLocationRelativeTo(null); add(new JLabel("someLabel 1")); add(new JButton("someButton 1")); add(new JLabel("someLabel 2")); add(new JButton("someButton 2")); setVisible(true); } }; } catch (Exception ex) { throw new Error(ex); } } }); } } ```
The nimbus defaults are lazy created so setting 'defaultFont' before the screen is painted, will add the font to the parent defaults, and not to the nimbus defaults. Workaround: force nimbus to initialize the defaults and set then the defaults: ``` NimbusLookAndFeel laf = new NimbusLookAndFeel(); UIManager.setLookAndFeel(laf); laf.getDefaults().put("defaultFont", new Font("Monospaced", Font.BOLD, 12)); ``` Note: this code is more efficient then overriding getDefaults(), as suggested above.
Java: Altering UI fonts (Nimbus) doesn't work!
[ "", "java", "swing", "user-interface", "fonts", "nimbus", "" ]
[`newCachedThreadPool()`](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool--) versus [`newFixedThreadPool()`](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool-int-) When should I use one or the other? Which strategy is better in terms of resource utilization?
I think the docs explain the difference and usage of these two functions pretty well: [`newFixedThreadPool`](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool%28int%29) > Creates a thread pool that reuses a > fixed number of threads operating off > a shared unbounded queue. At any > point, at most nThreads threads will > be active processing tasks. If > additional tasks are submitted when > all threads are active, they will wait > in the queue until a thread is > available. If any thread terminates > due to a failure during execution > prior to shutdown, a new one will take > its place if needed to execute > subsequent tasks. The threads in the > pool will exist until it is explicitly > shutdown. [`newCachedThreadPool`](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool()) > Creates a thread pool that creates new > threads as needed, but will reuse > previously constructed threads when > they are available. These pools will > typically improve the performance of > programs that execute many short-lived > asynchronous tasks. Calls to execute > will reuse previously constructed > threads if available. If no existing > thread is available, a new thread will > be created and added to the pool. > Threads that have not been used for > sixty seconds are terminated and > removed from the cache. Thus, a pool > that remains idle for long enough will > not consume any resources. Note that > pools with similar properties but > different details (for example, > timeout parameters) may be created > using ThreadPoolExecutor constructors. In terms of resources, the `newFixedThreadPool` will keep all the threads running until they are explicitly terminated. In the `newCachedThreadPool` Threads that have not been used for sixty seconds are terminated and removed from the cache. Given this, the resource consumption will depend very much in the situation. For instance, If you have a huge number of long running tasks I would suggest the `FixedThreadPool`. As for the `CachedThreadPool`, the docs say that "These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks".
Just to complete the other answers, I would like to quote Effective Java, 2nd Edition, by Joshua Bloch, chapter 10, Item 68 : > "Choosing the executor service for a particular application can be tricky. If you’re writing a **small program**, or a **lightly loaded server**, using **Executors.new- CachedThreadPool is** generally a **good choice**, as it demands no configuration and generally “does the right thing.” But a cached thread pool is **not a good choice** for a **heavily loaded production server**! > > In a **cached thread pool**, **submitted tasks are not queued** but immediately handed off to a thread for execution. **If no threads are available, a new one is created**. If a server is so heavily loaded that all of its CPUs are fully utilized, and more tasks arrive, more threads will be created, which will only make matters worse. > > Therefore, **in a heavily loaded production server**, you are much better off using **Executors.newFixedThreadPool**, which gives you a pool with a fixed number of threads, or using the ThreadPoolExecutor class directly, **for maximum control.**"
Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()
[ "", "java", "multithreading", "concurrency", "executorservice", "threadpoolexecutor", "" ]
I am a TDD noob and I don't know how to solve the following problem. I have pretty large class which generates text file in a specific format, for import into the external system. I am going to refactor this class and I want to write unit tests before. How should these tests look like? Actually the main goal - do not break the structure of the file. But this does not mean that I should compare the contents of the file before and after?
I think you would benefit from a test that I would hesitate to call a "unit test" - although arguably it tests the current text-file-producing "unit". This would simply run the current code and do a diff between its output and a "golden master" file (which you could generate by running the test once and copying to its designated location). If there is much conditional behavior in the code, you may want to run this with several examples, each a different test case. With the existing code, by definition, all the tests should pass. Now start to refactor. Extract a method - or better, write a test for a method that you can envision extracting, a true unit test - extract the method, and ensure that all tests, for the new small method and for the bigger system, still pass. Lather, rinse, repeat. The system tests give you a safety net that lets you go forward in the refactoring with confidence; the unit tests drive the design of the new code. There are libraries available to make this kind of testing easier (although it's pretty easy even without them). See <http://approvaltests.sourceforge.net/>.
In such a case I use the following strategy: * Write a test for each method (just covering its default behavior without any error handling etc.) * Run a code coverage tool and find the blocks not covered by the tests. Write tests covering these blocks. * Do this until you get a code coverage of over 80% * Start refactoring the class (mostly generate smaller classes following the separation of concern principle). * Use Test Driven Development for writing the new classes.
Refactoring strategy for the class which generates specific text file
[ "", "c#", "unit-testing", "refactoring", "tdd", "" ]
How would I do this? The reason being I wanted to try some pygame out, but I have python 3 installed currently and have been learning with that. I'm also interested in trying out wxpython or something like that, but I haven't looked at their compatibilities yet. EDIT:: im on a windows vista 64-bit
If you are on Windows, then just install another version of Python using the installer. It would be installed into another directory. Then if you install other packages using the installer, it would ask you for which python installation to apply. If you use installation from source or easy\_install, then just make sure that when you install, you are using the one of the proper version. If you have many packages installed in your current python-3, then just make a zip backup of your current installation just in case.
Erm... yes. I just installed Python 3.0 on this computer to test it. You haven't specified your operating system, but I'm running Ubuntu 9.04 and I can explicitly specify the version of Python I want to run by typing `python2.5 myscript.py` or `python3.0 myscript.py`, depending on my needs.
Is it possible to install python 3 and 2.6 on same PC?
[ "", "python", "python-3.x", "" ]
There are many ways to do this but I feel like I've missed a function or something. Obviously `List == List` will use `Object.Equals()` and return `false`. If every element of the list is equal and present in the same location in the opposite list then I would consider them to be equal. I'm using value types, but a correctly implemented Data object should work in the same fashion (i.e I'm not looking for a shallow copied list, only that the *value* of each object within is the same). I've tried searching and there are similar questions, but my question is an equality of every element, in an exact order.
``` Enumerable.SequenceEqual<TSource> ``` [MSDN](http://msdn.microsoft.com/en-us/library/bb348567.aspx)
Evil implementation is ``` if (List1.Count == List2.Count) { for(int i = 0; i < List1.Count; i++) { if(List1[i] != List2[i]) { return false; } } return true; } return false; ```
What is the best way to check two List<T> lists for equality in C#
[ "", "c#", "linq", "list", "equality", "" ]
I am looking for a LAMPish/WAMPish experience. Something very transparent. Write the script, hit F5 and see the results. Very little, if any abstraction. SQLAlchemy and (maybe) some simple templating engine will be used. I need simple access to the environment - similar to the PHP way. Something like the COOKIE, SESSION, POST, GET objects. I don't want to write a middleware layer just to get some web serving up and running. And I do not want to deal with specifics of CGI. This is not meant for a very complex project and it is for beginning programmers and/or beginning Python programmers. An MVC framework is not out of the question. ASP.NET MVC is nicely done IMO. One thing I liked is that POSTed data is automatically cast to data model objects if so desired. Can you help me out here? Thanks! PS: I did not really find anything matching these criteria in older posts.
For low barrier to entry, [web.py](http://webpy.org/) is very very light and simple. Features: * easy (dev) deploy... copy web.py folder into your app directory, then start the server * regex-based url mapping * very simple class mappings * built-in server (most frameworks have this of course) * *very thin* (as measured by lines of code, at least) layer over python application code. Here is its **hello world**: ``` import web urls = ( '/(.*)', 'hello' ) app = web.application(urls, globals()) class hello: def GET(self, name): if not name: name = 'world' return 'Hello, ' + name + '!' if __name__ == "__main__": app.run() ``` As much as I like Werkzeug conceptually, writing wsgi plumbing in the Hello, World! is deeply unpleasant, and totally gets in the way of actually demoing an app. That said, web.py isn't perfect, and for big jobs, it's probably not the right tool, since: * routes style systems are (imho) better than pure regex ones * integrating web.py with other middlewares might be adventurous
[CherryPy](http://cherrypy.org) might be what you need. It transparently maps URLs onto Python functions, and handles all the cookie and session stuff (and of course the POST / GET parameters for you). It's not a full-stack solution like Django or Rails. On the other hand, that means that it doesn't lump you with a template engine or ORM you don't like; you're free to use whatever you like. It includes a WSGI compliant web server, so you don't even need Apache.
Python web framework with low barrier to entry
[ "", "python", "" ]
I have an application written in C# which uses Linq2SQL for communicating with the SQL Server. There are some queries that run a bit (very) slow, and I figure it probably need some indexes to speed things up. But I don't really know how to do that or on what or where or what I should or should not do. So I was thinking I could ask here, but then I discovered the program called *Database Engine Tuning Advisor* which I thought I could try out first. The problem is I can't get it to work. It is probably me who just doesn't know how to, but I just can't really figure this out. As far as I can see, I have done what I am supposed to according to the help files. 1. Open up *SQL Server Profiler*. 2. Start a new *Trace* using the *Tuning* template. 3. Start my application and do some things that generates SQL queries. 4. Close my application. 5. Stop the trace. 6. Save the trace as a *Trace file*. 7. Open *Database Engine Tuning Advisor* 8. Choose *File* as *Workload* and select the *Trace file* I saved earlier. 9. Select the databases that my application uses under *Select databases and tables to tune*. 10. Click on *Start Analysis*. This far I thought things were going ok. But when it finishes after a while short while, I get this: [![Progress](https://i.stack.imgur.com/SUUyl.jpg)](https://i.stack.imgur.com/SUUyl.jpg) And a completely empy *Recommendations* page. Event does not reference any tables? What does that mean (other than the obvious of course :p)? Have I misunderstood something about the process here? What is going on?
I think the reason you're not getting recommendations is because you don't have 'SHOWPLAN' permissions on your database. Grant the user you're running the analyzer that access and try again. Also, I see some "invalid object name" errors as well -- make sure the user you are running the analyzer as has the appropriate permissions to all of the tables involved.
There is another thing you can check if you get this error. If you're a numpty like me you may have forgotten to select the appropriate database on from he "Database for workload analysis" drop down on the General tab
SQL Server: Event does not reference any tables (Tuning Advisor warning)
[ "", "c#", "sql-server", "linq-to-sql", "performance", "sql-server-profiler", "" ]
How to prevent browsers from caching Ajax results? I have and event triggered Ajax script the displays results only when the browsers data has been cleared. *Tested in IE6 and Firefox 3.0.10*
Add a random query string to the URL you are sending. E.g. if the Ajax request is sent to "<http://www.xyz.com/a>" then add a random string at the end: "<http://www.xyz.com/a?q=39058459ieutm39>"
The random URL works, but it's kind of a hack. HTTP has solutions built in that should work. Try using the solution [indicated here](http://www.webreference.com/programming/javascript/rg33/). Basically, set the headers: ``` "Pragma": "no-cache", "Cache-Control": "no-store, no-cache, must-revalidate, post-check=0, pre-check=0", "Expires": 0, "Last-Modified": new Date(0), // January 1, 1970 "If-Modified-Since": new Date(0) ```
How to prevent Ajax/javascript result caching in browsers?
[ "", "javascript", "ajax", "caching", "" ]
I have a website that has user ranking as a central part, but the user count has grown to over 50,000 and it is putting a strain on the server to loop through all of those to update the rank every 5 minutes. Is there a better method that can be used to easily update the ranks at least every 5 minutes? It doesn't have to be with php, it could be something that is run like a perl script or something if something like that would be able to do the job better (though I'm not sure why that would be, just leaving my options open here). This is what I currently do to update ranks: ``` $get_users = mysql_query("SELECT id FROM users WHERE status = '1' ORDER BY month_score DESC"); $i=0; while ($a = mysql_fetch_array($get_users)) { $i++; mysql_query("UPDATE users SET month_rank = '$i' WHERE id = '$a[id]'"); } ``` **UPDATE (solution):** Here is the solution code, which takes less than 1/2 of a second to execute and update all 50,000 rows (make rank the primary key as suggested by Tom Haigh). ``` mysql_query("TRUNCATE TABLE userRanks"); mysql_query("INSERT INTO userRanks (userid) SELECT id FROM users WHERE status = '1' ORDER BY month_score DESC"); mysql_query("UPDATE users, userRanks SET users.month_rank = userRanks.rank WHERE users.id = userRanks.id"); ```
Make `userRanks.rank` an autoincrementing primary key. If you then insert userids into `userRanks` in descending rank order it will increment the `rank` column on every row. This should be extremely fast. ``` TRUNCATE TABLE userRanks; INSERT INTO userRanks (userid) SELECT id FROM users WHERE status = '1' ORDER BY month_score DESC; UPDATE users, userRanks SET users.month_rank = userRanks.rank WHERE users.id = userRanks.id; ```
My first question would be: why are you doing this polling-type operation every five minutes? Surely rank changes will be in response to some event and you can localize the changes to a few rows in the database *at the time when that event occurs*. I'm pretty certain the entire user base of 50,000 doesn't change rankings every five minutes. I'm assuming the `"status = '1'"` indicates that a user's rank has changed so, rather than setting this when the user triggers a rank change, why don't you calculate the rank at that time? That would seem to be a better solution as the cost of re-ranking would be amortized over all the operations. Now I may have misunderstood what you meant by ranking in which case feel free to set me straight.
Best way to update user rankings without killing the server
[ "", "php", "mysql", "optimization", "query-optimization", "ranking", "" ]
I was wondering if it was possible to create a view in a database then be able to link a Model to it?
Yes it's possible. Create the view as if it were a table and make sure that it adheres to all the cake rules for [creating tables](http://book.cakephp.org/1.2/en/The-Manual/Developing-with-CakePHP/Models.html#creating-database-tables). Then you can create a model, controller and view as you would with any other Table. It even comes up in the cake bake app as a normal Table. One of the nice things I found was when dealing with pagination/sorting across a very normalised database, cake becomes almost impossible to deal with. Thus you can combine all your complex joins into one database query which then plugs nicely into cake's world of pagination/sorting on one table which works like a charm.
If you use the property var $useTable in the Model you should be able to use a view. I have not tried it but I'm pretty sure it would work, but of course you cannot insert into it.
Can a model link to a View in the database instead of a table in CakePHP?
[ "", "php", "database", "cakephp", "model", "" ]
How are you formatting your `try..catch.finally` blocks? Especially when only wrapping it around a small amount of code, it blows everything and makes code pretty unreadable and unsightly in my opinion. Such as: ``` try { MyService service = new Service(); service.DoSomething(); return something; } catch (Exception ex) { LogSomething(); return somethingElse; } finally { MarkAsComplete(); service.Dispose(); } ``` These 7 lines of code turned into a 16-line mess. Any suggestions on better `try..catch..finally` formatting?
Actually, this reads very well to me. If your actual code looks a lot like this, then I really wouldn't worry about it. It is VERY clear what is happening. If your actual code is more complex, then consider breaking the blocks into well-named methods.
you can use a `using` block instead of an explicit `Dispose()`, or else you probability have to check for null before disposing it, `using` blocks does that for you. unfortunately it does increase nesting =/ ``` try { using(MyService service = new MyService()) { service.DoSomething(); return something; } } catch (SpecificException ex) { LogSomething(ex); return somethingElse; } finally { MarkAsComplete(); } ```
Formatting of hard to read try..catch..finally blocks?
[ "", "c#", "formatting", "try-catch-finally", "" ]
C++ comes with four built-in casts. 1. `static_cast` 2. `dynamic_cast` 3. `const_cast` 4. `reinterpret_cast` Not to meantion the frowned upon `C (style*)cast`. Additionally [boost](http://www.boost.org) supplies a [lexical\_cast](http://www.boost.org/doc/libs/release/libs/conversion/lexical_cast.htm), are there any other useful casts that you use or would like to exist?
My favorite and most loved cast is `implicit_cast`. It only succeeds if the types can be implicitly converted. Useful for conversion from some type into `void*` or from some derived class into a base (if you want to select a specific instance of an overloaded function or constructor) or to safely add const-qualifications and any other scenario where you really just need implicit conversions to happen and even `static_cast` is too powerful. Also read [How does C++ pick which overload to call](https://stackoverflow.com/questions/385556/how-does-c-pick-which-overloaded-function-to-call/394742#394742). [`boost/implicit_cast.hpp`](http://www.boost.org/doc/libs/1_39_0/boost/implicit_cast.hpp). You can add this to your code collection too, if you want ``` template<typename T> struct identity { typedef T type; }; template<typename Dst> Dst implicit_cast(typename identity<Dst>::type t) { return t; } ```
There's also the **function-style cast** which looks like a function or constructor call. This resolves to the constructor call for classes, and (more generally) to C-style casts for all other types. Examples: ``` int x = int(1.0); // equals `(int)1.0` string s = string("x"); // equals call to constructor ``` The call to a constructor can *also* be achived using an explicit cast (apart from the C-style cast which would also work): ``` string s = static_cast<string>("x"); // is the same as above! ```
What other useful casts can be used in C++
[ "", "c++", "casting", "" ]
``` File files[] = rootDir.listFiles(new FileFilter() { public boolean accept(File file) { if (file.isDirectory()) return true; String name = file.getName().toLowerCase(); if (name.endsWith(".zip") || name.endsWith(".jar") || name.endsWith(".z") || name.endsWith(".gz") || name.endsWith(".tar") || name.endsWith(".bz2") || name.endsWith(".bz")) return true; return false; } }); ``` As you can see, the code is dirty with "||" Do you know how to make it better?
With Java 6 or above, this is a perfect case for a [`FileNameExtensionFilter`](http://java.sun.com/javase/6/docs/api/javax/swing/filechooser/FileNameExtensionFilter.html)... except that it extends `javax.swing.filechooser.FileFilter` instead of implementing `java.io.FileFilter`. But it is trivial to write a wrapper for it: ``` File[] files = rootDir.listFiles(new FileFilter() { private final FileNameExtensionFilter filter = new FileNameExtensionFilter("Compressed files", "zip", "jar", "z", "gz", "tar", "bz2", "bz"); public boolean accept(File file) { return filter.accept(file); } }); ```
Why not use regular expressions? `static final Pattern p = Pattern.compile("\\.(zip|jar|z|gz)$");` and then `return p.matcher(name).find();`
Is there any better way to do filefilter for many ext?
[ "", "java", "string", "file-io", "filter", "" ]
I have a program that uses way too much memory for allocating numerous small objects on heap. So I would like to investigate into ways to optimize it. The program is compiled with Visual C++ 7. Is there a way to determine how much memory is actually allocated for a given object? I mean when I call *new* the heap allocates *not less than* the necessary amount. How can I find how much exactly has been allocated?
There is no exact answer, because some heap managers may use different amount of memory for sequential allocations of the same size. Also, there is (usually) no direct way to measure number of bytes the particular allocation took. You can approximate this value by allocating a certain number of items of the same size (say, 4096) and noting the difference in memory used. Dividing the later by the former would give you the answer. Please note that this value changes from OS to OS, and from OS version to OS version and sometimes Debug builds of your application may enable extra heap tracking, which increases the overhead. On some OSes users can change heap policies (i.e. use one heap allocator vs. another as default). Example: Windows and pageheap.exe Just FYI, the default (not LFH) heap on Windows 32-bit takes up: * sizeof(your\_type), rounded up to DWORD boundary, * 3 pointers for prev/next/size * 2 pointers for security cookies
You're probably looking to move to a memory pool model (which is what the previous answer about "allocating a large pool" was describing. Because memory pools do not require overhead for each allocation, they offer space savings for large numbers of small objects. If the lifetime of a group of those small objects is short (i.e. you allocate a bunch of small objects then need to get rid of the lot), a memory pool is also much faster because you can just free the pool instead of each object. Wikipedia has some info on the technique as well as a link to a few implementations: <http://en.wikipedia.org/wiki/Memory_pool> you should be able to find other implementations with a simple web search.
How much memory was actually allocated from heap for an object?
[ "", "c++", "visual-c++", "memory", "memory-management", "" ]
I have created setup project with Visual Studio. I also need some custom actions - created DLL with Visual c++ and it works just fine but i don't want to include visual c++ runtime files to my project. So is it possible to build this dll with some other c++ compiler? I have tried to make make it with Dev-c++ but when compiling i get few hundred compilation errors from files msi.h and msiquery.h
Probably the easiest solution is to link your DLLs against the static runtime lib.
In general custom action DLLs should only rely on DLLs that are already in the system before the installation. This means, for example, statically linking the CRT, as noted by MSalters, but also applies to any other dependency on 3rd party libraries. Another option is to link with the OS CRT, as Koby Kahane explains [here](http://kobyk.wordpress.com/2007/07/20/dynamically-linking-with-msvcrtdll-using-visual-c-2005/).
Does custom action dll-s for msi installer have to be created with Visual Studio only?
[ "", "c++", "windows-installer", "custom-action", "" ]
``` function icPageInit() { $("icImgDiv" + icAlternate()).setOpacity(0); return true; } window.onload = icPageInit; ``` This piece of Javascript code works fine in Firefox and Chrome, but fails with the error 'Object Expected' in Internet Explorer 8. IE8 says the error occurs on line 3 of the above code. Does anyone know why this is happening, and/or how to get it working?
Figured it out. Turns out Internet Explorer chokes if you use anything other than `"javascript"` in the `language` attribute of the `script` tag. I was using version numbers appended onto `javascript` in the `language` attribute, which was causing IE not to load `prototype.js`.
Are you sure that this: *$("icImgDiv" + icAlternate())* returns a reference to an element? If so, have you tried using Microsoft Script Debugger / Visual Studio to debug when and where the exception is raised?
'Object Expected' Javascript error in IE8 when using prototype.js
[ "", "javascript", "internet-explorer", "internet-explorer-8", "prototypejs", "object-expected", "" ]
I am able to set bookmarks in a source file, but are there shortcut keys to navigate to a bookmark ? The **navigate** menu has a goto line. But that is not useful.
There is not a shortcut key but you can make appear a 'Bookmark view' which is located in *Window > Show view > Other...* and in the dialog inside the *General* classification, Then just double-click on the desired bookmark to reach it
If you check the "Bookmark" item in the "Next Annotation"/"Previous Annotation" toolbar dropdown item, you can use `Ctrl+,` and `Ctrl+.` to navigate to previous/next bookmark in the current opened file. ![toolbar](https://i.stack.imgur.com/ggUvV.png) from [Tutorial](http://www.vogella.com/articles/Eclipse/article.html#sourcenavigation_annotations)
How to navigate to a bookmark in eclipse 3.4.1?
[ "", "java", "eclipse", "editor", "bookmarks", "" ]
I am trying to install sqlite3 for PHP in Ubuntu. I install `apt-get php5-sqlite3` and edited `php.ini` to include sqlite3 extension. When I run `phpinfo();` I get ``` SQLITE3 SQLite3 support enabled sqlite3 library version 3.4.2 ``` as shown above, `sqlite3` is enabled. However, I get "Class SQLite3 not found" when I use ``` new SQLite3("database"); ```
**Edit: This answer is outdated, but can't be removed because it's accepted. Please see the solution from Stacey Richards for the correct answer.** ``` sudo apt-get install php5-cli php5-dev make sudo apt-get install libsqlite3-0 libsqlite3-dev sudo apt-get install php5-sqlite3 sudo apt-get remove php5-sqlite3 cd ~ wget http://pecl.php.net/get/sqlite3-0.6.tgz tar -zxf sqlite3-0.6.tgz cd sqlite3-0.6/ sudo phpize sudo ./configure sudo make sudo make install sudo apache2ctl restart ``` Ripped from the [ubuntu form](http://ubuntuforums.org/showthread.php?t=891767).
Try: ``` apt-get install php5-sqlite ``` That worked for me.
how to enable sqlite3 for php?
[ "", "php", "sqlite", "" ]
Well im new to javascript but why does this not work, all i want to do is to get a list of all selects on the page. ``` var elements = document.getElementsByTagName("select"); alert("there are " + elements.length + " select's"); for (i = 0; i < elements.length; i++) { alert(elements[i].getAttribute('Id')); } ``` Edit: the error is that it does not find any selects at all, elements.length is allways zero!
You'r saying that elements.length is always returning **0** for you, this could be because: * You are running the JS code in the beginning of your page, thus the DOM is not fully available yet
Try using `.id` instead of of `getAttribute('Id')`.
JavaScript, loop all selects?
[ "", "javascript", "dom", "" ]
I have a textbox, and it needs not allow the user to enter any special characters. He can enter: 1. A-Z 2. a-z 3. 0-9 4. Space. One more condition is the first letter should be alphabetic. How can I do a JavaScript verification on each keypress?
add a onKeyUp="javascript:checkChar(this);" to the input box. ``` function checkChar(tBox) { var curVal = tBox.value; if ( /[^A-Za-z0-9 ]/.test(curVal) ) { //do something because he fails input test. } } ``` alernatively to check JUST the key that was pressed you can grab the keycode from the event like so: onKeyUp="javascript:checkChar(event);" ``` function checkChar(e) { var key; if (e.keyCode) key = e.keyCode; else if (e.which) key = e.which; if (/[^A-Za-z0-9 ]/.test(String.fromCharCode(key))) { //fails test } } ``` missed the part about first char, but you can do a test on the textbox value as in the first example: ``` /^[A-Za-z]/.test(curVal) ``` or even use the second method but pass the text box as well so you can get it's full value.
This function will check the string given to it for those criteria: ``` function checkvalue(value) { return value.match( /[A-Za-z][A-Za-z0-9 ]*/ ); } ``` You can then use that in an onkeypress event, passing in the current value.
Textbox with alphanumeric check in javascript
[ "", "asp.net", "javascript", "" ]
I have this class: ``` public class Test { public static void main(String[] args) { System.out.println("Hello World!"); } } ``` And I used Eclipse's "Export to runnable JAR" function to make it into a executable jar-file (test.jar). When I run this program in Eclipse, it prints out "Hello World!", but when I call the jar-file from the command line, nothing happens. I have tried calling the jar-file like this: ``` test.jar test.jar -jar ``` There is no output whatsoever. I have another program that also has a side effect (in addition to output to stdout) and while the side effect is being performed (which tells me the jar-file was definitely executed), again no output is given to the command line. I have also tried using stderr, but that makes no difference. Does anybody know how I can make this work? Thanks!
You must *run* the JAR using ``` java -jar test.jar ``` (Your JRE's bin folder must be added to PATH in order to get the command working from any location) NOTE: I know you created the JAR using Eclipse but you might want to know [how does an *executable* JAR works](http://www.skylit.com/javamethods/faqs/createjar.html)
The previous answers are correct, so I'll just clarify a bit the "executable jar" concept. There's no such thing as an "executable jar", equivalent to an exe file in windows, in an "executable jar" you'll be only specifying the "entry" point ( your main class you want to be executed by default ) A jar is basically just an archive, you'll still need java to actually launch the jar ( java -jar your.jar ) The fact that in windows you might have an association with javaw.exe means this will be launched by the OS when you double-click on the jar, like a .txt file being opened automatically with notepad, it doesn't make the .txt an executable file. Check this out as well : [JAR files revealed](http://www.ibm.com/developerworks/library/j-jar/index.html)
System.out not working when calling jar-file from Windows command line
[ "", "java", "eclipse", "jar", "executable-jar", "" ]
I remember in college taking a database class where we, the students, were given the ability to choose our Database Management System. Being my first experience with databases I remember being confused that there were different syntax to the SQL statements depending upon which Database Management System used. Up until this class I was under the impression that the SQL language was a universal language that a user could use to communicate with all databases. So what's the deal? Is there a defined SQL standard? If so, why does Database Management System manufactures differ from the specification? Was the standard designed incomplete with the idea that companies would use it as a foundation for their extensions to the language? Was the original SQL standard outdated and manufacturers needed to build more functionality? Is/was the original not updated at a pace to stay current with modern application needs? Was it to create a business model for revenue? Thanks.
Yes, there are SQL ANSI standards, see e.g. [a draft of the SQL-92 one](http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt). However, every database vendor implements "an extended subset" of standard SQL -- and if you think about it, anything is an "extended subset" of anything else, in a sense;-). No doubt there are commercial reasons behind this, but even non-commercial implementations such as PostgreSQL behave much the same...
There are SQL standards: <http://en.wikipedia.org/wiki/SQL#Standardization> However, most DBMSs still implement a somewhat custom or extended version of the standard. (Microsoft SQL Server being the prime suspect).
Is there a defined and accepted standard SQL language?
[ "", "sql", "database", "" ]
I have a the query: ``` SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age FROM availables INNER JOIN rooms ON availables.room_id=rooms.id WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094 GROUP BY availables.bookdate ``` Which returns something like: ``` Date Age 2009-06-25 0 2009-06-26 2 2009-06-27 1 2009-06-28 0 2009-06-29 0 ``` How can I then do a Count on the number of rows which is returned.. (in this case 5) and an SUM of the Ages? To return just one row with the Count and the SUM? ``` Count SUM 5 3 ``` Thanks
Usually you can plug a Query's result (which is basically a table) as the FROM clause source of another query, so something like this will be written: ``` SELECT COUNT(*), SUM(SUBQUERY.AGE) from ( SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age FROM availables INNER JOIN rooms ON availables.room_id=rooms.id WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094 GROUP BY availables.bookdate ) AS SUBQUERY ```
You just wrap your query in another one: ``` SELECT COUNT(*), SUM(Age) FROM ( SELECT availables.bookdate AS Count, DATEDIFF(now(),availables.updated_at) as Age FROM availables INNER JOIN rooms ON availables.room_id=rooms.id WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094 GROUP BY availables.bookdate ) AS tmp; ```
Performing a query on a result from another query?
[ "", "sql", "select", "count", "aggregate", "sum", "" ]
A very basic question, but still, it would be good to hear from C++ gurus out there. There are two rather similar ways to declare by-reference parameters in C++. 1) Using "asterisk": ``` void DoOne(std::wstring* iData); ``` 2) Using "ampersand": ``` void DoTwo(std::wstring& iData); ``` What are implications of each method? Are there any gotcha's in any case? Bonus #1: What would be a formal way to call method in #1 and #2? Are they both called "by-reference"? Bonus #2: std::wstring is used deliberately. What would be implications towards standard library classes in each case?
#1 uses a pointer parameter ('passing a pointer to'), #2 uses a reference parameter ('passing by reference'). They are very similar, but note that the calling code looks different in the two cases: ``` std::wstring s; DoOne(&s); // pass a pointer to s DoTwo(s); // pass s by reference ``` Some people prefer #1, using a convention that passing by pointer indicates that the function might change the value of s (even though either function could). Other people (myself included) prefer #2, since passing by reference does not allow NULL to be passed. There is another important difference when passing by `const` pointer or reference. A temporary variable can only be passed to a const reference parameter: ``` void ByConstPointer(const std::wstring&); void ByConstReference(const std::wstring*); void test() { ByConstPointer(&std::wstring(L"Hello")); // error: cannot take address of temporary ByConstReference(std::wstring(L"Hello")); // fine } ```
Rule number one for this: If NULL is a valid value for the function parameter in the context of the function, then pass it as pointer, otherwise pass it as reference. Rationale, if it cannot (should not!) ever be NULL, then don't put yourself through the trouble of checking for NULL.
What are the differences between parameter definitions as (type& name), and (type* name)?
[ "", "c++", "argument-passing", "" ]
I have a table with multiple readings\_miu\_id's each with multiple RSSI readings (RSSI is also the name of the field). So, i currently have a datasheet, with many columns, but the two pertinent ones to this conversation look something like this: ``` readings_miu_id RSSI =============== ==== 11011032 -90 11011032 -81 11011032 -62 11011032 -84 11011032 -86 11010084 -84 11010084 -86 11010084 -87 ``` and so on. My original plan was to change the value of RSSI for each record having the same readings\_miu\_id with the average RSSI for that readings\_miu\_id (which should look the same as above except that the individual RSSI's will be replaced by the average RSSI for that miu), and then pull only one record for each distinct readings\_miu\_id (which I'm pretty sure I can do with the select top 1 type statement.) However I'm having problems figuring the first part out. The sql statements I've tried that seem like they should be close are: ``` UPDATE analyzedCopy2 as A SET analyzedCopy2.RSSI = Avg(RSSI) where readings_miu_id = A.readings_miu_id ``` and ``` UPDATE analyzedCopy2 as A SET RSSI = Avg(select RSSI from analyzedCopy2 where readings_miu_id = A.readings_miu_id) WHERE readings_miu_id = A.readings_miu_id; ``` Help please!
Not sure why you want to update the records. If you just want an avg reading you can do this: ``` SELECT readings_miu_id, AVG(RSSI) FROM analyzedCopy2 GROUP BY readings_miu_id ```
Please see this [question](https://stackoverflow.com/questions/839938/mysql-sql-update-with-correlated-subquery-from-the-updated-table-itself), where a similar scenario is discussed. The query you are looking for is something like this (I don't have an SQL shell here so there may be slight syntax problems): ``` UPDATE analyzedCopy2 AS target INNER JOIN ( select avg(RSSI) as AvgRSSI, readings_miu_id from analyzedCopy2 T group by readings_miu_id ) as source ON target.readings_miu_id = source.readings_miu_id SET target.RSSI = source.AvgRSSI ```
Using Avg() with SQL update
[ "", "sql", "ms-access", "sql-update", "" ]
I am a beginner to WPF Databinding and I just found a confusing kind of behaviour. Maybe someone can help me: My xaml code binds a listbox to a list: ``` <ListBox ItemsSource="{Binding Path=Axes}" SelectedItem="{Binding Path = SelectedAxis}" DisplayMemberPath = "Name" Name="listboxAxes"/> ``` If the actual item that is bound to is an List everything works as expected. But when I change to KeyedCollection there occurs an update problem. Calls to NotifyPropertychanged("Axes") does NOT update the ListBox as a whole. Any ideas about this?
If whatever Axes is collecting isn't a class with it's own Name property then the DisplayMemberPath="Name" property may be causing you to not see anything. Using a KeyedCollection as an ItemsSource is perfectly fine though. The ItemsSource property is the [ItemsControl.ItemsSource](http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemssource.aspx) property. And it merely requires that whatever it's bound to implements IEnumerable. [KeyedCollection](http://msdn.microsoft.com/en-us/library/ms132438.aspx) does implement IEnumerable, as it implements Collection. Here's a short sample using a KeyedCollection: ``` <Grid> <DockPanel x:Name="QuickListButtonsStackPanel"> <Button DockPanel.Dock="Top" Content="Load Animals" Click="AnimalButtonClick" /> <Button DockPanel.Dock="Top" Content="Load Objects" Click="ObjectButtonClick" /> <TextBlock DockPanel.Dock="Bottom" Background="Azure" Text="{Binding SelectedExample}" /> <ListBox x:Name="uiListBox" ItemsSource="{Binding Examples}" SelectedItem="{Binding SelectedExample}" /> </DockPanel> </Grid> ``` And the code for our Window & KeyedCollection: ``` public partial class Window1 : Window, INotifyPropertyChanged { public Window1() { InitializeComponent(); this.DataContext = this; } public KeyedCollection<char, string> Examples { get; set; } private string mySelectedExample; public string SelectedExample { get { return this.mySelectedExample; } set { this.mySelectedExample = value; this.NotifyPropertyChanged("SelectedExample"); } } private void AnimalButtonClick(object sender, RoutedEventArgs e) { Examples = new AlphabetExampleCollection(); Examples.Add("Ardvark"); Examples.Add("Bat"); Examples.Add("Cat"); Examples.Add("Dingo"); Examples.Add("Emu"); NotifyPropertyChanged("Examples"); } private void ObjectButtonClick(object sender, RoutedEventArgs e) { Examples = new AlphabetExampleCollection(); Examples.Add("Apple"); Examples.Add("Ball"); Examples.Add("Chair"); Examples.Add("Desk"); Examples.Add("Eee PC"); NotifyPropertyChanged("Examples"); } #region INotifyPropertyChanged Members private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } public event PropertyChangedEventHandler PropertyChanged; #endregion } public class AlphabetExampleCollection : KeyedCollection<char, string> { public AlphabetExampleCollection() : base() { } protected override char GetKeyForItem(string item) { return Char.ToUpper(item[0]); } } ``` The other issue that may be occurring is if you are just adding/removing items from the collection, and not re-setting the collection. In the example above, you can see that we are re-instating the keyed collection. If we didn't do this, then just calling NotifyPropertyChanged wouldn't do anything. Lets add in two more buttons to demonstrate this: ``` <Button DockPanel.Dock="Top" Content="Add Zebra" Click="AddZebraClick" /> <Button DockPanel.Dock="Top" Content="Add YoYo" Click="AddYoYoClick" /> ``` And the Hanlders: ``` private void AddZebraClick(object sender, RoutedEventArgs e) { Examples.Add("Zebra"); NotifyPropertyChanged("Examples"); } private void AddYoYoClick(object sender, RoutedEventArgs e) { Examples.Add("YoYo"); NotifyPropertyChanged("Examples"); } ``` Both of these, as is **will not work**. When you call NotifyPropertyChanged the property has to actually be changed. And in this case, it is not. We've modified it's items, but the Examples collection is still the same collection. To fix this we could cycle the collection as we did in the first part, or if we have access to the UI, we could call: ``` uiListBox.Items.Refresh(); ``` We could also cycle the DataSource, we could cycle the ListBox's ItemsSource, or we could clear and re-assign the binding but just calling UpdateTarget() won't do it however.
Try calling `listboxAxes.Items.Refresh()`. That helps sometimes.
DataBinding wpf KeyedCollection
[ "", "c#", "wpf", "data-binding", "xaml", "" ]
Web server running in Dutch(Belgium) ``` double output; double.TryParse(txtTextbox1.Text, out output); ``` Is this a good way to convert text to double in dutch environment? Let's say the input is "**24.45**" instead of "**24,45**"
If you want to use the Dutch (Belgium) number format: ``` double output; double.TryParse("24,45", NumberStyles.Any, CultureInfo.GetCultureInfo("nl-BE"), out output); ``` Or to use the US number format: ``` double output; double.TryParse("24.45", NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out output); ``` If you attempt to parse "24.45" with a Dutch culture set, you'll get back "2445", similarly, if you attempt to parse "24,45" with a US culture, you'll get "2445". If you want the parse to fail if the wrong decimal point is used, change NumberStyles.Any to exclude the flag: `NumberStyles.AllowThousands`: ``` double output; if (double.TryParse("24.45", NumberStyles.Any ^ NumberStyles.AllowThousands, CultureInfo.GetCultureInfo("nl-BE"), out output)) ``` If your entire application is in Dutch, you should change your cultureinfo globally - [here's how to do it in WinForms](http://www.sisulizer.com/online-help/ActionMessageNetUiLocale.htm) and [here's how to do it in ASP.NET](http://msdn.microsoft.com/en-us/library/bz9tc508.aspx). Once you're using a globally set CultureInfo, you can change the above code to: ``` double output; double.TryParse("24.45", NumberStyles.Any, CultureInfo.CurrentCulture, out output); ```
The correct Culture Code for dutch-Belgium is "nl-BE", so you should use that instead of the often suggested "nl-NL", which would give you the variant of Dutch culture settings appropriate for the Netherlands. ``` double output; double.TryParse("24.45", NumberStyles.Any, CultureInfo.GetCultureInfo("nl-BE"), out output); ``` You can find a complete list of Culture Codes at <http://arvindlounge.spaces.live.com/blog/cns!C9061D5B358A2804!263.entry> .
double.TryParse in dutch
[ "", "c#", "" ]
Hey everyone, I am getting a heap corruption error I cannot figure out. ``` char * c = (char *) malloc(1); // main loop _gcvt_s(c, 100, ball->get_X_Direction(), 10); if(pushFont(c, (SCREEN_WIDTH - 30), (SCREEN_HEIGHT - 40), message, screen, font, textColor) == false) { //return 1; // error rendering text. } // end main loop free(c); ``` The above code is the only time I use c pointer, in \_gcvt\_s and pushFont() which simply accepts a char \* as its first parameter, and puts the text on the screen. Other then that I do not use c. When I try to free c after the main loop (which I think I am supposed to do), I get an error saying Visual Studio has acquired an error with the heap (heap corruption). Commenting out the call to pushFont I still receive the error. Can anyone explain to me why freeing a character (the 1 byte I allocated on the heap) would give me a heap corruption? Lastly my main loop does a lot of stuff, a buddy and I are making a pong game with WinSocket, the rest of the main body is the loop for the game. I didnt think it was necessary to post, but I will update my post with the entire main loop if it is necessary, but I believe I am just off with my understanding of malloc() and free(). Thanks all,
Doesn't \_gcvt\_s use the 2nd parameter as the max size of the allocated buffer? You allocate 1 byte but tell \_gcvt\_s there are 100. So it happily writes up to 100 bytes into the buffer corrupting your heap. Then the free crashes. Allocate 100 bytes if you are going to potentially access 100 bytes. EDIT: It sounds like you need to learn how C stores and manipulates strings. C stores strings as individual bytes in contiguous runs of memory followed by an extra character to indicate the end of the string. This extra character has an ASCII value of 0 (not the character '0' which is ASCII 48). So if you have a string like "HELLO", it takes 6 bytes to store - one for each of the 5 letters and the terminator. In order for \_gcvt\_s() to return the value to your buffer, you need to include enough bytes for the conversion and the extra terminating byte. In the case of \_gcvt\_s(), you are asking for 10 characters of precision. But you also have to reserve room for the decimal point, the potential negative sign. According to this [documentation](<http://msdn.microsoft.com/en-us/library/a2a85fh5(VS.80).aspx)>, there is a #define in the headers for the maximum necessary size of the buffer: \_CVTBUFSIZE. The example there should help you with this issue.
According to the documentation I can find `_gcvt_s()` takes a buffer and the length of that buffer as the first two arguments. ``` errno_t _gcvt_s( char *buffer, size_t sizeInBytes, double value, int digits ); ``` Your `malloc()`ed buffer is 1 byte long, you tell `_gcvt_s()` it is 100 bytes long. I would start looking here.
allocating and freeing a char * in c++
[ "", "c++", "malloc", "heap-memory", "free", "" ]
jQuery and similar libraries provide a number of useful APIs for DOM traversal and manipulation. Where your site as high number of repeat visitors, their use is easily justified as caching will offset any bandwidth cost to the end user. In other cases visitors to the site might always be unique and thus the bandwidth penalty for these libraries can be too severe relative to the benefits for a development team. Are there any libraries that provide this style of DOM interaction while allowing you to choose the parts relevant to your page. For example, ``` jQuery('#myId').addClass('error'); ``` and many other APIs in jQuery can be replicated in a few lines of code, thus avoiding ~50kB of downloads. So the question is, does a library exist that contains these functions with little dependency on other aspects of the library or will I need to create them myself as necessary? Are there mechanisms/tools available to break down existing libraries like jQuery into their minimal components?
As discussed [here](https://stackoverflow.com/questions/936399/should-i-link-to-google-apis-cloud-for-js-libraries/936419#936419), if you use google as a host of the libraries, the user probably already has it cached before they ever get to your site. [This page](http://code.google.com/apis/ajaxlibs/) shows you which libraries are supported. Currently: * jQuery * jQuery UI * Prototype * script.aculo.us * MooTools * Dojo * SWFObject *New!* * Yahoo! User Interface Library (YUI) *New!* --- I'm all for rolling your own, but be sure you know all the bugs of all the browser versions if you don't use a library. Not a bad idea, though. It would be nice if you could create a custom version of jQuery. I'd especially like one for iPhone's Mobile Safari and Adobe AIR that stripped out all the non-webkit stuff.
The production version of jQuery is 19k, same as a rather small image. Not a severe bandwidh penalty in my book! **Edit**: ..and worth every k, too.
Modular Javascript library with functionality similar to jQuery
[ "", "javascript", "jquery", "dom", "" ]
I am writing a API over the top of a COM object and you have to pass around the COM object into pretty much every type and static method that I write so that I can test each part of my API. Now my question is do I have an overloaded method for the one that takes the COM object but pass the IoC resolved one instead to the other one instead, so that the users of the API don't have to worry about passing in the COM object or should I remove the overloaded method and just resolve it with out the option to pass it in. Bit hard to explain so here is an example; **Constuctor Example;** ``` FooType(IComObject obj,string table) {} FooType(string table) : this(Ioc.Resolve<IComObject>(), table) {} ``` or just ``` FooType(string table) : this(Ioc.Resolve<IComObject>(), table) {} ``` **Static method example;** ``` public static SomeType Create(IComObject obj,string table) { // Do some work with obj} public static SomeType Create(string table) { return MyClass.Create(Ioc.Resolve<IComObject>(),table); } ``` or just ``` public static SomeType Create(string table) { IComObject obj = Ioc.Resolve<IComObject>(); return MyClass.Create(Ioc.Resolve<IComObject>(),table); } ``` My biggest worry with the overloading is that it's going to create a lot of methods that just froward calls. What other options do I have here or is this correct way of tackling this? P.S I really don't want to burden the user with having to pass a instance of IComObject all around their application.
One of the principles of Dependency Injection is that dependencies of a class should be made explicit to the outside world. When a class resolves a dependency itself (as in your second example) it goes against that principle, and is headed back down the road of using singleton services - though admittedly you are somewhat better off because you do have the IoC container as an "escape hatch" for mocking the service objects. Obviously having a whole load of parameters in the constructors of all your objects is rather burdensome, but that's where the IoC Container steps in. If it supports auto-wiring, and you're using it as it was designed, you usually find yourself having to resolve very few instances yourself: you pull the first object out, and it comes ready-configured with all its dependencies - and they're ready configured with all their dependencies, and so on. For this reason, Joshua Flanagan [makes the argument](http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/06/09/let-your-inversion-of-control-tool-work-for-you.aspx) that IoC Containers really ought to be called IoC Composers. If you want to avoid burdening the users of your API, how about having a focal object that wraps up your IoC container and pulls configured instances out of it for consumption by calling code?
From my point of view, unless you have a compelling reason to allow the overload, having both (overload and resolution) will unnecessarily complicate your API and lead too potential gotchas for your users. I think you have answered your own question when you said "P.S I really don't want to burden the user".
Having overload methods that use IoC container
[ "", "c#", "dependency-injection", "inversion-of-control", "" ]
Consider the code below: ``` DummyBean dum = new DummyBean(); dum.setDummy("foo"); System.out.println(dum.getDummy()); // prints 'foo' DummyBean dumtwo = dum; System.out.println(dumtwo.getDummy()); // prints 'foo' dum.setDummy("bar"); System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo' ``` So, I want to copy the `dum` to `dumtwo` and change `dum` without affecting the `dumtwo`. But the code above is not doing that. When I change something in `dum`, the same change is happening in `dumtwo` also. I guess, when I say `dumtwo = dum`, Java copies the **reference only**. So, is there any way to create a fresh copy of `dum` and assign it to `dumtwo`?
Create a copy constructor: ``` class DummyBean { private String dummy; public DummyBean(DummyBean another) { this.dummy = another.dummy; // you can access } } ``` Every object has also a clone method which can be used to copy the object, but don't use it. It's way too easy to create a class and do improper clone method. If you are going to do that, read at least what Joshua Bloch has to say about it in *[Effective Java](http://books.google.com/books?id=ka2VUBqHiWkC&pg=PA55&lpg=PA55&dq=effective+java+clone&source=bl&ots=yXGhLnv4O4&sig=zvEip5tp5KGgwqO1sCWgtGyJ1Ns&hl=en&ei=CYANSqygK8jktgfM-JGcCA&sa=X&oi=book_result&ct=result&resnum=3#PPA54,M1)*.
**Basic:** Object Copying in Java. Let us Assume an object- `obj1`, that contains two objects, **containedObj1** and **containedObj2**. ![enter image description here](https://i.stack.imgur.com/ZK4pQ.gif) **shallow copying:** shallow copying creates a new `instance` of the same class and copies all the fields to the new instance and returns it. **Object class** provides a `clone` method and provides support for the shallow copying. ![enter image description here](https://i.stack.imgur.com/xhF9B.gif) **Deep copying:** A deep copy occurs when *an object is copied along with the objects to which it refers*. Below image shows `obj1` after a deep copy has been performed on it. *Not only has `obj1` been copied*, but the objects contained within it have been copied as well. We can use `Java Object Serialization` to make a deep copy. Unfortunately, this approach has some problems too([detailed examples](http://javatechniques.com/blog/faster-deep-copies-of-java-objects/)). ![enter image description here](https://i.stack.imgur.com/mtNjt.gif) **Possible Problems:** `clone` is tricky to implement correctly. It's better to use [Defensive copying](http://www.javapractices.com/topic/TopicAction.do?Id=15), [copy constructors](http://www.javapractices.com/topic/TopicAction.do?Id=12)(as @egaga reply) or [static factory methods](http://www.javapractices.com/topic/TopicAction.do?Id=21). 1. If you have an object, that you know has a public `clone()` method, but you don’t know the type of the object at compile time, then you have problem. Java has an interface called `Cloneable`. In practice, we should implement this interface if we want to make an object `Cloneable`. `Object.clone` is **protected**, so we must *override* it with a public method in order for it to be accessible. 2. Another problem arises when we try **deep copying** of a *complex object*. Assume that the `clone()` method of all member object variables also does deep copy, this is too risky of an assumption. You must control the code in all classes. For example [org.apache.commons.lang.SerializationUtils](http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/SerializationUtils.html#clone%28java.io.Serializable%29) will have method for Deep clone using serialization([Source](http://www.jarvana.com/jarvana/view/commons-lang/commons-lang/2.4/commons-lang-2.4-sources.jar!/org/apache/commons/lang/SerializationUtils.java?format=ok)). If we need to clone Bean then there are couple of utility methods in [org.apache.commons.beanutils](http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/BeanUtils.html) ([Source](http://grepcode.com/file/repo1.maven.org/maven2/commons-beanutils/commons-beanutils/1.8.0/org/apache/commons/beanutils/BeanUtils.java)). * `cloneBean` will Clone a bean based on the available property getters and setters, even if the bean class itself does not implement Cloneable. * `copyProperties` will Copy property values from the origin bean to the destination bean for all cases where the property names are the same.
How do I copy an object in Java?
[ "", "java", "object", "copy", "clone", "" ]
I want to set user date format yyyyMMdd using culture name. Which culture name have to specify to accomplish this?
Why wouldn't you use the format specifier? ``` string s = DateTime.Today.ToString("yyyyMMdd"); ``` I'm not aware of any pre-rolled cultures that use this specifier. You could perhaps roll your own culture?
You can create your own culture using the CultureAndRegionInfoBuilder class (in assembly *sysglobl*). But it may be overkill for your need... Another, simpler solution : create a new instance of CultureInfo based on the current culture, and assign it a custom DateTimeFormatInfo : ``` DateTimeFormatInfo dtfi = new DateTimeFormatInfo(); dtfi.ShortDateTimePattern = "yyyyMMdd"; CultureInfo ci = new CultureInfo(CultureInfo.CurrentCulture.Name); ci.DateTimeFormat = dtfi; ```
Setting Date format yyyyMMdd through specify Culture Name
[ "", "c#", "asp.net", "date", "format", "culture", "" ]