Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have two parallel inheritance chains: ``` Vehicle <- Car <- Truck <- etc. VehicleXMLFormatter <- CarXMLFormatter <- TruckXMLFormatter <- etc. ``` My experience has been that parallel inheritance hierarchies can become a maintenance headache as they grow. i.e. NOT adding `toXML(), toSoap(), toYAML()` methods to my principal classes. How do I avoid a parallel inheritance hierarchy without breaking the concept of separation of concerns?
I am thinking of using the Visitor pattern. ``` public class Car : Vehicle { public void Accept( IVehicleFormatter v ) { v.Visit (this); } } public class Truck : Vehicle { public void Accept( IVehicleFormatter v ) { v.Visit (this); } } public interface IVehicleFormatter { public void Visit( Car c ); public void Visit( Truck t ); } public class VehicleXmlFormatter : IVehicleFormatter { } public class VehicleSoapFormatter : IVehicleFormatter { } ``` With this, you avoid an extra inheritance tree, and keep the formatting logic separated from your Vehicle-classes. Offcourse, when you create a new vehicle, you'll have to add another method to the Formatter interface (and implement this new method in all the implementations of the formatter interface). But, I think that this is better then creating a new Vehicle class, and for every IVehicleFormatter you have, create a new class that can handle this new kind of vehicle.
Another approach is to adopt a push model rather than a pull model. Typically you need different formatters because you're breaking encapsulation, and have something like: ``` class TruckXMLFormatter implements VehicleXMLFormatter { public void format (XMLStream xml, Vehicle vehicle) { Truck truck = (Truck)vehicle; xml.beginElement("truck", NS). attribute("name", truck.getName()). attribute("cost", truck.getCost()). endElement(); ... ``` where you're pulling data from the specific type into the formatter. Instead, create a format-agnostic data sink and invert the flow so the specific type pushes data to the sink ``` class Truck implements Vehicle { public DataSink inspect ( DataSink out ) { if ( out.begin("truck", this) ) { // begin returns boolean to let the sink ignore this object // allowing for cyclic graphs. out.property("name", name). property("cost", cost). end(this); } return out; } ... ``` That means you've still got the data encapsulated, and you're just feeding tagged data to the sink. An XML sink might then ignore certain parts of the data, maybe reorder some of it, and write the XML. It could even delegate to different sink strategy internally. But the sink doesn't necessarily need to care about the type of the vehicle, only how to represent the data in some format. Using interned global IDs rather than inline strings helps keep the computation cost down (only matters if you're writing ASN.1 or other tight formats).
Avoiding parallel inheritance hierarchies
[ "", "java", "oop", "inheritance", "anti-patterns", "" ]
How do You manage all of Your `.js` and `.css` files in ASP.NET project? Especially when they have a lot of dependency between each other? I've combined all script in one. But it's become weighty, and 90% of them were not used on particular pages. What I want is an instrument or guidance to manage all of those scripts, simple dependency management, that help to include on page only those JS and CSS that needed on this page. Also used ScriptManager nut when You use a lot of controls it's very handy.... maybe I'm using it in the wrong way.
I prefer to divide my JS files based on their function - for instance, I could have a single JS file for all AJAX based interaction, one for all Validations and a common JS library for all functions that are common to the entire web application. Having a single file that combines the entire JS scripts into one would definitely slow down the application because each page would load the entire file, even though only a small portion might be relevant. For CSS files, I prefer to have a single common stylesheet that would contain the general styles available to the entire application. I might also create individual CSS files for pages that have a very specific layout structure. I don't know of any tools that could handle this dependency automatically, but When you divide your files according to function, this becomes unnecessary in most cases.
On our projects, we tag the scripts and the CSS as resources for the class, and then register them during the page lifecycle, usually in PreRender(). For example: ``` // Css [assembly: WebResource("Assembly.Class.MyClass.css", "text/css")] // Javascript [assembly: WebResource("Assembly.Class.MyClass.js", "text/javascript")] namespace OurNamespace { public class MyClass... ``` We then set the properties of each of our scripts and css files to be Embedded Resources. This approach lets you keep your scripts seperate and targeted to individual UI components. You can register the same resources to multiple classes, and then ScriptManager will take care of making sure that the right resources show up on the page. We then wrote a class at the HTTP handler level that handles compressing all the CSS resources into one file before it's streamed out, to make sure we didn't hit the 32 CSS file limit for IE6. It also strips out whitespace, comments, etc. from our scripts to optimize the javascript output.
What is best practice to handle javascript and css files
[ "", "asp.net", "javascript", "css", "" ]
I am trying to get my Django app (NOT using Google app engine) retrieve data from Google Contacts using Google Contacts Data API. Going through [authentication documentation](http://code.google.com/apis/accounts/docs/AuthSub.html) as well as [Data API Python client docs](http://code.google.com/apis/contacts/docs/1.0/developers_guide_python.html) First step (AuthSubRequest) which is getting the single-use token works fine. The next step(AuthSubSessionToken), which is upgrade single-use token to a session token. The python API call UpgradeToSessionToken() simply didn't work for me it gave me NonAuthSubToken exception: ``` gd_client = gdata.contacts.service.ContactsService() gd_client.auth_token = authsub_token gd_client.UpgradeToSessionToken() ``` As an alternative I want to get it working by "manually" constructing the HTTP request: ``` url = 'https://www.google.com/accounts/AuthSubSessionToken' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'AuthSub token=' + authsub_token, 'User-Agent': 'Python/2.6.1', 'Host': 'https://www.google.com', 'Accept': 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2', 'Connection': 'keep-alive', } req = urllib2.Request(url, None, headers) response = urllib2.urlopen(req) ``` this gives me a different error: HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop. The last 30x error message was: Moved Temporarily What am I doing wrong here? I'd appreciate help/advice/suggestions with either of the methods I am trying to use: Python API call (UpgradeToSessionToken) or manually constructing HTTP request with urllib2.
According to the 2.0 documentation [here](http://code.google.com/apis/contacts/docs/2.0/developers_guide_protocol.html#auth_sub) there is a python example set... > Running the sample code > > A full working sample client, containing all the sample code shown in this document, is available in the Python client library distribution, under the directory `samples/contacts/contacts_example.py`. > > The sample client performs several operations on contacts to demonstrate the use of the Contacts Data API. Hopefully it will point you in the right direction.
I had a similar issue recently. Mine got fixed by setting "secure" to "true". ``` next = 'http://www.coolcalendarsite.com/welcome.pyc' scope = 'http://www.google.com/calendar/feeds/' secure = True session = True calendar_service = gdata.calendar.service.CalendarService() ```
Google Data API authentication
[ "", "python", "django", "google-api", "gdata", "gdata-api", "" ]
Further to my question yesterday ([here](https://stackoverflow.com/questions/693905/live-orders-view-on-website-advice-needed)), I am working on a webpage that has a section that shows 'live' order details. The top half of my webpage has Spry Tabbed Panels. One of the panels contains an include call to a separate php page that I have created (getOpenOrders.php). This contains an SQL query to obtain all open orders and then puts the details into a table. As a result, the table of open orders is shown in the Spry panel. What steps do I now need to take to have this refresh every 15 seconds?
Do you really want to call the database every 15 seconds for each user? isn't that an overload? I'm not saying that your database will be overloaded, but, thats how you **shouldn't** do things! **Edited** you should show an image, or the link to that page in order to gt an appropriate answer, because it all depends in what are you doing in the table. because I don't know, I will give you an answer on what probably is happening. Because you said that you're new to the ajax world, let's make things simple, and not to complicate on the you should return a JSON object and use it to re populate your table. :) So we will start with 2 buttons (Previous and Next) so the user can move the data that is showing (you probably don't want to give him/her 100 lines to see right?) --- let's say that you have 2 pages, a **showData.php** and **getTable.php**, in the showData.php you will need to load jQuery (wonderful for this) and add a little code, but where the table is to be placed, just add a div tag with an id="myTable" because we will get the data from the getTable.php file. getTable.php file has to output only the table html code with all the data in, without no html, body, etc... the idea is to add inside the div called myTable all the code generated by getTable.php Let's imagine that getTable.php gets a page variable in the queryString, that will tell what page you should show (to use `LIMIT` in your MySQL or PostgreSQL database) --- You can use jQuery plugin called [datatables](http://www.datatables.net/) witch is one of my choices, [check his example](http://www.datatables.net/examples/example_zero_config.html) and how small code you need to write! just using jQuery and Datatables plugin. The first description follows the jQuery.Load() to load the getTable.php and add as a child of the div and wold do this for the previous and next buttons, passing a querystring with the page that the user requested. It's to simple and you can see the website for that, if you prefer to use the DataTables plugin, then just follow their examples :) if you, after all this need help, drop me a line.
``` <META HTTP-EQUIV=Refresh CONTENT="15; URL=<?php print $PHP_SELF ?>"> ``` This should be in between the head tags. -or- ``` header('Refresh: 15'); ``` This should be **before** the head tag and directly after the html tag. As said by balexandre, a different method should be used. One that does not require a database hit every 15 seconds for every single user that is connected to the site. But, there is your answer anyways.
Refresh Using Ajax/PHP
[ "", "php", "ajax", "" ]
As the title says, is there an easy way to output two columns to the console in Java? I'm aware of `\t`, but I haven't found a way to space based on a specific column when using printf.
Use the width and precision specifiers, set to the same value. This will pad strings that are too short, and truncate strings that are too long. The '-' flag will left-justify the values in the columns. ``` System.out.printf("%-30.30s %-30.30s%n", v1, v2); ```
i did it without using Formatter class as : ``` System.out.printf("%-10s %-10s %-10s\n", "osne", "two", "thredsfe"); System.out.printf("%-10s %-10s %-10s\n", "one", "tdsfwo", "thsdfree"); System.out.printf("%-10s %-10s %-10s\n", "onsdfe", "twdfo", "three"); System.out.printf("%-10s %-10s %-10s\n", "odsfne", "twsdfo", "thdfree"); System.out.printf("%-10s %-10s %-10s\n", "osdne", "twdfo", "three"); System.out.printf("%-10s %-10s %-10s\n", "odsfne", "tdfwo", "three"); ``` and output was ``` osne two thredsfe one tdsfwo thsdfree onsdfe twdfo three odsfne twsdfo thdfree osdne twdfo three odsfne tdfwo three ```
Is there an easy way to output two columns to the console in Java?
[ "", "java", "" ]
I need to create some files using Visual Studio T4 (templating). What is the best way to import some configuration settings into multiple .tt files and have it accessible in the templating code portion.
The simplest way to store configuration is by placing it as code in a shared .tt file, which you can include from multiple templates (i.e. if you need a connection string, make it a constant in a class feature block). However, if that is not an option and you need to access settings in .config file, I agree with John's suggestion.
I'd do this the same way as for any normal piece of code. Using AppSettings, or a custom configuration section. If you do it a lot, you should create a [Custom Directive Processor](http://msdn.microsoft.com/en-us/library/bb126315.aspx). This could emit a property granting you access to the custom configuration.
Best way to store configuration settings for T4
[ "", "c#", "visual-studio", "t4", "" ]
I am trying to implement an interface class, that contains a list of objects. How can I make the list generic, so that the implementing class defines the type of list: ``` public interface IEntity { Guid EntityID { get; set; } Guid ParentEntityID{ get; set; } Guid RoleId { get; set; } void SetFromEntity(); void Save(); bool Validate(); IQueryable<T> GetAll(); // That is what I would like to do List<Guid> Search(string searchQuery); } public class Dealer : IEntity { public IQueryable<Dealer> GetAll() { } } ```
You can do something like this: ``` public interface IEntity<T> { IQueryable<T> GetAll(); } public class Dealer : IEntity<Dealer> { public IQueryable<Dealer> GetAll() { } } ```
You just need to make IEntity generic itself. Then, use the type parameter in the definition of GetAll(). Here's how you'd change your code: ``` public interface IEntity<TListItemType> { // stuff snipped IQueryable<TListItemType> GetAll(); } public class Dealer : IEntity<Dealer> { public IQueryable<Dealer> GetAll() { // some impl here } } ```
Generic list in an interface
[ "", "c#", "linq", "generics", "generic-list", "" ]
I’m interested in developing an iPhone application using Visual Studio and C#.NET on Windows Vista. I tried to download the SDK from <http://developer.apple.com/iphone/index.action>, but the file has a `.dmg` extension and I don’t know how to open that file. So can I as .NET developer work and develop against iPhone APIs? And are there any existing applications which haven been developed using .NET? Are there any resources or web sites can help in that matter? Thanks!
In a word, no. There is Mono support for the iPhone, but it's currently limited. They have spoken in the past about the possibility of writing a Silverlight app, with a series of "iPhone style" controls that could be statically linked as an iPhone app, but that's some way off. If it's games you're interested in, and you have deep pockets, then [UNITY](http://unity3d.com/unity/features/iphone-publishing) is a Mono based game development platform that supports the iPhone (and runs on Windows) Failing that, bite the bullet and get a cheap Mac from EBay. Officially only Intel Macs are supported for the SDK, but you can get it to install on PPC ones and I've yet to have a problem with that (I'm running it on a G5 PowerMac at the moment)
**UPDATE 7/18/2013:** Since this answer is 3 years old I would like to update it with current information. MonoTouch is no more because it is now part of [Xamarin](http://www.xamarin.com). With it you can develop mobile applications using C# and parts of the .NET Framework (using Mono). [You can develop iOS apps using Windows](https://store.xamarin.com/) and Visual Studio, but you still need a Mac to compile and build. [Here's](http://blog.xamarin.com/introduction-to-building-xamarin.ios-applications-in-visual-studio/?mkt_tok=3RkMMJWWfF9wsRonv6TNZKXonjHpfsXw6OgkT/rn28M3109ad%2brmPBy%2b3oUJWp8na%2bqWCgseOrQ8mVsNV8q6RM0XrKw=) a blog post on how to use VS for iOS development. **ORIGINAL ANSWER** [MonoTouch](http://monotouch.net/). You still need a mac and a minimum of $400 (as of this writing) You can try the eval version which doesn't require you to pay and allows you program using the simulator. If you want to test your app on the hardware then you need to pocket the money.
Can I develop iPhone applications using C#.NET on Vista?
[ "", "c#", "iphone", "mobile", "" ]
How do you access the Description property on either a const or a property, i.e., ``` public static class Group { [Description( "Specified parent-child relationship already exists." )] public const int ParentChildRelationshipExists = 1; [Description( "User is already a member of the group." )] public const int UserExistsInGroup = 2; } ``` or ``` public static class Group { [Description( "Specified parent-child relationship already exists." )] public static int ParentChildRelationshipExists { get { return 1; } } [Description( "User is already a member of the group." )] public static int UserExistsInGroup { get { return 2; } } } ``` In the calling class I'd like to access the Description property, i.e., ``` int x = Group.UserExistsInGroup; string description = Group.UserExistsInGroup.GetDescription(); // or similar ``` I'm open to ideas to other methodologies as well. **EDIT:** I should have mentioned that I've seen an example provided here: [Do auto-implemented properties support attributes?](https://stackoverflow.com/questions/464889/does-auto-implemented-properties-support-attributes) However, I'm looking for a method to access the description attribute without having to enter a string literal into the property type, i.e., I'd rather not do this: ``` typeof(Group).GetProperty("UserExistsInGroup"); ``` Something along the lines of an Extension Method; similar to the following method that will return the Description attribute on an Enum via an Extension Method: ``` public static String GetEnumDescription( this Enum obj ) { try { System.Reflection.FieldInfo fieldInfo = obj.GetType().GetField( obj.ToString() ); object[] attribArray = fieldInfo.GetCustomAttributes( false ); if (attribArray.Length > 0) { var attrib = attribArray[0] as DescriptionAttribute; if( attrib != null ) return attrib.Description; } return obj.ToString(); } catch( NullReferenceException ex ) { return "Unknown"; } } ```
You can call [MemberInfo.GetCustomAttributes()](http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.getcustomattributes.aspx) to get any custom attributes defined on a member of a `Type`. You can get the `MemberInfo` for the property by doing something like this: ``` PropertyInfo prop = typeof(Group).GetProperty("UserExistsInGroup", BindingFlags.Public | BindingFlags.Static); ```
Try the following ``` var property = typeof(Group).GetProperty("UserExistsInGroup"); var attribute = property.GetCustomAttributes(typeof(DescriptionAttribute), true)[0]; var description = (DescriptionAttribute)attribute; var text = description.Description; ```
How to access the Description attribute on either a property or a const in C#?
[ "", "c#", ".net", "attributes", "" ]
I have the following code: ``` class SuperClass { public static String getName() { return "super"; } } class SubClass extends SuperClass { public static String getName() { return "sub"; } } public class Dummy<T extends SuperClass> { public void print() { System.out.println("SuperClass: " + SuperClass.getName()); System.out.println("SubClass: " + SubClass.getName()); System.out.println("T: " + T.getName()); } public static void main(String[] args) { new Dummy<SubClass>().print(); } } ``` This code outputs the following: ``` SuperClass: super SubClass: sub T: super ``` My question is: Why doesn't T.getName() return the value of SubClass.getName()? After all, I specified that T == SubClass. Or are static function calls invalid for generic references? Thanks a lot in advance!
This isn't just an issue about generics. If you say: ``` SuperClass obj = new SubClass(); System.out.println(obj.getName()); ``` you will also get "super". There are no "polymorphic" static methods. In your case, all the compiler knows about `T` is that it extends `SuperClass`, so it will call `SuperClass.getName()`.
Unlike C++ templates, Java generics work by type erasure, so it only generates one class for all values of `T`, and translates all references to type `T` in this class to the super type of `T`, in this case `SuperClass`, then uses virtual dispatch to provide the variance for calls to object methods, and static dispatch to calls to static methods. So when you do `Dummy<SubClass>.print()`, the compiler does not make a global replace of `T` with `SubClass` in `Dummy`. All the compiler does is check that uses of `T` as an argument or return type in the methods of `Dummy` are `SubClass`. There's no change to any code inside `Dummy`, so the same `SuperClass` static method gets called whatever `T` is. If you want different behaviour in a generic class depending on the parameterised type, you have pass an object of that type in and use a virtual method, or pass in the class for the type and use reflection.
Unable to make static reference to generic subclass (Java)
[ "", "java", "generics", "inheritance", "static", "extends", "" ]
I'm learning python and PyGTK now, and have created a simple Music Organizer. <http://pastebin.com/m2b596852> But when it edits songs with the Norwegian letters æ, ø, and å it's just changing them to a weird character. So is there any good way of opening or encode the names into utf-8 characters? ### Two relevant places from the above code: Read info from a file: ``` def __parse(self, filename): "parse ID3v1.0 tags from MP3 file" self.clear() self['artist'] = 'Unknown' self['title'] = 'Unknown' try: fsock = open(filename, "rb", 0) try: fsock.seek(-128, 2) tagdata = fsock.read(128) finally: fsock.close() if tagdata[:3] == 'TAG': for tag, (start, end, parseFunc) in self.tagDataMap.items(): self[tag] = parseFunc(tagdata[start:end]) except IOError: pass ``` Print to sys.stdout info: ``` for info in files: try: os.rename(info['name'], os.path.join(self.dir, info['artist'])+' - '+info['title']+'.mp3') print 'From: '+ info['name'].replace(os.path.join(self.dir, ''), '') print 'To: '+ info['artist'] +' - '+info['title']+'.mp3' print self.progressbar.set_fraction(i/num) self.progressbar.set_text('File %d of %d' % (i, num)) i += 1 except IOError: print 'Rename fail' ```
You want to start by decoding the input FROM the charset it is in TO utf-8 (in Python, encode means "take it from unicode/utf-8 to some other charset"). Some googling suggests the Norwegian charset is plain-ole 'iso-8859-1'... I hope someone can correct me if I'm wrong on this detail. Regardless, whatever the name of the charset in the following example: ``` tagdata[start:end].decode('iso-8859-1') ``` In a real-world app, I realize you can't guarantee that the input is norwegian, or any other charset. In this case, you will probably want to proceed through a series of likely charsets to see which you can convert successfully. Both SO and Google have some suggestions on algorithms for doing this effectively in Python. It sounds scarier than it really is.
You'd need to convert the bytestrings you read from the file into Unicode character strings. Looking at your code, I would do this in the parsing function, i.e. replace `stripnulls` with something like this ``` def stripnulls_and_decode(data): return codecs.utf_8_decode(data.replace("\00", "")).strip() ``` Note that this will only work if the strings in the file are in fact encoded in UTF-8 - if they're in a different encoding, you'd have to use the corresponding decoding function from the `codecs` module.
Using norwegian letters æøå in python
[ "", "python", "utf-8", "" ]
I am testing my Zend Framework application and would like to test that something happens when a particular key is not set in the registry. This is the function that I am testing: ``` protected function getDomainFromConfig() { $config = Zend_Registry::get('config'); if (!isset($config->domain)) { throw new Exception('Please make sure you have "domain" set in your config file and your config file is being set in the Zend_Registry.'); } return $config->domain; } ``` How can I unset a key in the registry? I tried this, but it did not work: ``` $config = Zend_Registry::get('config'); $config->__unset('domain'); ``` **Update:** What I really want to know is how should I test that my method throws an exception when the "domain" key in the config file is not set.
The only real way to change the value of the config object would be to dump it to a variable, unset the item in question, ask the registry to delete the key for config, and then reset it. ``` <?php $registry = Zend_Registry::getInstance(); $config = $registry->get('config'); unset($config->domain); $registry->offsetUnset('config'); $registry->set('config', $config); ?> ``` However, for this to work you would have to have set the Zend\_Config object to editable before it is set into the registry the first time. You should consider that it is not best practice to edit the registry in this way. In particular, the Zend\_Config object is designed to be static once it is instantiated originally. I hope I have understood your problem well enough!
If your 'config' is actually `Zend_Config`, then by default it's read-only. `Zend_Config` constructor's optional second parameter is boolean `$allowModifications`, by default set to `false`. You probably create `Zend_Config_Ini` in `bootstrap.php` with ``` new Zend_Config_Ini(APPLICATION_PATH . '/config/app.ini', APPLICATION_ENVIRONMENT) ``` append `$allowModifications` param: ``` new Zend_Config_Ini(APPLICATION_PATH . '/config/app.ini', APPLICATION_ENVIRONMENT, true) ```
Zend Framework: How to unset a key in Zend_Registry?
[ "", "php", "zend-framework", "registry", "config", "" ]
I have a form with an `<input type=text />` and I want to call a javascript function after 5 seconds of the last key press, and every time a new key is pressed, this timer should reset and only call the function after 5 seconds. How can I do this? I'm using jQuery. thanks!
Something like this should get you started: ``` var timeout; $('input[type=text]').keypress(function() { if(timeout) { clearTimeout(timeout); timeout = null; } timeout = setTimeout(myFunction, 5000) }) ```
[This answer](https://stackoverflow.com/a/693863/3303195) is great, but remember that you need to enable this code after the documents loads and after the function loads to clear the timeout. Here is the complete code: ``` var timeout; $(document).ready(function(){ $('input[type=text]').keypress(function() { if(timeout) { clearTimeout(timeout); timeout = null; } timeout = setTimeout(myFunction, 5000); }); }); var myFunction = new function() { alert('myFunction is running'); clearTimeout(timeout); // this way will not run infinitely } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> ```
Call a javascript function after 5 sec of last key press
[ "", "javascript", "jquery", "" ]
I have a line of jquery that is inserting a div before another div that is already on the page using jQuery's before method: ``` $("#sendEmail").before('<div id="response"><h1>Success</h1><p>Your email was sent.</p></div>'); ``` I want the new div to fade in, so I tried to combine the methods in two different ways, but both did not work correctly. Here is what I tried: ``` $("#sendEmail").before('<div id="response"><h1>Success</h1><p>Your email was sent.</p></div>').fadeIn("slow"); ``` That didn't work cause it was trying to fade out the #sendmail div and not the one i was inserting. Here's the other attempt I made: ``` $("#sendEmail").before('<div id="response"><h1>Success</h1><p>Your email was sent.</p></div>'); $("#response").fadeIn("slow"); ``` That also didn't work since the #response div is already inserted when I try to fade it in, so nothing happens. I feel like I'm really close, but I can't figure it out. Can someone help?
set a css rule on #response to have display: none then it won't show until you fade in
``` $('<div id="response"><h1>Success</h1><p>Your email was sent.</p></div>') .hide().insertAfter("#sendemail").fadeIn(); ```
How do I combine the 'before' method with the 'fadeIn' method in jQuery?
[ "", "javascript", "jquery", "effects", "" ]
Why the following program prints ``` B B ``` (as it should) ``` public class A { public void Print() { Console.WriteLine("A"); } } public class B : A { public new void Print() { Console.WriteLine("B"); } public void Print2() { Print(); } } class Program { static void Main(string[] args) { var b = new B(); b.Print(); b.Print2(); } } ``` but if we remove keyword 'public' in class B like so: ``` new void Print() { Console.WriteLine("B"); } ``` it starts printing ``` A B ``` ?
When you remove the `public` access modifier, you remove any ability to call B's `new Print()` method from the `Main` function because it now defaults to `private`. It's no longer accessible to Main. The only remaining option is to fall back to the method inherited from A, as that is the only accessible implementation. If you were to call Print() from within another B method you would get the B implementation, because members of B would see the private implementation.
You're making the `Print` method `private`, so the only available `Print` method is the inherited one.
How method hiding works in C#?
[ "", "c#", "inheritance", "compiler-construction", "method-hiding", "" ]
Since I've been learning Java, I've been able to create GUI programs. However, even simple "Hello World!" programs will not work, if they require a console. My research on the topic has lead me to the conclusion that my Java Runtime Environment does not have a console associated with it. Is it possible to call the Win32 "AllocConsole" method somehow, like is possible in C#? Edit: I mean the console like you are describing, a console just like C# programs can have. I forgot to mention that I'm using the Eclipse IDE. From what I've discovered Eclipse runs a program using "javaw.exe" instead of "java.exe" which causes the program not to have a console. Also, the windows "command prompt" is a program that uses the type of console I mean. Thanks for any answers. Euphoria83 is on the right track as to what I am trying to do. By the way his method works, but I want the console to automatically appear when I click on the ".jar" file of a program I create. Basically, I need the console to act like it does in C# at runtime. Also, Eclipse does have a console window (I think they call it the console perspective, but I am used to using Visual Studio so I am not exactly sure) which will display the program output **inside Eclipse only**. I want the console to work at runtime, not just inside the integrated development environment.
Either associate 'java.exe' with the .jar extension (by default it will be 'javaw.exe', which has no console), in which case you'll get a console with every jar, or create a shortcut/.exe in the language of your choice/batch script to run 'java -jar myjar.jar' when you click on it.
What exactly do you mean by console? Typing the regular ``` System.out.println("Hello world!"); ``` On a simple Java program and running it from command line should give you the results you want. Unless your definition of console is different in which case you'll need to explain yourself better.
How can I associate a console with a Java application?
[ "", "console", "java", "" ]
I have the following SQL within a stored procedure. Is there a way to remove the IF statement and pass the 'ASC'/'DESC' option as a variable? I know I could do the query a number of different ways, or return a table and sort it externally etc. I would just like to know if I can avoid duplicating the CASE statement. ``` IF @sortOrder = 'Desc' BEGIN SELECT * FROM #t_results ORDER BY CASE WHEN @OrderBy = 'surname' THEN surname END DESC, CASE WHEN @OrderBy = 'forename' THEN forename END DESC, CASE WHEN @OrderBy = 'fullName' THEN fullName END DESC, CASE WHEN @OrderBy = 'userId' THEN userId END DESC, CASE WHEN @OrderBy = 'MobileNumber' THEN MSISDN END DESC, CASE WHEN @OrderBy = 'DeviceStatus' THEN DeviceStatus END DESC, CASE WHEN @OrderBy = 'LastPosition' THEN LastPosition END DESC, CASE WHEN @OrderBy = 'LastAlert' THEN LastAlert END DESC, CASE WHEN @OrderBy = 'LastCommunication' THEN LastCommunication END DESC, CASE WHEN @OrderBy = 'LastPreAlert' THEN LastPreAlert END DESC END ELSE BEGIN SELECT * FROM #t_results ORDER BY CASE WHEN @OrderBy = 'surname' THEN surname END DESC, CASE WHEN @OrderBy = 'forename' THEN forename END DESC, CASE WHEN @OrderBy = 'fullName' THEN fullName END DESC, CASE WHEN @OrderBy = 'userId' THEN userId END DESC, CASE WHEN @OrderBy = 'MobileNumber' THEN MSISDN END DESC, CASE WHEN @OrderBy = 'DeviceStatus' THEN DeviceStatus END DESC, CASE WHEN @OrderBy = 'LastPosition' THEN LastPosition END DESC, CASE WHEN @OrderBy = 'LastAlert' THEN LastAlert END DESC, CASE WHEN @OrderBy = 'LastCommunication' THEN LastCommunication END DESC, CASE WHEN @OrderBy = 'LastPreAlert' THEN LastPreAlert END DESC END END ```
Pass in @OrderBy int, where positive is ASC, negative is DESC, and the actual number is the column to sort by: ``` SELECT dt.yourColumn1 ,dt.yourColumn2 ,dt.yourColumn3 ,CASE WHEN @OrderBy>0 THEN dt.SortBy ELSE NULL END AS SortByAsc ,CASE WHEN @OrderBy<0 THEN dt.SortBy ELSE NULL END AS SortByDesc FROM (SELECT yourColumn1 ,yourColumn2 ,yourColumn3 ,CASE WHEN ABS(@OrderBy) = 1 THEN surname WHEN ABS(@OrderBy) = 2 THEN forename WHEN ABS(@OrderBy) = 3 THEN fullName WHEN ABS(@OrderBy) = 4 THEN CONVERT(varchar(10),userId) WHEN ABS(@OrderBy) = 5 THEN CONVERT(varchar(10),MobileNumber WHEN ABS(@OrderBy) = 6 THEN DeviceStatus WHEN ABS(@OrderBy) = 7 THEN LastPosition WHEN ABS(@OrderBy) = 8 THEN CONVERT(varchar(23),LastAlert,121) WHEN ABS(@OrderBy) = 9 THEN CONVERT(varchar(23),LastCommunication,121) WHEN ABS(@OrderBy) =10 THEN CONVERT(varchar(23),LastPreAlert,121) ELSE NULL END AS SortBy FROM YourTablesHere WHERE X=Y ) dt ORDER BY SortByAsc ASC, SortByDesc DESC ``` Just make sure you build a string that sort properly. Notice I used 'YYYY-MM-DD hh:mm:ss.mmm' for the dates and put the numbers into strings. We usually put multiple columns together, so if you sort by surname, forename is used too, etc. Watch out, if you do combine multiple columns you'll need to pad with zeros or spaces. If you don't want the SortByAsc and SortByDesc columns to be in the result set, wrap the entire thing in a derived table.
You can do it without dynamic SQL... ``` SELECT * FROM My_Table WHERE Whatever = @something ORDER BY CASE @sort_order WHEN 'ASC' THEN CASE @order_by WHEN 'surname' THEN surname WHEN 'forename' THEN forename WHEN 'fullname' THEN fullname ELSE surname END ELSE '1' END ASC, CASE @sort_order WHEN 'DESC' THEN CASE @order_by WHEN 'surname' THEN surname WHEN 'forename' THEN forename WHEN 'fullname' THEN fullname ELSE surname END ELSE '1' END DESC ```
Can I store SQL Server sort order in a variable?
[ "", "sql", "sql-server", "" ]
Please excuse my ignorance, I only started coding in Silverlight recently. I tried implementing the command pattern in Silverlight and hit a wall. They say commands are great, because you can write them into xaml, so you can keep your code-behind clean, also you have loose coupling between your view and your viewmodel because there is no direct reference to the viewmodel in the view. **You can not keep your code-behind clean**, because you can bind only one command to a control, and you have to decide which event will fire your command when you bind it. If a control has 30 events, you have to choose one for commanding. The other 29 will execute the other commands from event handlers from the code behind. **Loose coupling can be achieved more simply by dependency injection**, commands add a useless layer of indirection that gives nothing extra, they only make it a bit harder to maintain your code. It is easier to maintain your code, when you are programming against an interface and see exactly what method gets called, then when you have to keep jumping between your command definitions and your viewmodel. Did I miss anything, or commands are really not meant to be used for view and viewmodel interaction? Please see the following question. This is why I don't get all the hype with commands: [How should I handle multiple events per control w/command pattern using MVVM in Silverlight?](https://stackoverflow.com/questions/567672/how-should-i-handle-multiple-events-per-control-w-command-pattern-using-mvvm-in-s)
Take a look at Prism (<http://prism.codeplex.com>) and their DelegateCommand<> infrastructure. Its a good solution for Silverlight and WPF to create commands in the ViewModel (or Presenter) and bind directly to it. Also in Silverlight 3, Behaviors can give you some of this same XAML-based syntax.
SL 2.0 is not so powerful as WPF, you will have to write some code behind :-(. Not sure if you have read this article about MVVM and SL, talks about commands limitations on SL: <http://msdn.microsoft.com/en-us/magazine/dd458800.aspx>
Are WPF and Silverlight command implementations useless for the M-V-VM (M-V-P) pattern?
[ "", "c#", "wpf", "silverlight", "design-patterns", "mvp", "" ]
I once ran a home-made forum system for a small group of online deathmatch players. These forums have long since been shut down, and are currently offline. What I want to do is create static HTML files that contain all of the data for the entire system, in the interest of having an online archive that the former users could search. I have control over all of the original data. This would include: * Images * Profiles * Forum Threads * Database * PHP Scripts Basically, I want to take the database out of the equation, so that I don't have to waste the resources to keep it alive. (and also because this was a home-made forum solution, I'm sure it's not very optimized) Is this a feasible goal, or should I just keep the forums the way they are, and not worry about the overhead? If it is possible (and remotely feasible), can I get a few suggestions about how to proceed?
wget can create an HTML mirror of a website. Look in the docs for usage of --mirror.
Use output buffering to capture all your output and write it to a file instead of out to the browser. Edit your code so that at the top (before any HTML output to the browser), you have this line: ``` ob_start(); ``` at the end of the script, add this: ``` $output = ob_get_clean(); file_put_contents("<<name of this page>>.html", $output); ``` You'd have to come up with some naming scheme so you don't get duplicates. Then, using a regex, use apache RewriteRules to redirect all requests to the new HTML page so your links don't break. To get all the pages, you could just click through each of them one by one if you don't have many, you could write all the URLs into an array manually and then loop through them, or you could even crawl the site yourself, looking for all URLs on a page and adding them into the queue as you go.
Permanently Cache Dynamic PHP/MySQL Forums as Static Pages
[ "", "php", "mysql", "database", "forum", "archiving", "" ]
I would like to create in C++ a Notifier class that I will use in other objects to notify various holders when the object gets destroyed. ``` template <class Owner> class Notifier<Owner> { public: Notifier(Owner* owner); ~Notifier(); // Notifies the owner that an object is destroyed }; class Owner; class Owned { public: Owned(Owner* owner); private: Notifier<Owner> _notifier; }; ``` My point is that as I have a dense and complicated object graph, I'd like to avoid storing the address of the owned object in the notifier. Is there a way to change my notifier class so that it can deduce the owned object's address from its own address and an offset that would be computed at compile time? Note also that any object may have to notify several 'owners', possibly from the same class. Thanks.
Or something like this : Inherit from your notifier and add Owned as template parameter. Then you can have a owned method available inside the notifier : ``` template < class Owner , class Owned > class Notifier { public: Notifier(Owner* owner) {} Owned * owned() { return static_cast< Owned * >( this ); } ~Notifier() { // notify owner with owned() } }; class Owner {}; class Owned : public Notifier< Owner , Owned > { public: Owned( Owner * owner ) : Notifier< Owner , Owned >( owner ) {} }; ```
Take a look at the [GoF Observer Design Patter](http://www.vincehuston.org/dp/observer.html).
How can I know the address of owner object in C++?
[ "", "c++", "templates", "notifications", "one-to-many", "" ]
I have been developing in VB.NET and SQL Server 2008 for a while now, but haven't got into live installs yet. In the database system I used be on it had the ability to archive multiple tables into a .dga file, as it was called. I could then restore the .dga file into another database or on another server. I'm looking for the easiest way to accomplish something similar in SQL Server.
If you want to transfer specific tables, then using Data Transformation Services (right click on the database in SQL Server Management studio and select "Import Data" and it will bring the dialog up for it). Of course, this assumes that you have both databases available to you. If you are comfortable with replacing the database as a whole, you can easily backup the database and then restore it into a new one through SQL Server Management studio (or through calling the appropriate SP).
I would go for one of the following : * From MS SQL Management Studio, right click on the database / Tasks / Generate scripts * From Visual Studio, in the Server Explorer tab, "publish to provider" Both will launch a wizard allowing you to export the tables you want the way you want (including data or not, creation scripts or not, etc etc.)
What is the best way to transfer a table or tables from one SQL server to another?
[ "", "sql", "sql-server", "" ]
The pickle module seems to use string escape characters when pickling; this becomes inefficient e.g. on numpy arrays. Consider the following ``` z = numpy.zeros(1000, numpy.uint8) len(z.dumps()) len(cPickle.dumps(z.dumps())) ``` The lengths are 1133 characters and 4249 characters respectively. z.dumps() reveals something like "\x00\x00" (actual zeros in string), but pickle seems to be using the string's repr() function, yielding "'\x00\x00'" (zeros being ascii zeros). i.e. ("0" in z.dumps() == False) and ("0" in cPickle.dumps(z.dumps()) == True)
Try using a later version of the pickle protocol with the protocol parameter to `pickle.dumps()`. The default is 0 and is an ASCII text format. Ones greater than 1 (I suggest you use pickle.HIGHEST\_PROTOCOL). Protocol formats 1 and 2 (and 3 but that's for py3k) are binary and should be more space conservative.
Solution: ``` import zlib, cPickle def zdumps(obj): return zlib.compress(cPickle.dumps(obj,cPickle.HIGHEST_PROTOCOL),9) def zloads(zstr): return cPickle.loads(zlib.decompress(zstr)) >>> len(zdumps(z)) 128 ```
more efficient way to pickle a string
[ "", "python", "numpy", "pickle", "space-efficiency", "" ]
I have utf-8 file which I want to read and display in my java program. In eclipse console(stdout) or in swing I'm getting question marks instead of correct characters. ``` BufferedReader fr = new BufferedReader( new InputStreamReader( new FileInputStream(f),"UTF-8")); System.out.println(fr.readLine()); inpuStreamReader.getEncoding() //prints me UTF-8 ``` I generally don't have problem displaying accented letters either on the linux console or firefox etc. Why is that so? I'm ill from this :/ thank you for help
I'm not a Java expert, but it seems like you're creating a UTF-8 `InputStreamReader` with a file that's not necessarily UTF-8. See also: [Java : How to determine the correct charset encoding of a stream](https://stackoverflow.com/questions/499010/java-how-to-determine-the-correct-charset-encoding-of-a-stream)
It sounds like the Eclipse console is not processing UTF-8 characters, and/or the font configured for that console does not support the Unicode characters you are trying to display. You might be able to get this to work if you configure Eclipse to expect UTF-8 characters, and also make sure that the font in use can display those Unicode characters that are encoded in your file. From the [Eclipse 3.1 New and Noteworthy](http://archive.eclipse.org/eclipse/downloads/drops/R-3.1-200506271435/eclipse-news-part1c.html) page: > You can configure the console to > display output using a character > encoding different from the default > using the Console Encoding settings on > the Common tab of a launch > configuration. As for Swing, I think you're going to need to select the right font.
How to get correct encoding?
[ "", "java", "" ]
I need to provide secure communication between various processes that are using TCP/IP sockets for communication. I want both authentication and encryption. Rather than re-invent the wheel I would really like to use SSL and the SslStream class and self-signed certificates. What I want to do is validate the remote process's certificate against a known copy in my local application. (There doesn't need to be a certificate authority because I intend for the certificates to be copied around manually). To do this, I want the application to be able to automatically generate a new certifiate the first time it is run. In addition to makecert.exe, it looks like [this link](http://blogs.msdn.com/dcook/archive/2008/11/25/creating-a-self-signed-certificate-in-c.aspx) shows a way to automatically generate self-signed certificates, so that's a start. I've looked at the AuthenticateAsServer and AuthenticateAsClient methods of SslStream. You can provide call-backs for verification, so it looks like it's possible. But now that I'm into the details of it, I really don't think it's possible to do this. Am I going in the right direction? Is there a better alternative? Has anyone done anything like this before (basically peer-to-peer SSL rather than client-server)?
**Step 1:** Generating a self-signed certificate: * I downloaded the [Certificate.cs class](http://blogs.msdn.com/dcook/archive/2008/11/25/creating-a-self-signed-certificate-in-c.aspx) posted by Doug Cook * I used this code to generate a .pfx certificate file: ``` byte[] c = Certificate.CreateSelfSignCertificatePfx( "CN=yourhostname.com", //host name DateTime.Parse("2000-01-01"), //not valid before DateTime.Parse("2010-01-01"), //not valid after "mypassword"); //password to encrypt key file using (BinaryWriter binWriter = new BinaryWriter( File.Open(@"testcert.pfx", FileMode.Create))) { binWriter.Write(c); } ``` **Step 2:** Loading the certificate ``` X509Certificate cert = new X509Certificate2( @"testcert.pfx", "mypassword"); ``` **Step 3:** Putting it together * I based it on [this very simple SslStream example](http://leastprivilege.com/2005/02/28/sslstream-sample/) * You will get a compile time error about the SslProtocolType enumeration. Just change that from SslProtocolType.Default to SslProtocols.Default * There were 3 warnings about deprecated functions. I replaced them all with the suggested replacements. * I replaced this line in the Server Program.cs file with the line from Step 2: X509Certificate cert = getServerCert(); * In the Client Program.cs file, make sure you set serverName = yourhostname.com (and that it matches the name in the certificate) * In the Client Program.cs, the CertificateValidationCallback function fails because sslPolicyErrors contains a RemoteCertificateChainErrors. If you dig a little deeper, this is because the issuing authority that signed the certificate is not a trusted root. * I don`t want to get into having the user import certificates into the root store, etc., so I made a special case for this, and I check that certificate.GetPublicKeyString() is equal to the public key that I have on file for that server. If it matches, I return True from that function. That seems to work. **Step 4:** Client Authentication Here's how my client authenticates (it's a little different than the server): ``` TcpClient client = new TcpClient(); client.Connect(hostName, port); SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallback), new LocalCertificateSelectionCallback(CertificateSelectionCallback)); bool authenticationPassed = true; try { string serverName = System.Environment.MachineName; X509Certificate cert = GetServerCert(SERVER_CERT_FILENAME, SERVER_CERT_PASSWORD); X509CertificateCollection certs = new X509CertificateCollection(); certs.Add(cert); sslStream.AuthenticateAsClient( serverName, certs, SslProtocols.Default, false); // check cert revokation } catch (AuthenticationException) { authenticationPassed = false; } if (authenticationPassed) { //do stuff } ``` The CertificateValidationCallback is the same as in the server case, but note how AuthenticateAsClient takes a collection of certificates, not just one certificate. So, you have to add a LocalCertificateSelectionCallback, like this (in this case, I only have one client cert so I just return the first one in the collection): ``` static X509Certificate CertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { return localCertificates[0]; } ```
you can look too this example Sample Asynchronous SslStream Client/Server Implementation <http://blogs.msdn.com/joncole/archive/2007/06/13/sample-asynchronous-sslstream-client-server-implementation.aspx> if certificate is not produced correctly you can get exception The server mode SSL must use a certificate with the associated private key. basic certificate example makecert -sr LocalMachine -ss My -n CN=Test -sky exchange -sk 123456 or as external file makecert -sr LocalMachine -ss My -n CN=Test -sky exchange -sk 123456 c:\Test.cer Certificate Creation Tool (Makecert.exe) <http://msdn.microsoft.com/en-us/library/bfsktky3%28VS.80%29.aspx>
Using SSL and SslStream for peer to peer authentication?
[ "", "c#", "ssl", "ssl-certificate", "sslstream", "" ]
``` Dictionary<string, string> optionDictionary = new Dictionary<string, string>(); optionDictionary = ....; SortedDictionary<string, string> optionsSorted; if(sorting) { optionsSorted = new SortedDictionary<string, string>(optionDictionary ); // Convert SortedDictionary into Dictionary } return optionDictionary ; ```
You can pass in your `optionsSorted<TKey,TValue>` dictionary as a parameter to an instance of a new `Dictionary<TKey,TValue>`, Like so: ``` var dictionary = new Dictionary<type1,type2>(optionsSorted); ```
Try the following ``` var dictionary = optionsSorted.ToDictionary(x => x.Key, x=> x.Value); ```
How to convert a sortedDictionary into Dictionary?
[ "", "c#", "generics", "" ]
I am trying to find a good way to capture a number that is at no more than N characters away from a given string. For example, if the String is "age" and N=4 have to find ``` "Age 5" => 5 "My age is 10 and I my name is John" => 10 "My age is almost 5 and I my name is Mary" => null ``` In the last case, the number is separated more than 4 characters from "age".
What about ``` age[^0-9]{0,4}[0-9]+ ``` if you want to capture the number possibly found: ``` age[^0-9]{0,4}([0-9]+) ``` ?
Something like the following: ``` age[^\d]{,4}(\d+) ``` this means "age followed by 0 to 4 non-digits followed by one or more digits...capture the digits"
Regular Expression : find a number near to a given String
[ "", "java", "regex", "" ]
So I'm trying to debug this strange problem where a process ends without calling some destructors... In the VS (2005) debugger, I hit 'Break all' and look around in the call stacks of the threads of the misteriously disappearing process, when I see this: [smells like SO http://img6.imageshack.us/img6/7628/95434880.jpg](http://img6.imageshack.us/img6/7628/95434880.jpg) This definitely looks like a SO in the making, which would explain why the process runs to its happy place without packing its suitcase first. The problem is, the VS debugger's call stack only shows what you can see in the image. So my question is: how can I find where the infinite recursion call starts? I read [somewhere](https://stackoverflow.com/questions/81202/segfault-on-stack-overflow "somewhere") that in Linux you can attach a callback to the SIGSEGV handler and get more info on what's going on. Is there anything similar on Windows?
**To control what Windows does in case of an access violation** (`SIGSEGV`-equivalent), call [`SetErrorMode`](http://msdn.microsoft.com/en-us/library/ms680621(VS.85).aspx) (pass it parameter 0 to force a popup in case of errors, allowing you to attach to it with a debugger.) However, based on the stack trace you have already obtained, **attaching with a debugger on fault may yield no additional information**. Either your stack has been corrupted, or the depth of recursion has exceeded the maximum number of frames displayable by VS. In the latter case, **you may want to *decrease* the default stack size of the process** (use the `/F` switch or equivalent option in the Project properties) in order to make the problem manifest itself sooner, and make sure that VS *will* display all frames. You may, alternatively, want to stick a breakpoint in std::basic\_filebuf<>::flush() and walk through it until the destruction phase (or disable it until just prior to the destruction phase.)
Well, you know what thread the problem is on - it might be a simple matter of tracing through it from inception to see where it goes off into the weeds. Another option is to use one of the debuggers in the [Debugging Tools for Windows](http://www.microsoft.com/whdc/devtools/debugging/default.mspx) package - they may be able to show more than the VS debugger (maybe), even if they are generally more complex and difficult to use (actually maybe because of that).
debug stack overflow in windows?
[ "", "c++", "windows", "debugging", "stack-overflow", "" ]
As a programmer I would like to get a strong hold on writing queries. In my college years I've read a few sql books and rest I've just learned working as a programmer for last couple of years. But as those queries were work related...they weren't that 'hard' or complex. what would you guys suggest ? Is there a good advanced sql book that would teach and then test the knowledge by giving some questions? Thanks!
IMHO SQL skill, more than any other programming skill, requires mentoring. There are three primary reasons. 1. It's quite possible (often easy) to write a SQL statement that gives you the right answer. So developers often end up telling themselves "Hey, it works, (and all in one statement,) I'm done." Usually not so, and the only efficient way to take the next step is to have your work reviewed and get suggestions (and reasons for the suggestions). 2. Skills aren't nearly as transferrable from "regular" programming as you might expect. Principles like decomposition, subroutines, etc. are usually blind alleys. 3. Real SQL skill requires just as much testing skill. You can only truly evaluate SQL execution by knowing your SQL query analysis tools inside out, and using them without fail on almost every query. So the answer to your question is: get as much help as you can, early and often. And don't be reluctant to ask "Why".
I have always felt that SQL was something you had to learn by doing. I found my self on a project that forced me to write SQL not stop for several weeks to analyze every aspect of a fairly large database. In many isntances I wrote many SQLs that all resulted in the same results but went about getting them in different ways. Using Sql Server Management Studio's execution path tool I was able to review the query options and improve each and finally pick the "best" for the situation. If you can find a reason or purpose to write a bunch of SQL I beleive that will be the best catalyst you can have for truely learning the art of milking data from the DB.
best way to get good with sql queries
[ "", "sql", "" ]
I'm trying to set the main class in netbeans to be the main class it was in the last environment it was in, however the program insists it can't find the main class itself and when I set it as the name of the main class in project properties it says the class does not exist (even though it does). When I right click on the source file with the main class and hit 'run [file]' it works (albeit with errors related to assets which I can fix later on, has nothing to do with the code itself. All I did as of now is simply copy and paste the code into netbeans from the last project, so would I be overlooking anything here? Thanks for any help.
The way applets work in Netbeans is annoying to me. The suggested usage from the help is to run the applet as you indicate you did (Run File). NetBeans will produce an HTML file under build/classes that references the applet. You then copy the HTML file to src where your class is. You can then tweak the HTML and in subsequent runs NetBeans will use your HTML file instead of generating it. Every time you run the file NetBeans opens the applet viewer program that ships with Java. You cannot control any of the arguments passed to the applet viewer. It ignores the run-time parameters you configure in the project. To change the parameters passed to the applet you must edit the HTML file manually. A better way is to use the AppletWindow classes created over at the BlueJ project. It lets you host an applet on a JFrame, which means you can make a small standalone Swing app which calls your applet. The program then has a main method, you can launch an extra Swing window with buttons and text controls to simulate javascript calls to the applet and you can tweak the attributes that get passed to the applet at runtime. It's very nice for trying out new things in your code. Links: * [AppletWindow Download](http://www.bluej.org/resources/classes/appletwn.jar): This jar contains the compiled .class files and the source. * [More info about BlueJ and other resources](http://www.bluej.org/resources/classes.html)
Do you really speak about an applet? Applets have no main-class (they can, but they do not have to). So you probably have an option to import the project as an applet-project, not as standalone-java-app, in Netbeans.
Imported Java applet project into netbeans won't work, Netbeans refuses to identify or even find main class even when manually set
[ "", "java", "class", "ide", "netbeans", "program-entry-point", "" ]
In a [previous question](https://stackoverflow.com/questions/665781/copy-constructor-in-c-is-called-when-object-is-returned-from-a-function), it appeared that a plain return-by-value function always copies its `return` argument into the variable being assigned from it. Is this required by the standard, or can the function be optimized by constructing the 'assigned to' variable even within the function body? ``` struct C { int i; double d; }; C f( int i, int d ) { return C(i,d); // construct _and_ copy-construct? } int main() { C c = f( 1, 2 ); } ```
The standard allows any level of copy omission here: * construct a local temporary, copy-construct it into a return value, and copy-construct the return value into the local "c". **OR** * construct a local temporary, and copy-construct that into "c". **OR** * construct "c" with the arguments "i,d"
The standard says that the copy constructor need not be used - see section 12.8/15: > 15 Whenever a temporary class object > is copied using a copy constructor, > and this object and the copy have the > same cv-unqualified type, an > implementation is permitted to treat > the original and the copy as two > different ways of referring to the > same object and not perform a copy at > all, even if the class copy > constructor or destructor have side > effects. And much more in a similar vein.
Copy constructor vs. return value optimization
[ "", "c++", "copy-constructor", "return-value-optimization", "" ]
I recently took a class at school where we had to learn Scheme to build a parser for a simple made up scheme-like language. As the semester went on, we added to our parser to make it more and more interesting. Since then, on my own time, I've started writing my own parser that's quite a bit neater than what I did in class, but it parses my C++ code, gathers a list of all the data structures and public members, and generates a recursive descent parser for it. For example, if I have the the following ``` class Bar { public: int a; } class Foo { public: Bar* myBar; int x; } ``` and I run my parser generator on it, it spits out a new class simply called Parser that I can use like this to read from a file: ``` Parser p; Foo* f = p.parseFoo("example.txt"); ``` where example.txt would be something like this: ``` Foo { myBar { a 5 } x 10 } ``` (This is just a simple example, there are some other neat things too like recognizing when it should be push\_back-ing onto a vector, and being able to assign function callbacks) This seems like the type of thing that other (probably smarter) people ought to have done before me. I did some quick Google searches to see what was out there, but there's a lot of stuff to sift though. So my question is this: are there tools out there that do what my parser generator does right now? Is this project worth continuing\* or are there better tools out there already? \*of course it's always worth continuing as a learning experience. Rather, I mean from the point of view as a user who would want to read data structures to and from text.
lex and yacc (or rather, [flex](https://github.com/westes/flex) and [bison](http://www.gnu.org/software/bison/)) are powerful tools that will help you generate parsers for regular languages with ease.
Boost.Spirit is *very* impressive and useful. Documentation on this can be found [here](http://www.boost.org/doc/libs/1_38_0/libs/spirit/classic/index.html) But be aware that parsing C++ is **really not** easy.
What programs are there for parser generation?
[ "", "c++", "parsing", "" ]
I am using getopt\_long to process command line arguments in a C++ application. The examples all show something like `printf("Username: %s\n", optarg)` in the processing examples. This is great for showing an example, but I want to be able to actually store the values for use later. Much of the rest of the code uses `string` objects instead of `char*` so I need to cast/copy/whatever the contents of optarg into a string. ``` string bar; while(1) { c = getopt_long (argc, argv, "s:U:", long_options, &option_index); if (c == -1) break; switch(c) { case 'U': // What do I need to do here to get // the value of optarg into the string // object bar? bar.assign(optarg); break; } } ``` The above code compiles, but when it executes I get an `Illegal instruction` error if I try to print out the value of bar using printf (it seems to work just fine for cout). ``` // Runs just fine, although I'm not certain it is actually safe! cout << " bar: " << bar << "\n"; // 'Illegal instruction' printf(" bar: %s\n", bar); ``` I do not know enough about command line debugging to better dig into what the illegal instruction might be. I had been running valgrind, but the sheer volume of memory errors that result from this error have made it difficult for me to pinpoint exactly what might be causing this error.
You told printf that you were suppling a c style string (null terminated array of chars) when specifying %s, but you provided a string class instead. Assuming you are using std::string try: ``` printf("bar : %s\n", bar.c_str()); ```
`printf()` can't handle C++ `string`s. Use `bar.c_str()` instead.
Get optarg as a C++ string object
[ "", "c++", "string", "getopt", "getopt-long", "" ]
I am working on an online store on the Magento platform and have hit a major roadblock: For some reason **I cannot figure out how to export current orders (with shipping information/shipment type/etc).** Does anyone have any suggestions? This seems as if it should be one of the most basic things for a system like this to do, but I have not been able to find out how.
Seeing as you want this for shipping you might want to ask whoever handles your shipping whether they have some sort of API so you can build/buy/download an appropriate shipping module and spare yourself the hassle of mucking about with CSV files. If you really want a CSV file however I can show you how to create it. You didn't mention where this script will run so I'll assume it's an external script (which will make it easier to use with a cron job). You want to do the following: ``` //External script - Load magento framework require_once("C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\magento\app\Mage.php"); Mage::app('default'); $myOrder=Mage::getModel('sales/order'); $orders=Mage::getModel('sales/mysql4_order_collection'); //Optional filters you might want to use - more available operations in method _getConditionSql in Varien_Data_Collection_Db. $orders->addFieldToFilter('total_paid',Array('gt'=>0)); //Amount paid larger than 0 $orders->addFieldToFilter('status',Array('eq'=>"processing")); //Status is "processing" $allIds=$orders->getAllIds(); foreach($allIds as $thisId) { $myOrder->reset()->load($thisId); //echo "<pre>"; //print_r($myOrder); //echo "</pre>"; //Some random fields echo "'" . $myOrder->getBillingAddress()->getLastname() . "',"; echo "'" . $myOrder->getTotal_paid() . "',"; echo "'" . $myOrder->getShippingAddress()->getTelephone() . "',"; echo "'" . $myOrder->getPayment()->getCc_type() . "',"; echo "'" . $myOrder->getStatus() . "',"; echo "\r\n"; } ``` For the sake of brevity (and sanity) I haven't listed all the available order information. You can find out what fields are available by dumping the relevant objects and taking a look at their fields. For example if you were to do print\_r($myOrder->getBillingAddress()); you'd see fields like "address\_type" and "lastname". You can use these with $myOrder->getBillingAddress()->getAddress\_type() and $myOrder->getBillingAddress()->getLastname() respectively. **Edit**: Changed code according to craig.michael.morris's answer
I was in the process of implementing your solution and noticed that it was only returning the first values for all the foreign keys such as billing address, shipping address, payment etc... This can be fixed by changing $myOrder->load($thisId); to $myOrder->reset()->load($thisId);
Export Orders from Magento for shipment
[ "", "php", "magento", "export", "" ]
The default DataTemplate in a wpf application displays the result of the `.ToString()` method. I'm developing an application where the default DataTemplate should display nothing. I've tried: ``` <Grid.Resources> <DataTemplate DataType="{x:Type System:Object}"> <Grid></Grid> </DataTemplate> </Grid.Resources> ``` But this doesn't work. Does anyone knows if this is possible without specifiing a specific DataTemplate for every class type in the application?
I know of no way to do this. As per Joe's comment below, WPF specifically disallows specifying a `DataTemplate` for type `Object`. Depending on your exact requirements, it may be easier to search for a `DataTemplate` that matches the specific type. If you find one, use it. Otherwise, display nothing. For example: ``` <ContentControl Content="{Binding YourContent}" ContentTemplateSelector="{StaticResource MyContentTemplateSelector}"/> ``` And in your selector (pseudo-code, obviously): ``` var dataTemplateKey = new DataTemplateKey() { DataType = theType; }; var dataTemplate = yourControl.FindResource(dataTemplateKey); if (dataTemplate != null) { return dataTemplate; } return NulloDataTemplate; ```
If you are using the MVVM pattern and have an abstract class which all your ViewModel classes derive from, you can use that class instead of System.Object: ``` <Grid.Resources> <DataTemplate DataType="{x:Type vm:VMBase}"> </DataTemplate> </Grid.Resources> ```
Specify a default empty DataTemplate instead of the default 'ToString()' DataTemplate
[ "", "c#", "wpf", "datatemplate", "default", "" ]
I'm using calendar from Yahoo UI as follows: > calDate = (calDate.getMonth() + 1) + > '/' + calDate.getDate() + '/' + > calDate.getFullYear(); This displays a `MMDDYYYY` format. I want to change this format to `YYYY-MM-DD` so that I can insert it into a MySQL database. I changed the code to: > calDate = calDate.getFullYear() + '-' > + (calDate.getMonth() + 1) + '-' + calDate.getDate(); It worked but the problem is now that when I want to change the selected date the calender doesn't display the date and instead shows `NAN`.
You should change the format of the date just before it is inserted on the server side, let the client side have the format that it wants, and change the date around later.
It's typically best to pass the date to your back end as a unix timestamp and convert it in the database itself. In the code where you construct your POST data for the server, you'd pass something like this: ``` var t = calDate.getTime()/1000; ``` Note the divide by 1000. This is required because javascript timestamps are in milliseconds, while MySQL requires seconds. In your SQL statement, you'll pass the timestamp as is, and use the FROM\_UNIXTIME function to convert it to your required format: ``` INSERT INTO ... VALUES ( FROM_UNIXTIME($t), ...) ``` Naturally there will be some code in between that converts `t` from javascript into `$t` in your back end script, and then passes that on to the SQL. Now, if you really need to format dates on the front end, you can make use of the handy `YAHOO.util.Date` utility. Just do something like this: ``` alert(YAHOO.util.Date.format(calDate, {format: "%Y-%m-%d" })); ``` Much easier than calling `getFullYear, getMonth`, and `getDate`
Changing the format of a date in Yahoo UI
[ "", "javascript", "yui", "" ]
I'm new to Java. I'm simply trying to build a .jar file of my applet so I can run it from my browser. This is what my directory structure looks like: ``` C:\java\pacman\src ``` contains all of the .java class files. ``` C:\java\pacman\assets ``` contains about 4-5 images and audio files. If I try to use the following code: ``` Image someFile=getCodeBase().toString() + "file.png"; ``` The result of `getCodeBase()` is ``` file:/C:/java/pacman/bin/ ``` However the following code fails to load: ``` img=new ImgHelper(getCodeBase().toString() + "assets/"); ImageIO.read(new File(img.getPath("pacman.png"))); ``` Moving my 'assets' folder to the 'bin' folder didn't fix this either. It tries loading: ``` file:/C:/java/pacman/bin/assets/pacman.png ``` saying: ``` Can't read input file! ``` But the url it gave opens fine if I paste it into run and hit enter: So to avoid myself a lot of headache i commented out the code in my ImgHelper class and did this: ``` public ImgHelper(String dir) { //this.imgDir=dir; imgDir="C:\\java\\pacman\\assets\\"; } ``` Which works perfectly. But I want to put this on a web server, and I have no idea how/what I should do to make all the images and sounds work. Any ideas? Thanks...
Why not put it all in a JAR file and then call Class.getResourceAsStream? A JAR file is better as it is a single HTTP connection rather than one HTTP connection per file. It is also much more flexible to use a Stream than a File. getResourceAsStream will work when the files are not in a JAR as well, they need to be relative to the class file. EDIT: Another thing, the File method won't work if the applet is on a server as it will be trying to open the file from the local machine (I think, I haven't tried it) rather then from the server. Even if it tried to create a file path to the server that won't work.
I agree with tofubeer about the JAR, but if you want to put the image on your server, see the tutorial on Applet images [here](http://www.realapplets.com/tutorial/ImageExample.html). The codebase will be whatever location your applet is on the server, and you can put images relative to that on the server as well. Use a media tracker along with the Applet.getImage() method to retrive the url. From the example: ``` my_gif = getImage(getDocumentBase(),"imageExample.gif"); ```
Having a lot of trouble deploying a java applet
[ "", "java", "file", "applet", "relative-path", "" ]
I'm working on a problem in C# 2.0/.NET 2.0 where I have a Sortedlist and want to search all the "values" (not the "keys") of this SortedList for a certain substring and count up how many occurrences there are. This is what I'm trying to do: ``` { Sortedlist<string,string> mySortedList; // some code that instantiates mySortedList and populates it with data List<string> myValues = mySortedList.Values; // <== does not work int namesFound = myValues.FindAll(ByName(someName)).Count; } ``` Naturally, this doesn't work because mySortedList.Values returns an IList, while "myValues" is a List. I tried "casting" the IList so that it would be accepted by myValues, but it doesn't seem to work. Of course, I can loop over mySortedList.Values in a "foreach" loop, but I don't really want to do this. Anyone have any suggestions? EDIT-1: Ok, well it looks like there isn't a native way to do this easily. I had assumed that I was just missing something, but apparently I'm not. So I guess I'm just going to do a "foreach" over the IList. Thanks for the feedback everyone! I voted everyone up 1 because I thought all the feedback was good. Thanks again! :-) EDIT-2: Looks like CMS has the answer I was looking for. The only caveat with this (as Qwertie pointed out) is that there is a potential performance penalty since it involves copying all the values to another List and then searching that list start-to-finish. So for short lists, this answer is effective. Longer lists? well that's up to you to decide...
Since the [IList Interface](http://msdn.microsoft.com/en-us/library/system.collections.ilist(VS.80).aspx) implements [IEnumerable](http://msdn.microsoft.com/en-us/library/system.collections.ienumerable(VS.80).aspx), you can actually get a `List<T>` of values using the [`List<T> (IEnumerable) Constructor`](http://msdn.microsoft.com/en-us/library/fkbw11z0(VS.80).aspx): ``` List<string> myValues = new List<string>(mySortedList.Values); ```
You can't cast the Values property to List<string> because it is not a List<string>--it is a Dictionary<TKey, TValue>.ValueCollection. But if you use [LinqBridge](http://www.albahari.com/nutshell/linqbridge.aspx) (for .NET Framework 2.0 with C# 3.0), this problem is easily solved with LINQ as follows: ``` SortedList<string, string> m = ...; int namesFound = m.Values.Where(v => v.Contains("substring")).Count(); ``` (if you're still on C# 2.0, you can use [Poor-man's LINQ](http://www.codeproject.com/KB/linq/linq2005.aspx) instead, with slightly more work)
How do I perform a FindAll() on an IList<T>? (eg. SortedList.Values)
[ "", "c#", "ilist", "sortedlist", "findall", "" ]
I have an application that I am writing that modifies data on a cached object in the server. The modifications are performed through an ajax call that basically updates properties of that object. When the user is done working, I have a basic 'Save Changes' button that allows them to Save the data and flush the cached object. In order to protect the user, I want to warn them if the try to navigate away from the page when modifications have been made to the server object if they have not saved. So, I created a web service method called IsInitialized that will return true or false based on whether or not changes have been saved. If they have not been saved, I want to prompt the user and give them a chance to cancel their navigation request. Here's my problem - although I have the calls working correctly, I can't seem to get the ajax success call to set the variable value on its callback function. Here's the code I have now. ``` ////Catches the users to keep them from navigation off the page w/o saved changes... window.onbeforeunload = CheckSaveStatus; var IsInitialized; function CheckSaveStatus() { var temp = $.ajax({ type: "POST", url: "URL.asmx/CheckIfInstanceIsInitilized", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(result) { IsInitialized = result.d; }, error: function(xmlHttpRequest, status, err) { alert(xmlHttpRequest.statusText + " " + xmlHttpRequest.status + " : " + xmlHttpRequest.responseText); } }); if (IsInitialized) { return "You currently have unprocessed changes for this Simulation."; } } ``` I feel that I might be trying to use the Success callback in an inappropriate manner. How do I set a javascript variable on the Success callback so that I can decide whether or not the user should be prompted w/ the unsaved changes message? As was just pointed out, I am making an asynchronous call, which means the rest of the code gets called before my method returns. Is there a way to use that ajax call, but still catch the window.onunload event? (without making synchronos ajax)
Since you need this behavior in the unload event, you will have to make a synchronous call instead. However it may freeze the browser window/tab dependent on how long the call will take, but because you're effectively trying to prevent the user from closing the window... Add `async: false` to your JSON to make a synchronous call.
An example of jquery page: ``` var html = $.ajax({ url: "some.php", async: false }).responseText; ``` Source: <http://api.jquery.com/jQuery.ajax/>
jQuery Ajax call - Set variable value on success
[ "", "asp.net", "javascript", "jquery", "ajax", "web-services", "" ]
There are some very good questions here on SO about file management and storing within a large project. > [Storing Images in DB - Yea or Nay?](https://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay) > [Would you store binary data in database or in file system?](https://stackoverflow.com/questions/662488/would-you-store-binary-data-in-database-or-in-file-system) The first one having some great insights and in my project i've decided to go the file route and not the DB route. A major point against using the filesystem is backup. But in our system we have a great backup scheme so i am not worried about that. The next path is how to store the actual files. And I've thought about having the files' location static at all times and create a virtual directory system in the database side of things. So links to the file don't change. The system i am building will have one global file management so all files are accessible to all users. But many that have gone the file route talk about physical directory size (if all the files are within one directory for example) So my question is, what are some tips or best practice methods in creating folders for these static files, or if i shouldn't go the virtual directory route at all. (the project is on the LAMP stack (PHP) if that helps at all)
One way is to assign a unique number to each file and use it to look up the actual file location. Then you an use that number to distribute files in different directories in the filesystem. For example you could use something like this scheme: `/images/{0}/{1}/{2}` > `{0}: file_number % 100` > `{1}: (file_number / 100) % 100` > `{2}: file_number`
I've ran into this problem some time ago for a website that was hosting a lot of files. What we did was take a GUID (which is also the Primary Key field of a file) (e.g. BCC46E3F-2F7A-42b1-92CE-DBD6EC6D6301) and store a file like this: /B/C/C/BCC46E3F-2F7A-42b1-92CE-DBD6EC6D6301/filename.ext This has certain advantages: * You can scale out the file servers over multiple servers (and assign specific directories to each one) * You don't have to rename the file * Your directories are guaranteed to be unique Hope this helps!
Tips for managing a large number of files?
[ "", "php", "directory-structure", "file-management", "" ]
I need to access the current and previous element in an IQueryable object. If I had an int array, I would do the following: ``` var array = new int[]{0,1,2,3,4}; for(var i = 1; i<array.Length ; i++) { method1(array[i-1], array[i]); } ``` I don't know to do the same with IQueryable, since it does not implement IList.
Using extension methods makes this fairly easy. ``` public static class IEnumerableExtensions { public static IEnumerable<ValueWithPrevious<T>> WithPrevious<T>(this IEnumerable<T> @this) { using (var e = @this.GetEnumerator()) { if (!e.MoveNext()) yield break; var previous = e.Current; while (e.MoveNext()) { yield return new ValueWithPrevious<T>(e.Current, previous); previous = e.Current; } } } } public struct ValueWithPrevious<T> { public readonly T Value, Previous; public ValueWithPrevious(T value, T previous) { Value = value; Previous = previous; } } ``` Usage: ``` var array = new int[] { 1, 2, 3, 4, 5 }; foreach (var value in array.WithPrevious()) { Console.WriteLine("{0}, {1}", value.Previous, value.Value); // Results: 1, 2 // 2, 3 // 3, 4 // 4, 5 } ```
**EDIT** Misread the question a bit. This code will give you consequetive elements ``` public static IEnumerable<Pair<T,T>> GroupIntoConsequetive(this IEnumerable<T> enumerable) { using ( var e = enumerable.GetEnumerator() ) { if ( !e.MoveNext() ) { yield break; } var last = e.Current; while ( e.MoveNext() ) { yield return new Pair<T,T>(last, e.Current); last = e.Current; } } } ``` I'm not sure there is default way but writing an extension method to do so shouldn't be to difficult. I'm assuming there is a simple Pair implementation ``` public static IEnumerable<Pair<T,T>> Window(this IEnumerable<T> enumerable) { using ( var e = enumerable.GetEnumerator() ) { while ( e.MoveNext() ) { var first = e.Current; if ( !e.MoveNext() ) { throw new InvalidOperationException("Need even number"); } var second = e.Current; yield return new Pair<T,T>(first,second); } } } ``` With the window you could then get the behavior you desire with the following ``` var col = GetQueryableItem(); col.Window().Select(pair => method1(pair.First, pair.Second)); ``` Quick and dirty Pair implementation ``` public struct Pair<T1,T2> { public readonly T1 First; public readonly T2 Second; public Pair(T1 first, T2 second) { First = first; Second = second; } } ```
How do I access consecutive elements in an IQueryable<T> object?
[ "", "c#", ".net", "linq", "iteration", "iqueryable", "" ]
### Duplicate: > [Unique random numbers in O(1)?](https://stackoverflow.com/questions/196017/unique-random-numbers-in-o1) I want an pseudo random number generator that can generate numbers with no repeats in a random order. For example: random(10) might return 5, 9, 1, 4, 2, 8, 3, 7, 6, 10 Is there a better way to do it other than making the range of numbers and shuffling them about, or checking the generated list for repeats? --- ### Edit: Also I want it to be efficient in generating big numbers without the entire range. --- ### Edit: I see everyone suggesting shuffle algorithms. But if I want to generate large random number (1024 byte+) then that method would take alot more memory than if I just used a regular RNG and inserted into a Set until it was a specified length, right? Is there no better mathematical algorithm for this.
You may be interested in a linear feedback shift register. We used to build these out of hardware, but I've also done them in software. It uses a shift register with some of the bits xor'ed and fed back to the input, and if you pick just the right "taps" you can get a sequence that's as long as the register size. That is, a 16-bit lfsr can produce a sequence 65535 long with no repeats. It's statistically random but of course eminently repeatable. Also, if it's done wrong, you can get some embarrassingly short sequences. If you look up the lfsr, you will find examples of how to construct them properly (which is to say, "maximal length").
A shuffle is a perfectly good way to do this (provided you do not introduce a bias using the naive algorithm). See [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
Create Random Number Sequence with No Repeats
[ "", "c++", "c", "algorithm", "random", "" ]
If I write something like this: ``` string s = @"...."......"; ``` it doesn't work. --- If I try this: ``` string s = @"...\"....."; ``` it doesn't work either. How can I add a " character to a multi line string declaration in C#?
Try this: ``` string s = @"...""....."; ```
The double character usage also works with the characters `{` and `}` when you're using `string.Format` and you want to include a literal instance of either rather than indicate a parameter argument, for example: ``` string jsString = string.Format( "var jsonUrls = {{firstUrl: '{0}', secondUrl: '{1}'}};", firstUrl, secondUrl ); ```
How can I add " character to a multi line string declaration in C#?
[ "", "c#", "string", "escaping", "" ]
I need to create a service that will return XML containing data from the database. So I am thinking about using an ASHX that will accept things like date range and POST an XML file back. I have dealt with pages pulling data from SQL Server and populating into a datagrid for visual display but never into XML for delivery, what is the best way to do this? Also if an ASHX and POST isn't the best method for delivery let me know... thanks! EDIT: These answers are great and pointing me in the right direction. I should have also mentioned that the XML format has already been decided so I can't use any automatically generated one.
Combining linq2sqlwith the XElement classes, something along the lines: ``` var xmlContacts = new XElement("contacts", (from c in context.Contacts select new XElement("contact", new XElement { new XElement("name", c.Name), new XElement("phone", c.Phone), new XElement("postal", c.Postal) ) ) ).ToArray() ) ); ``` Linq2sql will retrieve the data in a single call to the db, and the processing of the XML will be done at the business server. This splits the load better, since you don't have the sql server doing all the job.
Have you tried [DataSet.WriteXml()](http://msdn.microsoft.com/en-us/library/system.data.dataset.writexml.aspx)? You could have this be the output of a web service call.
Best method to populate XML from SQL query in ASP.NET?
[ "", "asp.net", "sql", "xml", "" ]
Hi my question is this. Suppose you have an interface that defines how a converter would be implemented. This interface could have a method loadDocument() and another convert(). Now suppose we want to have multiple converters, ConvertHTML2DOC, ConvertXML2HTML e.t.c you get the idea. Suppose you get the two formats you need to convert in 2 strings (doesn't matter HOW you get them). Now you need to create an instance of your converter and convert the documents. My question is which is better: to actually create an elaborate if statement or to load the classes through reflection with the Class class? to demonstrate I wrote a little example of what I mean. In my example I have 2 classes P1 and P2 that share an interface. I also create 50000 of them to show of the speed differences. As it turns out the normal invocation is slightly faster, but I think that in a complex example such as the one i mentioned in the beginning, the benefits of creating the classes through the Class method is more convenient and more maintainable. What are your thoughts? ``` import java.util.*; public class Test { public static void main(String[] args) { try { Random r = new Random(); Date test1start = new Date(); for (int i = 0; i<= 50000; i++){ Printable p = (Printable)Class.forName("P"+(r.nextInt(2)+1)).newInstance(); System.out.println(p.getString()); } Date test1stop = new Date(); Date test2start = new Date(); for (int i = 0; i<= 50000; i++){ Printable p; if (r.nextInt(2) == 0 ) { p = new P1(); } else { p = new P2(); } System.out.println(p.getString()); } Date test2stop = new Date(); System.out.println("Test with 'Class' invocation took "+(test1stop.getTime()-test1start.getTime())+" milliseconds."); System.out.println("Test with 'normal' invocation took "+(test2stop.getTime()-test2start.getTime())+" milliseconds."); } catch (Exception e) { } } } interface Printable { public String getString(); } class P1 implements Printable { public String getString(){ return "1"; } } class P2 implements Printable { public String getString(){ return "2"; } } ```
You should definitely follow the advice from Javier - a registry of factories is the right way to go for this problem. I've implemented it that way many times in the past, be for format translation or some other extensible "predicate" based factory solution (eg, automatic GUI generation based on reflection information). I would however suggest one addition to the design - the introduction of a common domain model (CDM) that is targeted by all translators. Say that you have formats A, B and C an that you need to support transformation between each - you get all the permutations: * A -> B * A -> C * B -> A * B -> C * C -> A * C -> B As the number of format grows, you get an explosion of transformations! A better idea is to separate each transformation into two parts - lets call it an *importer* and an *exporter*. The importer converts a format to the common domain model (CDM) while an export converts the from the CDM to some format. As an example, we decompose the conversion from A to B into the following: * A --> CDM (this is an import) * CDM --> B (this is an export) Now when you want to add a new format you need only write an importer and an exporter but you get translation to/from all other formats! Talk about extensible! It also allows for formats for which yo can read but not write and vice versa. So, the solution would be to have a registry of importer factories and a registry of exporter factories.
definitely use a factory method; but instead of a "big `if`", or name-mangling, use a "class registration" method. for this, the factory class maintains a table where each concrete class registers it's condition (in your case it's the source and target names) and the constructor (it's a 'condition->constructor' dictionary). the factory itself simply constructs the dictionary key and fetches the constructor it needs. one big advantage is that each concrete class encapsulates the condition it solves, and you can add more without changing the factory method.
Best method to create a new instance based on precondition
[ "", "java", "" ]
Which is better? 1. `@SuppressWarnings("unchecked")` 2. `@SuppressWarnings(AnnotationConstants.UNCHECKED)` Where `AnnotationConstants` is a typical constants class... ``` public final class AnnotationConstants { private AnnotationConstants() { } public static final String UNCHECKED = "unchecked"; ... } ``` I know that there are a lot of general arguments for and against constants classes--and that's exactly what I'm **not** interested in. I want to know if a constants class **specifically** for annotations is a good idea or a bad idea.
For this *specific* example I'd stick with literals. After all, you're trying to suppress warnings - if you use the wrong literal, the warning won't be suppressed, which will draw your attention to the problem.
I'd say a little bit of both, please. In Spring, you could say something like @Scope(Scopes.SESSION) or @Scope(Scopes.REQUEST), which attaches a specific kind of behavior to the annotation so I'd say *always* use a constants class, which is good for traceability. If you're just supressing warnings, there's little likelyhood that you want to really trace this, so just go with the literal.
Should I make a constants class for my annotations?
[ "", "java", "annotations", "constants", "" ]
I am constructing an array of bytes in java and I don't know how long the array will be. I want some tool like Java's StringBuffer that you can just call .append(byte b) or .append(byte[] buf) and have it buffer all my bytes and return to me a byte[] when I'm done. Is there a class that does for bytes what StringBuffer does for Strings? It does not look like the ByteBuffer class is what I'm looking for. Anyone have a good solution?
Try [`ByteArrayOutputStream`](http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html). You can use `write( byte[] )` and it will grow as needed.
Just to extend the previous answer, you can use [ByteArrayOutputStream](http://docs.oracle.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html) and it's method `public void write(byte[] b, int off, int len)`, where parameters are: > b - the data > > off - the start offset in the data > > len - the number of bytes to write If you want to use it as a "byte builder" and insert byte by byte, you can use this: ``` byte byteToInsert = 100; ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(new byte[]{byteToInsert}, 0, 1); ``` Then you can use `baos.toString()` method to convert the array to string. The advantage is when you need to set up encoding of input, you can simply use i.e.: ``` baos.toString("Windows-1250") ```
Byte array of unknown length in java
[ "", "java", "buffer", "byte", "" ]
I'm looking to start using Java Open GL, but I can't find it.
Have you tried [JOGL's website](http://jogamp.org/jogl/www/)? It looks like their most recent release can be found [here](http://jogamp.org/deployment/archive/rc/), or you can grab a nightly build [here](http://jogamp.org/deployment/autobuilds/master).
To get the latest stable version of the new JOGL 2.0 beta, go to <http://jogamp.org/deployment/webstart/>. The nightly builds are at <http://jogamp.org/deployment/autobuilds/master/>. The most recent auto build (as of this writing) is at <http://jogamp.org/deployment/autobuilds/master/jogl-b242-2010-11-28_23-03-07/>. You can see a description of their versioning at <http://jogamp.org/wiki/index.php/Jogamp_Versioning_and_Releases>. To get the old JOGL 1.1.1a (the last build before JOGL moved), go to <http://download.java.net/media/jogl/builds/archive/jsr-231-1.1.1a/>.
Where can I download JOGL?
[ "", "java", "opengl", "jogl", "" ]
Can someone show me some example for restricting user input (on input tag) in Javascript? Something that when we set the input (type="text") to only accept numeric, so it will ignore any other input except for numeric... I think it's handy for number input (such as zip, credit card, money, value, score, date etc...), and if you can please show me how to create input with pattern, something like: ``` Please Input Date: |-----------------| | / / | |-----------------| ``` PS: I heard WebForms 2.0 will support this in the future... (Acid 3 compliant browser?) input type="date" input type="time" input type="number" input type="money" But it was only news from future :D
This might help you. <http://www.w3schools.com/jsref/event_onkeydown.asp> ``` <html> <body> <script type="text/javascript"> function noNumbers(e) { var keynum; var keychar; var numcheck; if(window.event) // IE { keynum = e.keyCode; } else if(e.which) // Netscape/Firefox/Opera { keynum = e.which; } keychar = String.fromCharCode(keynum); numcheck = /\d/; return !numcheck.test(keychar); } </script> <form> <input type="text" onkeydown="return noNumbers(event)" /> </form> </body> </html> ```
This question has already an accepted answer, but I think there is a better solution to this. You don't have to implement that yourself on keydown etc., there are libraries for that. They call the technique you describe "input masks". Check out [this jQuery plugin](http://digitalbush.com/projects/masked-input-plugin/) it does exactly what you want.
restrict user input using javascript
[ "", "javascript", "html", "user-interface", "input", "" ]
For a project I need to develop an app in Adobe AIR, I choose for the HTML/Ajax version. For now the project is quite small, and contains a login part, and a details part. What I would like to do is on app launch show login.html, and if that was succesfull show/browse-to details.html . My question is if there is some quick and dirty way to save some of the info I received from the login (such as userid) in a session/application container? I briefly looked into their `BlackBookSafe` example, but what I saw there is that although there are multiple pages, they actually keep the `blackbooksafe.html` open all the time, and load the childpages into the body, thus saving session data in `blackbooksafe.html` But in my eyes it creates kind of a mess, and would rather have every page take care of itself (javascript wise), which will make it a bit easier to read.
I saw a few hacks, like saving data on a file (used in one of Adobe's examples), or putting it in the database, but I didn't find any quick non-persistent data store. I would love to see a key/value dictionary hooked on to the NativeApplication object, where I could add my non-persistent data, but that doesn't exists. In the end I went for an IFRAME solution, where the parent page stores the non-persistent data.
Okay, I realize this thread is OLD but if it helps someone. My solution feels like a complete hack - shame on Adobe - but it works. # Store the data as JSON strings in the menu data Menus persist across page loads, and you can assign a custom data to a menu. So far it seems to only like simple data types, like strings or ints. So the solution is to download json2.js (<http://json.org>) and use it's `stringify()` and `parse()` commands to convert your application state into a JSON string then store that in the `.data` member of a menu. I stored it in the first menu. in the `items` list. Using `jQuery`, my application code looked like this: ``` function InitApp() { // check before we create the menu for the very first time. var menu = air.NativeApplication.nativeApplication.menu; var firstMenu = menu.items[0]; var dataStore = firstMenu.data; if (dataStore == null) { air.trace("Create Menu Data Store"); var dataObj = { msg: "Message Object", status: 1 }; var dataObjStr = JSON.stringify(dataObj); firstMenu.data = dataObjStr; dataStore = firstMenu.data; air.trace("Created menu data store"); air.trace(dataObjStr); } else { var dataStore = firstMenu.data; var obj = JSON.parse(dataStore); air.trace("Retrieved Menu Data Store"); air.trace(obj.msg); } BuildMenu(); // check after we create our menu firstMenu = air.NativeApplication.nativeApplication.menu.items[0]; firstMenu.data = dataStore; // pass it along. } $(document).ready(InitApp); ``` This data vanishes when the application is closed, so it is only persistent while the app is open. The real answer would have been for nativeApplication to support the EXACT SAME FEATURE as the menus! Note: I wrote this on a Mac, so you'd have to adjust the code for using NativeWindow.menu for windows / linux.
Does Adobe AIR for JS support some sort of non-persistent data container?
[ "", "javascript", "air", "session-state", "" ]
I'd like to construct a message with unknown length or number of arguments. I took a simple template like ``` template <typename T> class Argument { public: int size; int type; T data; }; ``` and with some overloaded ``` addMessage (int value) { Argument<int> *a = new Argument<int>; vec.push_back(a); } ``` (same for string and so on) I try to push it all into one vector. I tried ``` std::vector<Argument* > vec; std::vector<Argument<typename T>* > vec; std::vector<Argument<>* > vec; ``` but nothing of this seems to work. Is there a way to do this? Thanks in advance.
Option 1 : make sure that all different types of arguments derive from a base class and use pointers to that class. Note that this option is risky in terms of memory management. You might want to make it safer by using boost::shared\_ptr instead of pointers. Otherwise, you must manually clean up when an item is being removed from the vector. Option 2 (my personal favorite) : use [Boost.Variant](http://www.boost.org/doc/libs/1_38_0/doc/html/variant.html) to make a typedef of all possible argument types and use that typedef as the argument type in std::vector ``` typedef boost::variant<ArgumentType1, ArgumentType2, ArgumentType3> ArgumentType; std::vector<ArgumentType> vec; ```
The easiest way to do this would be to have a base Argument class, which is not templated, and then have the specific data types derive from it. (You could even make the templated version derive from the base class directly and just use those two classes.) Then you store them as pointers in a vector. This does require having some sort of functions to access the argument values and perform any conversions as required.
How to put different template types into one vector
[ "", "c++", "templates", "polymorphism", "" ]
the code below(in C++) is what I am trying the convert into C# ``` DWORD Func_X_4(DWORD arg1, DWORD arg2, DWORD arg3) { LARGE_INTEGER result = {1, 0}; LARGE_INTEGER temp1 = {0}; LARGE_INTEGER temp2 = {0}; LARGE_INTEGER temp3 = {0}; LARGE_INTEGER temp4 = {0}; for(int x = 0; x < 32; ++x) { if(arg2 & 1) { temp1.LowPart = arg3; temp1.HighPart = 0; temp2.QuadPart = temp1.QuadPart * result.QuadPart; temp3.LowPart = arg1; temp3.HighPart = 0; temp4.QuadPart = temp2.QuadPart % temp3.QuadPart; result.QuadPart = temp4.QuadPart; } arg2 >>= 1; temp1.LowPart = arg3; temp1.HighPart = 0; temp1.QuadPart *= temp1.QuadPart; temp2.LowPart = arg1; temp2.HighPart = 0; temp3.QuadPart = temp1.QuadPart % temp2.QuadPart; arg3 = temp3.LowPart; if(!arg2) break; } return result.LowPart; } ``` Here I tried to translate the code,but it's too messy and I never worked with Large integers before. Structure: ``` public struct LARGE_INTEGER { UInt32 LowPart; Int32 HighPart; Int32 QuadPart; } ``` Translated function: ``` public Int32 Func_X_4(Int32 arg1, Int32 arg2, Int32 arg3) { LARGE_INTEGER result = {1, 0}; //this and the four below,are they correct? LARGE_INTEGER temp1 = {0, 0}; LARGE_INTEGER temp2 = {0, 0}; LARGE_INTEGER temp3 = {0, 0}; LARGE_INTEGER temp4 = {0, 0}; for(int x = 0; x < 32; ++x) { if(arg2 & 1==0) //correct? { temp1.LowPart = arg3; temp1.HighPart = 0; temp2.QuadPart = temp1.QuadPart * result.QuadPart; temp3.LowPart = arg1; temp3.HighPart = 0; temp4.QuadPart = temp2.QuadPart % temp3.QuadPart; result.QuadPart = temp4.QuadPart; } arg2 >>= 1; temp1.LowPart = arg3; temp1.HighPart = 0; temp1.QuadPart *= temp1.QuadPart; temp2.LowPart = arg1; temp2.HighPart = 0; temp3.QuadPart = temp1.QuadPart % temp2.QuadPart; arg3 = temp3.LowPart; if(arg2 != 0) //correct? break; } return result.LowPart; } ``` Problems: The first problem is that I haven't found a LARGE\_INTEGER type variable in C#,so I created a strucure,I'd like to know if there is actually. As for the second problem,the function is not right,nothing worked. Any help on that particular question will be greatfuly appreciated! Thank you in advance.
A direct translation of the LARGE\_INTEGER structure would be: ``` [StructLayout(LayoutKind.Explicit, Size=8)] struct LARGE_INTEGER { [FieldOffset(0)]public Int64 QuadPart; [FieldOffset(0)]public UInt32 LowPart; [FieldOffset(4)]public Int32 HighPart; } ``` It's like a **union** in C, where `QuadPart` is an 8-byte value, with `LowPart` occupying the first 4 bytes and `HighPart` occupying the high 4 bytes.
Its Int64. Based on <http://msdn.microsoft.com/en-us/library/aa383713.aspx>, its a 64 bit-signed integer.
How to declarate LARGE_INTEGER in C#
[ "", "c#", "integer", "" ]
Very occasionally when making a http request, I am waiting for an age for a response that never comes. What is the recommended way to cancel this request after a reasonable period of time?
Set the HTTP request timeout.
The timeout parameter to [urllib2.urlopen](http://docs.python.org/library/urllib2.html#urllib2.urlopen), or [httplib](http://docs.python.org/library/httplib.html#httplib.HTTPConnection). The original urllib has no such convenient feature. You can also use an asynchronous HTTP client such as [twisted.web.client](http://twistedmatrix.com/documents/8.1.0/api/twisted.web.client.html), but that's probably not necessary.
Timeout on a HTTP request in python
[ "", "python", "httpwebrequest", "" ]
I did something similar to [this](http://www.postneo.com/projects/pyxml/), but couldn't find a way to write the result to an xml file.
The code on the web page you linked to uses `doc.toprettyxml` to create a string from the XML DOM, so you can just write that string to a file: ``` f = open("output.xml", "w") try: f.write(doc.toprettyxml(indent=" ")) finally: f.close() ``` In Python 2.6 (or 2.7 I suppose, whenever it comes out), you can use the "`with`" statement: ``` with open("output.xml", "w") as f: f.write(doc.toprettyxml(indent=" ")) ``` This also works in Python 2.5 if you put ``` from __future__ import with_statement ``` at the beginning of the file.
coonj is kind of right, but xml.dom.ext.PrettyPrint is part of the increasingly neglected PyXML extension package. If you want to stay within the supplied-as-standard minidom, you'd say: ``` f= open('yourfile.xml', 'wb') doc.writexml(f, encoding= 'utf-8') f.close() ``` (Or using the ‘with’ statement as mentioned by David to make it slightly shorter. Use mode 'wb' to avoid unwanted CRLF newlines on Windows interfering with encodings like UTF-16. Because XML has its own mechanisms for handling newline interpretation, it should be treated as a binary file rather than text.) If you don't include the ‘encoding’ argument (to either writexml or toprettyxml), it'll try to write a Unicode string direct to the file, so if there are any non-ASCII characters in it, you'll get a UnicodeEncodeError. Don't try to .encode() the results of toprettyxml yourself; for non-UTF-8 encodings this can generate non-well-formed XML. There's no ‘writeprettyxml()’ function, but it's trivially simple to do it yourself: ``` with open('output.xml', 'wb') as f: doc.writexml(f, encoding= 'utf-8', indent= ' ', newl= '\n') ```
How to save an xml file to disk?
[ "", "python", "xml", "" ]
Where can I find precompiled Python SWIG SVN bindings for Windows?
The (old) [Windows binaries](http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=8100) page at tigris.org contains an installer for *python bindings for SVN*. View the source for the SWIG bindings at [/trunk/subversion/bindings/swig/python](http://svn.apache.org/viewvc/subversion/trunk/subversion/bindings/swig/python/). (May 2010 - The *Subversion project* is transitioning into its new role as an Apache Software Foundation, many resources are changing address. Updated source link. ) (November 2010 - more Windows binaries) The [win32svn](http://alagazam.net/) project, *Subversion for Windows, by alagazam*, is a win32 build of subversion. As of November 2010, it contains a 1.6.13 build dated 2010-10-05, *including `python 2.6` bindings*. (January 2011 - keeping up: 2010-12-17, [1.6.15](http://sourceforge.net/projects/win32svn/files/1.6.15/), Python 2.6.6.) (May 2011 - 2011-03-14, [1.6.16](http://sourceforge.net/projects/win32svn/files/1.6.16/), Python 2.6.6) (June 2011 - 2011-06-03, [1.6.17](http://sourceforge.net/projects/win32svn/files/1.6.17/), Python 2.6.6) (October 2011 - 2011-10-15, [1.7.0](http://sourceforge.net/projects/win32svn/files/1.7.0/)), Python 2.6.6 and 2.7.2) (December 2011 - 2011-12-12, [[1.7.2]](http://sourceforge.net/projects/win32svn/files/1.7.2/), Python 2.7.2 and 2.6.6) (February 2012 - 2012-02-18, [[1.7.3]](http://sourceforge.net/projects/win32svn/files/1.7.3/), Python 2.5.4 , 2.6.6 and 2.7.2 ) (March 2012 - 2012-03-08 [1.7.4](http://sourceforge.net/projects/win32svn/files/1.7.4/), Python 2.5.4 , 2.6.6 and 2.7.2) (May 2012 - 2012-05-17 [1.7.5](http://sourceforge.net/projects/win32svn/files/1.7.5/), Python 2.5.4 , 2.6.6 and 2.7.3) (August 2012 - 2012-08-15 [1.7.6](http://sourceforge.net/projects/win32svn/files/1.7.6/), Python 2.5.4, 2.6.6 and 2.7.3. No Python 3 version) (December 2012 - 2012-12-20 [1.7.8](http://sourceforge.net/projects/win32svn/files/1.7.8/), Python 2.5.4, 2.6.6 and 2.7.3.) (November 2013 - 2013-11-25 [1.8.5](http://sourceforge.net/projects/win32svn/files/1.8.5/), Python 2.6.6 and 2.7.6) (May 2016 - 2016-05-04 [1.8.16](https://sourceforge.net/projects/win32svn/files/1.8.16/), Python 2.6.6 and 2.7.9)
You can find working bindings in the Trac project: <http://trac.edgewall.org/wiki/TracSubversion> See the attachment: svn-win32-1.6.15\_py\_2.7.zip
Python SVN bindings for Windows
[ "", "python", "windows", "svn", "swig", "precompiled", "" ]
I am working with Python's SimpleCookie and I ran into this problem and I am not sure if it is something with my syntax or what. Also, this is classwork for my Python class so it is meant to teach about Python so this is far from the way I would do this in the real world. Anyway, so basically I am keeping information input into a form in a cookie. I am attempting to append to the previous cookie with the new information entered. But for some reason on the third entry of data the cookie suddenly gets "\" in it. I am not sure where they are coming from though. This is the type of output I am getting: > "\"\\"\\\\"test:more\\\\":rttre\\":more\":and more" ``` #!/usr/local/bin/python import cgi,os,time,Cookie #error checking import cgitb cgitb.enable() if 'HTTP_COOKIE' in os.environ: cookies = os.environ['HTTP_COOKIE'] cookies = cookies.split('; ') for myCookie in cookies: myCookie = myCookie.split('=') name = myCookie[0] value = myCookie[1] if name == 'critter' : hideMe = value #import critterClass #get info from form form = cgi.FieldStorage() critterName = form.getvalue('input') input2 = form.getvalue('input2') hiddenCookie = form.getvalue('hiddenCookie') hiddenVar = form.getvalue('hiddenVar') #make cookie cookie = Cookie.SimpleCookie() #set critter Cookie if critterName is not None: cookie['critter'] = critterName #If already named else: #if action asked, append cookie if input2 is not None: cookie['critter'] = hideMe+":"+input2 else: cookie['critter'] = "default" print cookie print "Content-type: text/html\n\n" if ((critterName is None) and (input2 is None)): print """ <form name="critter" id="critter" method="post" action="critter.py"> <label for="name">Name your pet: <input type="text" name="input" id="input" /></label> <input type="submit" name="submit" id="submit" value="Submit" /> </form> """ else: formTwo =""" <form name="critter2" id="critter2" method="post" action="critter.py"> <label for="name">%s wants to: <input type="text" name="input2" id="input2" /></label> <input type="hidden" name="hiddenVar" id="hiddenVar" value="%s" /> <input type="submit" name="submit" id="submit" value="Submit" /> </form> [name,play,feed,mood,levels,end] """ print formTwo % (critterName,critterName) if 'HTTP_COOKIE' in os.environ: cookies = os.environ['HTTP_COOKIE'] cookies = cookies.split('; ') for myCookie in cookies: myCookie = myCookie.split('=') name = myCookie[0] value = myCookie[1] if name == 'critter' : print "name"+name print "value"+value ```
As explained by others, the backslashes are escaping double quote characters you insert into the cookie value. The (hidden) mechanism in action here is the [`SimpleCookie`](http://docs.python.org/library/cookie.html#Cookie.SimpleCookie) class. The [`BaseCookie.output()`](http://docs.python.org/library/cookie.html#Cookie.BaseCookie.output) method returns a string representation suitable to be sent as HTTP headers. It will insert escape characters (backslashes) before double quote characters and **before backslash characters**. The ``` print cookie ``` statement activates `BaseCookie.output()`. On each trip your string makes through the cookie's `output()` method, backslashes are multiplied (starting with the 1st pair of quotes). ``` >>> c1=Cookie.SimpleCookie() >>> c1['name']='A:0' >>> print c1 Set-Cookie: name="A:0" >>> c1['name']=r'"A:0"' >>> print c1 Set-Cookie: name="\"A:0\"" >>> c1['name']=r'"\"A:0\""' >>> print c1 Set-Cookie: name="\"\\\"A:0\\\"\"" >>> ```
I'm not sure, but it looks like regular Python string escaping. If you have a string containing a backslash or a double quote, for instance, Python will often print it in escaped form, to make the printed string a valid string literal. The following snippet illustrates: ``` >>> a='hell\'s bells, \"my\" \\' >>> a 'hell\'s bells, "my" \\' >>> print a hell's bells, "my" \ ``` Not sure if this is relevant, perhaps someone with more domain knowledge can chime in.
Backslashes being added into my cookie in Python
[ "", "python", "" ]
I am basing my question and example on Jason's answer in [this](https://stackoverflow.com/questions/662630/javascript-form-bypassing-default-behaviour-for-ajax/664938#664938) question I am trying to avoid using an `eventListener`, and just to call `handleClick` `onsubmit`, when the submit button is clicked. Absolutely nothing happens with the code I have. Why is `handleClick` not being called? ``` <html> <head> <script type="text/javascript"> function getRadioButtonValue(rbutton) { for (var i = 0; i < rbutton.length; ++i) { if (rbutton[i].checked) return rbutton[i].value; } return null; } function handleClick(event) { alert("Favorite weird creature: "+getRadioButtonValue(this["whichThing"])); event.preventDefault(); // disable normal form submit behavior return false; // prevent further bubbling of event } </script> </head> <body> <form name="myform" onSubmit="JavaScript:handleClick()"> <input name="Submit" type="submit" value="Update" onClick="JavaScript:handleClick()"/> Which of the following do you like best? <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p> <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p> <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p> </form> </body> </html> ``` edit: Please do not suggest a framework as a solution. Here are the relevant changes I have made to the code, which results in the same behavior. ``` function handleClick() { alert("Favorite weird creature: "+getRadioButtonValue(document.myform['whichThing']))); event.preventDefault(); // disable normal form submit behavior return false; // prevent further bubbling of event } </script> </head> <body> <form name="aye">; <input name="Submit" type="submit" value="Update" action="JavaScript:handleClick()"/> Which of the following do you like best? <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p> <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p> <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p> </form> ```
In this bit of code: ``` getRadioButtonValue(this["whichThing"])) ``` you're not actually getting a reference to anything. Therefore, your radiobutton in the getradiobuttonvalue function is undefined and throwing an error. **EDIT** To get the value out of the radio buttons, grab the [JQuery](http://jquery.com/) library, and then use this: ``` $('input[name=whichThing]:checked').val() ``` **Edit 2** Due to the desire to reinvent the wheel, here's non-Jquery code: ``` var t = ''; for (i=0; i<document.myform.whichThing.length; i++) { if (document.myform.whichThing[i].checked==true) { t = t + document.myform.whichThing[i].value; } } ``` or, basically, modify the original line of code to read thusly: ``` getRadioButtonValue(document.myform.whichThing)) ``` **Edit 3** Here's your homework: ``` function handleClick() { alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing)); //event.preventDefault(); // disable normal form submit behavior return false; // prevent further bubbling of event } </script> </head> <body> <form name="aye" onSubmit="return handleClick()"> <input name="Submit" type="submit" value="Update" /> Which of the following do you like best? <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p> <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p> <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p> </form> ``` Notice the following, I've moved the function call to the Form's "onSubmit" event. An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button. I also removed the unneeded "JavaScript" in front of the function name, and added an explicit RETURN on the value coming out of the function. In the function itself, I modified the how the form was being accessed. The structure is: **document.[THE FORM NAME].[THE CONTROL NAME]** to get at things. Since you renamed your from aye, you had to change the document.myform. to document.aye. Additionally, the *document.aye["whichThing"]* is just wrong in this context, as it needed to be *document.aye.whichThing*. The final bit, was I commented out the **event.preventDefault();**. that line was not needed for this sample. **EDIT 4** Just to be clear. **document.aye["whichThing"]** will provide you direct access to the selected value, but **document.aye.whichThing** gets you access to the collection of radio buttons which you then need to check. Since you're using the "getRadioButtonValue(object)" function to iterate through the collection, you need to use **document.aye.whichThing**. See the difference in this method: ``` function handleClick() { alert("Direct Access: " + document.aye["whichThing"]); alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing)); return false; // prevent further bubbling of event } ```
You can either use javascript url form with ``` <form action="javascript:handleClick()"> ``` Or use onSubmit event handler ``` <form onSubmit="return handleClick()"> ``` In the later form, if you return false from the handleClick it will prevent the normal submision procedure. Return true if you want the browser to follow normal submision procedure. Your onSubmit event handler in the button also fails because of the `Javascript:` part **EDIT:** I just tried this code and it works: ``` <html> <head> <script type="text/javascript"> function handleIt() { alert("hello"); } </script> </head> <body> <form name="myform" action="javascript:handleIt()"> <input name="Submit" type="submit" value="Update"/> </form> </body> </html> ```
Calling Javascript from a html form
[ "", "javascript", "html", "forms", "dom-events", "" ]
I'm using `std::string` and need to left pad them to a given width. What is the recommended way to do this in C++? Sample input: ``` 123 ``` pad to 10 characters. Sample output: ``` 123 ``` *(7 spaces in front of 123)*
std::setw (setwidth) manipulator ``` std::cout << std::setw (10) << 77 << std::endl; ``` or ``` std::cout << std::setw (10) << "hi!" << std::endl; ``` outputs padded 77 and "hi!". if you need result as string use instance of std::stringstream instead std::cout object. ps: responsible header file `<iomanip>`
``` void padTo(std::string &str, const size_t num, const char paddingChar = ' ') { if(num > str.size()) str.insert(0, num - str.size(), paddingChar); } int main(int argc, char **argv) { std::string str = "abcd"; padTo(str, 10); return 0; } ```
Padding stl strings in C++
[ "", "c++", "string", "padding", "stdstring", "" ]
I've got a working app that serializes a document (of type IDocument) to disk. From there there's another app that I've made that can open that document (IDocument implements IPrintDocument) for viewing. Let's assume that I've written an IDocument to disk, and then a week later a field gets added to the IDocument object. Both the program that writes the files and the one that opens them are updated with this new 'version' of IDocument. It will then break (I assume - haven't had a chance to check, I'm looking ahead here) when trying to open the previous IDocument version. Is there a known pattern that alleviates this kind of problem?
Yes - use a serialization mechanism which is [tolerant to versioning](http://code.google.com/apis/protocolbuffers/docs/proto.html#updating). Predictably enough, I'm going to suggest using [Google's Protocol Buffers](http://code.google.com/apis/protocolbuffers/), for which there are at least [two](http://code.google.com/p/protobuf-csharp-port/) [viable](http://code.google.com/p/protobuf-net/) .NET implementations. So long as you're careful, Protocol Buffers are both backward and forward compatible - you can read a new message with old code and vice versa, and the old code will still be able to preserve the information it doesn't understand. Another alternative is XML, whether using .NET's built-in XML serialization or not. The built-in serialization isn't particularly flexible in terms of versioning as far as I'm aware.
The .net built-in serialization is an option, but it does requires you to add place holders on the specific pieces that you want to extend in the future. You add place holders for the extra elements/attributes like the following code: ``` [XmlAnyElement()] public XmlElement[] ExtendedElements { get; set; } [XmlAnyAttribute()] public XmlAttribute[] ExtendedAttributes { get; set; } ``` By adding the above in the involved classes, you can effectively read a information saved that has extra elements/attributes, modify the normal properties that the software knows how to handle and save it. This allows for both backwards and forward compatibility. When adding a new field, just add the desired property. Note that the above is limited to extend in the specified hooks. **Update:** As Jon mentioned in the comment, the above will only work for xml serialization. As far as I know binary serialization doesn't support something similar. In binary serialization you can get both old/new version of the app to be able to read each other serialized info (.net 2.0+), but if you save it back you will loose the extra info the version doesn't handles. Starting at .net 2.0 the de-serialization process ignores the extra data, if you combine that with optional fields you can effectively get both apps to read other version's formats. The problem is that the data isn't hold by the class like in the xml fields. Some related links: <http://msdn.microsoft.com/en-us/library/system.runtime.serialization.serializationbinder.aspx>, [http://msdn.microsoft.com/en-us/library/ms229752.aspx](http://msdn.microsoft.com/en-us/library/ms229752(VS.85).aspx) If you don't want xml serialization, I would go with Jon's approach. Ps. I am unaware if there is some good third party implementation, that we can access, that extends the binary serialization to hold and save the extra data.
versioning serialized files
[ "", "c#", "design-patterns", "serialization", "" ]
I am building a REST based API (Read only) for accessing services of my application. I plan on writing a web application that will leverage these APIs to provide basic information on the status of the application. I plan to use AJAX (using jQuery) to show the information. Originally I planned on using Grails, Spring MVC, RoR or one of the web frameworks to handle the back end of my application. The REST APIs I will be providing though are already built on a stanalone REST framework so I would only be leveraging the web framework for the core application and not the business logic. In the future, I might need the server side framework to handle other tasks but for now most of the work is done in the REST APIs. My question is, should I bother with using a web application framework on the server side? I should be able to make all the API calls I need from AJAX directly from the browser. I cannot think of much I would need to do on the server side. Would it make sense to have the application be standard HTML + AJAX + REST?
Its hard to say without actually knowing more about your current setup. This is what your situation sounds like: * You already have an app ready to go with all of the business logic contained. Sounds like its written in Java? * You already have the services written and exposed through a REST api using some other standalone framework. Meaning that if you wanted to, you could access the data right now with the browser without any extra work. * You have not yet built the web application, but when you do, it will get all of its content from the REST api using XHR and jquery. I say that, because otherwise, I would think that you would already be using some kind of framework to generate the other content. If I am correct in my assumptions, then I would say that you have no need for an additional framework layer. Grails, RoR, SpringMVC my use ajax, and aid in exposing REST services, but the bulk of what they provide is an easy way to make an application that must generate html on the server, deal with form submissions, and handle sessions in a request/response cycle. It doesn't really sound like you'll be doing any of that, and it will likely make your app more complicated. If you did at some point need the things that rails etc. provides, I would say that you may not need to use rails to expose the rest apis you have now. You could use rails just for what you need, and continue to use what you have for the REST api.
Well, the AJAX calls need to pull data from a server somewhere. If the goal is to avoid a complicated setup on the server side, CherryPy can keep the server side code VERY small. I've written a simple exapmle below. The first class would be where you put the logic for your ReST API. The code below the class is all you need to get the server up and running. Install Python 2.6, save the code below to restExample.py. Then in your command line run the python file by doing "python restExample.py". Point your browser to <http://localhost:8080/blog/999> and see some JSON come back. ``` import cherrypy import json # Create the controller class Blog_Controller(object): def get(self, entryID): cherrypy.response.headers['Content-Type'] = 'application/json' return json.dumps({'title':'Entry Title from DB', 'entry_text': 'Text From DB'}) def update(self, entryID, titleFromPOSTFormInput, textFromPOSTFormInput): # Update DB with passed in arguments. entryID comes from URL, # other two entries come from POST cherrypy.response.headers['Content-Type'] = 'application/json' return json.dumps({'success':True}) # Setup URL routes d = cherrypy.dispatch.RoutesDispatcher() d.connect(name='blog_entry', route='blog/:entryID', action='get', controller=Blog_Controller(), conditions={'method': ['GET']}) d.connect(name='blog_entry', route='blog/update/:entryID', action='update', controller=Blog_Controller(), conditions={'method': ['POST']}) config = { '/' : { 'request.dispatch': d } } cherrypy.tree.mount(root=None, config=config) # Start the webserver engine = cherrypy.engine try: engine.start() except: sys.exit(1) else: engine.block() ```
AJAX Using a REST API Without Server Side Framework
[ "", "java", "jquery", "ruby-on-rails", "ajax", "rest", "" ]
Just out of curiosity ... is it possible to programmatically get the MSIL of a delegate? I'm curious because I've been toying with the idea of a distributed computing system where you can simply write programs, and the program itself would be distributed to each disparate node where work would occur. I know you could do it by copying the actual assembly over the network and loading that in an appdomain, but I think it would be really interesting to have a simpler model to work with. thanks!
How is copying an assembly to another machine and loading it in an appdomain any more complex than the solution you're thinking of?
What about the dependencies of the delegate code -- this might possibly work using CodeDom reflection emit, but if the delegate calls anything outside itself (even framework code), how are you going to ensure it exists on the target machine(s)? Lots of Assembly.Load() code? By the way: if you build a dynamically changing distributed system along these lines, you ain't gonna get me to maintain or operate it! Imagine doing fault isolation or trying to do anything like comprehensive testing...
Possible to get MSIL of a C# Delegate?
[ "", "c#", "cil", "" ]
I have an `Object[]` array, and I am trying to find the ones that are primitives. I've tried to use `Class.isPrimitive()`, but it seems I'm doing something wrong: ``` int i = 3; Object o = i; System.out.println(o.getClass().getName() + ", " + o.getClass().isPrimitive()); ``` prints `java.lang.Integer, false`. Is there a right way or some alternative?
The types in an `Object[]` will never *really* be primitive - because you've got references! Here the type of `i` is `int` whereas the type of the object referenced by `o` is `Integer` (due to auto-boxing). It sounds like you need to find out whether the type is a "wrapper for primitive". I don't think there's anything built into the standard libraries for this, but it's easy to code up: ``` import java.util.*; public class Test { public static void main(String[] args) { System.out.println(isWrapperType(String.class)); System.out.println(isWrapperType(Integer.class)); } private static final Set<Class<?>> WRAPPER_TYPES = getWrapperTypes(); public static boolean isWrapperType(Class<?> clazz) { return WRAPPER_TYPES.contains(clazz); } private static Set<Class<?>> getWrapperTypes() { Set<Class<?>> ret = new HashSet<Class<?>>(); ret.add(Boolean.class); ret.add(Character.class); ret.add(Byte.class); ret.add(Short.class); ret.add(Integer.class); ret.add(Long.class); ret.add(Float.class); ret.add(Double.class); ret.add(Void.class); return ret; } } ```
[commons-lang](http://commons.apache.org/lang/) [`ClassUtils`](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ClassUtils.html) has relevant *methods*. The new version has: ``` boolean isPrimitiveOrWrapped = ClassUtils.isPrimitiveOrWrapper(object.getClass()); ``` The old versions have `wrapperToPrimitive(clazz)` method, which will return the *primitive* correspondence. ``` boolean isPrimitiveOrWrapped = clazz.isPrimitive() || ClassUtils.wrapperToPrimitive(clazz) != null; ```
Determining if an Object is of primitive type
[ "", "java", "reflection", "" ]
I have a variable d that I use like this: ``` $(function() { for(i = 1; i <= 31; i++) { var d = '#days' + i; if ($(d).attr("id").substr(4,2) == 11) { $(d).addClass("date_has_event"); //console.log("diez"); } else { console.log("otro"); } } } ``` However I get the following error in firebug: ``` $(d).attr("id") is undefined index.html (L23) (?)()() jquery.min.js (L27) onreadystatechange()() jquery.min.js (L27) onreadystatechange()() jquery.min.js (L21) nodeName()([function(), function()], function(), undefined) onreadystatechange()() ``` I really don't understand why. Does anyone know? --- **Edit** I'm sorry for the poor explanation I had to run, here's what's going on a little bit more detailed. I am generating a calendar using javascript. each td has a different id (hence the #days + i) and I am running it from 1 to 31 so I can cover the longer months. However I am getting the error I mentioned above. I am also using the jQuery library to enable me to select more easily (i.e. instead of getElementById just #days)
Why not just check if `i == 11`, then do your processing on it? It would still only fire on `$('#days11')`. Edit: If you need to make sure the element exists as well, just slap that into the conditional. ``` $(function(){ for(i = 1; i <= 31; i++){ var d = '#days' + i; // if($(d) && i == 11){ if(i == 11){ $(d).addClass("date_has_event"); //console.log("diez"); }else{ console.log("otro"); } } } ```
Ok, new answer. the way you are doing this is not very "jqueryish". lets step back a bit. from what I can tell you have an html structure something like: ``` <div id="days1"></div> <div id="days2"></div> ... ``` You are then running this against every item with a days(num) id? A better solution is this, if you want to add a class to every element with a date in it, first apply a class: ``` <div class="days"></div> <div class="days"></div> ``` Your code can then be ``` $(function(){ $(".days").each(function(i){ if($(this).substr(4,2) == 11){ $(this).addClass("date_has_event"); } }); }); ```
$(d).attr("id") is undefined javascript
[ "", "javascript", "jquery", "firebug", "" ]
I asked [a question about callbacks](https://stackoverflow.com/questions/615642/does-this-fit-your-definition-of-a-callback/615752#615752) and arrived at another question (see comment). How is a closure different from a callback?
Check the introduction in this: <http://jibbering.com/faq/faq_notes/closures.html>. It can help you understand better how closures relate to functions. Here is a set of closure examples: <http://www.javascriptkit.com/javatutors/closures2.shtml> Basically, the callback is like a function pointer. The bit that makes it a closure, is when that function accesses anything on the context where it lives, like variables outside it. When that happens, the function will use the current values of the variables (as opposed to copy them). See example 4.
In simple words: a callback using context variables is a closure.
How is a closure different from a callback?
[ "", "javascript", "closures", "callback", "" ]
OK my client wants to show a buy both feature in the cart, if they have 1 particular item type in the cart they want it to show up for another particular item type so if they buy both they can save $50 off the total. I am trying to wrap my head around what would be the best way to set this up so it couldn't be easily hacked (ie: adding both to the cart then removing one and keeping the discount) does anyone have some general ideas in theory? Thanks.
Why not perform the check right before they submit the order? that way, everytime they get to the submit order page, it will check if both items are present.
easy enough - always calculate the final price on the fly based on the current cart contents. The issue you mention seems like it would only be a problem if you were calculating the final price and caching it somehow.
PHP: Buy both and save $50?
[ "", "php", "php4", "" ]
How does std::vector implement the management of the changing number of elements: Does it use realloc() function, or does it use a linked list? Thanks.
It uses the allocator that was given to it as the second template parameter. Like this then. Say it is in push\_back, let `t` be the object to be pushed: ``` ... if(_size == _capacity) { // size is never greater than capacity // reallocate T * _begin1 = alloc.allocate(_capacity * 2, 0); size_type _capacity1 = _capacity * 2; // copy construct items (copy over from old location). for(size_type i=0; i<_size; i++) alloc.construct(_begin1 + i, *(_begin + i)); alloc.construct(_begin1 + _size, t); // destruct old ones. dtors are not allowed to throw here. // if they do, behavior is undefined (17.4.3.6/2) for(size_type i=0;i<_size; i++) alloc.destroy(_begin + i); alloc.deallocate(_begin, _capacity); // set new stuff, after everything worked out nicely _begin = _begin1; _capacity = _capacity1; } else { // size less than capacity // tell the allocator to allocate an object at the right // memory place previously allocated alloc.construct(_begin + _size, t); } _size++; // now, we have one more item in us ... ``` Something like that. The allocator will care about allocating memory. It keeps the steps of allocating memory and constructing object into that memory apart, so it can preallocate memory, but not yet call constructors. During reallocate, the vector has to take care about exceptions being thrown by copy constructors, which complicates the matter somewhat. The above is just some pseudo code snippet - not real code and probably contains many bugs. If the size gets above the capacity, it asks the allocator to allocate a new greater block of memory, if not then it just constructs at the previously allocated space. The exact semantics of this depend on the allocator. If it is the standard allocator, construct will do ``` new ((void*)(_start + n)) T(t); // known as "placement new" ``` And the allocate `allocate` will just get memory from `::operator new`. `destroy` would call the destructor ``` (_start + n)->~T(); ``` All that is abstracted behind the allocator and the vector just uses it. A stack or pooling allocator could work completely different. Some key points about `vector` that are important * After a call to `reserve(N)`, you can have up to N items inserted into your vector without risking a reallocation. Until then, that is as long as `size() <= capacity()`, references and iterators to elements of it remain valid. * Vector's storage is contiguous. You can treat &v[0] as a buffer containing as many elements you have currently in your vector.
One of the hard-and-fast rules of vectors is that the data will be stored in one contiguous block of memory. That way you know you can theoretically do this: ``` const Widget* pWidgetArrayBegin = &(vecWidget[0]); ``` You can then pass *pWidgetArrayBegin* into functions that want an array as a parameter. The only exception to this is the std::vector<bool> specialisation. It actually isn't bools at all, but that's another story. So the std::vector will reallocate the memory, and will not use a linked list. This means you can shoot yourself in the foot by doing this: ``` Widget* pInteresting = &(vecWidget.back()); vecWidget.push_back(anotherWidget); ``` For all you know, the push\_back call could have caused the vector to shift its contents to an entirely new block of memory, invalidating *pInteresting*.
How is dynamic memory managed in std::vector?
[ "", "c++", "memory-management", "stl", "vector", "" ]
I'm a programmer who has never really used .dll files. Of cause, when I need 3rd party software, such as a graphics library, a library to help me create graphs etc. I do add the references/ddl files to my program and use them in my code. Also, it seems like you can use .dll for a lot of different things, so I'd like the topic to concentrate on C#. Right now I am working on a sanitizing library(?) (I think that is the correct term), which will be full of relevant methods that can sanitize variables in all sorts of different ways. **What I want to know is:** would there be any advantage to: **1)** Write the methods to class library -> compile/build it -> add the library as a reference to the program - which would need to sanitize some variables ? Or would it be exactly the same if I where to: **2)** Create a new SanitizeClass in the program -> add all the sanitize methods -> call the methods from the SanitizeClass in the different classes in the program that needs to sanitize variables In general, I also want to know when it is an advantage to use compiled class libraries. I'm thinking of speed, security, all of it. Could anyone enlightenment me? :)
The key question is: does it make sense for more than one application to use the type? If so, it should be in a class library. If not, you may *still* want to put it in a class library just for the sake of separation (e.g. have one assembly per tier in an n-tier solution), but you *could* just put it in your application. If your sanitization is general-purpose, then putting it in a class library would definitely be the right move. I know of people who write almost no code in executable applications, and put almost *everything* in class libraries - so the application basically just wraps the class libraries. I don't tend to go quite that far myself...
The first thought that comes to mind is re usability. Will this sanitize library be used ever outside of the application you're currently working on? If you are, then you don't want to have to reference an exe in the future, for that you want to build a DLL file (possibly even strong name it and GAC it) and then just reference that in the future.
When is it the right time to use C# class library (.dll)?
[ "", "c#", "class", "dll", "class-library", "" ]
I'm using Hibernate's JPA implementation with MySQL 5.0.67. MySQL is configured to use InnoDB. In performing a JPA query (which is translated to SQL), I've discovered that using the `IN` clause is slower than performing individual queries. Example: ``` SELECT p FROM Person p WHERE p.name IN ('Joe', 'Jane', 'Bob', 'Alice') ``` is slower than four separate queries: ``` SELECT p FROM Person p WHERE p.name = 'Joe' SELECT p FROM Person p WHERE p.name = 'Jane' SELECT p FROM Person p WHERE p.name = 'Bob' SELECT p FROM Person p WHERE p.name = 'Alice' ``` Why is this? Is this a MySQL performance limitation?
This is a known deficiency in MySQL. It is often true that using `UNION` performs better than a range query like the one you show. MySQL doesn't employ indexes very intelligently for expressions using `IN (...)`. A similar hole exists in the optimizer for boolean expressions with `OR`. See <http://www.mysqlperformanceblog.com/2006/08/10/using-union-to-implement-loose-index-scan-to-mysql/> for some explanation and detailed benchmarks. The optimizer is being improved all the time. A deficiency in one version of MySQL may be improved in a subsequent version. So it's worth testing your queries on different versions. It is also advantageous to use `UNION ALL` instead of simply `UNION`. Both queries use a temporary table to store results, but the difference is that `UNION` applies `DISTINCT` to the result set, which incurs an additional un-indexed sort.
If you're using the IN operator, it's not much different than saying: ``` (p.name = 'Joe' OR p.name = 'Jane' OR p.name = 'Bob' OR p.name = 'Alice') ``` Those are four conditions which must be checked for every row that the query must consider. Of course, each other query you cite has only one condition. I don't believe in most real-world scenarios doing four such queries would be faster, since you have to consider the time it takes for your client to read the result sets and do something with them. In that case, IN looks pretty nice; even better if it can use an index.
SQL IN clause slower than individual queries
[ "", "sql", "mysql", "performance", "hibernate", "jpa", "" ]
I work for a team of ASP.net MVC and they are using Cruisecontrol, nUnit and nAnt for the automated testing and build. I am new to the group and i handle the Javascript layer and i am looking for ways to incorporate my work with my teams workflow. Are there any possoble way to do this? Thanks
A few thoughts: * There is JSUnit, a unit test framework for JavaScript. I used it a 2 years ago and it was pretty good. Something better may be out there now. * I assume they're using source code control of some form, and that Cruise Control monitors the repository. If so, then just make sure your JavaScript is kept in the same repo, so it will trigger builds, automatic kickoff of unit tests, etc. * If you have portions of your JavaScript layer that can only be tested in a browser, think about using Selenium or a similar tool to create a kind of automated tests that drive the browser through various scenarios. I'm sure there is a way to kick these off from Cruise Control.
Just a couple of days ago, John Resig announced a JavaScript unit test automator he's working on called **[Test Swarm](http://ejohn.org/blog/javascript-testing-does-not-scale/).** It's just now going into alpha, but it might be worth watching.
Automated Unit testing for Javascript integrated with CruiseControl, nUnit, nAnt and ASP.net MVC
[ "", "javascript", "asp.net-mvc", "unit-testing", "" ]
``` <script type="text/javascript"> $(document).ready(function() { $('#pHeader').click(function() { $('#pBody').slideToggle('fast'); }); }); </script> <asp:Panel ID="pHeader" runat="server" CssClass="cpHeader"> <asp:Label ID="lblText" runat="server" Text="Header" /> </asp:Panel> <asp:Panel ID="pBody" runat="server" CssClass="cpBody"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur </asp:Panel> ``` As you can see from the above I am trying to achieve a collapsible panel. However the above will only work once. How can I make this accessible to multiple controls, i.e. if I have 10 panels on a page? Thanks guys!
Try this: ``` $(function(){ $('.cpHeader').click(function() { $(this).next('.cpBody').slideToggle('fast'); }); }); ``` If you select by ID (e.g., `#pHeader`), you'll only affect one node, since IDs are meant to be unique. Classes are meant to be assigned to multiple nodes. Also note the shortened first line, which jQuery provides as a shortcut for `$(document).ready()`.
I guess you have to use `$('.pHeader')` and `$('.pBody')` instead of `$('#pHeader')` and `$('#pBody')` if you assign the CSS class `pHeader` to every Panel. The "#" character selects an element with the id after the "#" sign. The "." is used to get all elements to which you apply a certain CSS class name. So, code this should work: ``` <script type="text/javascript"> $(document).ready(function() { $('.pHeader').click(function() { $('.pBody').slideToggle('fast'); }); }); </script> ```
Multiple control instances using jQuery and ASP.NET controls
[ "", "asp.net", "javascript", "jquery", "" ]
What's the easiest way to convert these requests: ``` http://www.example.com/en/ http://www.example.com/en/index.php ``` To: ``` http://www.example.com/index.php?language_id=en ``` There's various PHP files, so the rule would also need to map ``` http://www.example.com/en/anyfile.php ``` To: ``` http://www.example.com/anyfile.php?language_id=en ``` The language ID can be any two letter code (it's checked within the PHP script, to ensure it's valid). Presumably, I'll need to use .htaccess, and any advice on how to implement the above would be greatly appreciated. Thanks. **Update** The following worked for me. ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ([a-z]+)/(css|js|images)/(.+) /$2/$3 [L] RewriteRule ([a-z]+)/(.+).php /$2.php?language_id=$1 [QSA,L] RewriteRule ([a-z]+)/$ /index.php?language_id=$1 [QSA,L] </IfModule> ``` This also re-routes requests to the css, js, and images folders back to the root folder. It also works if no filename is entered, automatically redirecting to index.php.
You probably want to add the `QSA` flag to your rewrite rules, which will append any addiitonal bits on the query string to the rewritten request, e.g. ``` RewriteRule magic here [PT,QSA] ```
``` RewriteRule /([^/]+)/(.*) /$2?language_id=$1 ```
Using mod_rewrite to convert folders to querystring
[ "", "php", ".htaccess", "mod-rewrite", "" ]
I have a generic class that I am using Reflection to pull out the properties of the type of the generic and looking for an attribute. I am recursing into each property to do the same for each of their properties. My issue is when I come to some sort of collection property (property that is a collection) or ICollection property. I will not be able to cast the value returned from GetValue into a specific type (tried to cast into IEnumerable but does not work for generic IEnumerables). Here is some code to help understand a little more: ``` public class NotificationMessageProcessor<T> : INotificationProcessor<T> { IList<string> availableTags = new List<string>(); public string ReplaceNotificationTags<T>(string message, T instance) { LoadTagValues(instance); return ReplaceTags(message); } private string ReplaceTags(string message) { foreach (KeyValuePair<string, string> tagVal in tagValues) { message = message.Replace(string.Format("<{0}>", tagVal.Key), tagVal.Value); } return message; } private void LoadTagValues(object val) { Type elementType = val.GetType(); PropertyInfo[] typeProperties = elementType.GetProperties(); foreach (PropertyInfo prop in typeProperties) { NotificationTag[] tags = (NotificationTag[])prop.GetCustomAttributes(typeof(NotificationTag), false); if (tags != null && tags.Length > 0) { string tagName = tags[0].TagName; object propValue = prop.GetValue(val, null); string propTypeString = prop.PropertyType.FullName; tagName = prop.ReflectedType.Name + "." + tagName; if (propValue != null) { tagValues.Add(tagName, propValue.ToString()); } if (propValue != null) { if (!prop.PropertyType.IsPrimitive) { LoadTagValues(propValue); } } } else { if (!prop.PropertyType.IsPrimitive) { object propValue = null; if (prop.GetGetMethod().GetParameters().Count() == 0) { propValue = prop.GetValue(val, null); } else { //have a collection...need to process but do not know how many in collection.... propValue = prop.GetValue(val, new object[] { 0 }); } if (propValue != null) { LoadTagValues(propValue); } } } } } NotificationMessageProcessor<User> userProcessor = new NotificationMessageProcessor(); userProcessor.ReplaceNotificationTags<User>(someMessage, instanceOfUser); ``` The User object has the proper attributes
I am doing the cast to IEnumerable, I was trying to cast the wrong object when I was having issues.
From what I understand, non-generic `IEnumerable` will do since you don't need the type information anyway.
process items in Generic list/collections with Reflection
[ "", "c#", ".net", "generics", "reflection", "" ]
I've read at various websites that Thread.Abort is not very good to use. In this case, how do you implement a timeout pattern? For instance, I've read that MS uses the pattern below (which I've wrapped in an extension method) throughout the framework. Personally, I think this is a pretty cool extension, but I'm worried about the Thread.Abort. Does anyone have a better way? ``` public static bool CallandWait(this Action action, int timeout) { Thread subThread = null; Action wrappedAction = () => { subThread = Thread.CurrentThread; action(); }; IAsyncResult result = wrappedAction.BeginInvoke(null, null); if (((timeout != -1) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted)) { if (subThread != null) { subThread.Abort(); } return false; } else { wrappedAction.EndInvoke(result); return true; } } ```
*Potentially* very bad. The aborted thread could leave shared state corrupted, could leave asynchronous operations running, ... See Joe Duffy's blog: ["Managed code and asynchronous exception hardening"](http://www.bluebytesoftware.com/blog/2009/03/13/ManagedCodeAndAsynchronousExceptionHardening.aspx).
Basically you're talking about aborting an action which (as far as we know) has no graceful way of aborting. That means there's going to be no *safe* way of aborting it. `Thread.Abort` is just not a nice thing to do - there are various race conditions and ugly situations you can get into (see the link in [Richard's answer](https://stackoverflow.com/questions/710070/timeout-pattern-how-bad-is-thread-abort-really/710094#710094)). I would try desperately hard to avoid wanting to cancel actions that don't know about cancellation - and if you absolutely *have* to do it, consider restarting the whole app afterwards, as you may no longer be in a sane state.
Timeout Pattern - How bad is Thread.Abort really?
[ "", "c#", "multithreading", "extension-methods", "" ]
I was reading somewhere about how to handle the issue of wanting to extend a sealed class in the .NET Framework library. This is often a common and useful task to do, so it got me thinking, in this case, what solutions are there? I believe there was a "method" demonstrated to extend a sealed class in the article I read, but I cannot remember now (it wasn't extension methods). Is there any other way? Thanks
There is 'fake' inheritance. That is, you implement the base class and any interfaces the other class implements: ``` // Given sealed class SealedClass : BaseClass, IDoSomething { } // Create class MyNewClass : BaseClass, IDoSomething { } ``` You then have a private member, I usually call it \_backing, thus: ``` class MyNewClass : BaseClass, IDoSomething { SealedClass _backing = new SealedClass(); } ``` This obviously won't work for methods with signatures such as: ``` void NoRefactoringPlease(SealedClass parameter) { } ``` If the class you want to extend inherits from ContextBoundObject at some point, take a look at [this article](http://msdn.microsoft.com/en-us/magazine/cc301356.aspx "MSDN Article"). The first half is COM, the second .Net. It explains how you can proxy methods. Other than that, I can't think of anything.
Extension methods is one way, the alternative being the Adapter Pattern. Whereby you write a class that delegates some calls to the sealed one you want to extend, and adds others. It also means that you can adapt the interface completely into something that your app would find more appropriate.
How to handle a class you want to extend which is sealed in the .NET library?
[ "", "c#", ".net", "" ]
Is there any utility for deep cloning for java collections: * Arrays * Lists * Maps NOTE: prefer some solution without usage of serialization, but with use of Object.clone() method. I can be sure that my custom object will implement clone() method and will use only java-standard classes that are cloneable...
**I think the previous green answer was bad** , why you might ask? * It adds a lot of code * It requires you to list all fields to be copied and do this * This will not work for Lists when using clone() (This is what clone() for HashMap says: Returns a shallow copy of this HashMap instance: the keys and valuesthemselves are not cloned.) so you end up doing it manually (this makes me cry) Oh and by the way serialization is also bad, you might have to add Serializable all over the place (this also makes me cry). **So what is the solution:** Java Deep-Cloning library *The cloning library* is a small, open source (apache licence) java library which deep-clones objects. The objects don't have to implement the Cloneable interface. Effectivelly, this library can clone ANY java objects. It can be used i.e. in cache implementations if you don't want the cached object to be modified or whenever you want to create a deep copy of objects. ``` Cloner cloner=new Cloner(); XX clone = cloner.deepClone(someObjectOfTypeXX); ``` Check it out at <https://github.com/kostaskougios/cloning>
All approaches to copy objects in Java have serious flaws: **Clone** 1. The clone() method is protected, so you can't call it directly unless the class in question overrides it with a public method. 2. clone() doesn't call the constructor. Any constructor. It will allocate memory, assign the internal `class` field (which you can read via `getClass()`) and copy the fields of the original. For more issues with clone(), see item 11 of Joshua Bloch's book "[Effective Java, Second Edition](https://rads.stackoverflow.com/amzn/click/com/0321356683)" **Serialize** Serialize is even worse; it has many of the flaws of `clone()` and then some. Joshua has a whole chapter with four items for this topic alone. **My Solution** My solution is add a new interface to my projects: ``` public interface Copyable<T> { T copy (); T createForCopy (); void copyTo (T dest); } ``` The code looks like this: ``` class Demo implements Copyable<Demo> { public Demo copy () { Demo copy = createForCopy (); copyTo (copy); return copy; } public Demo createForCopy () { return new Demo (); } public void copyTo (Demo dest) super.copyTo (dest); ...copy fields of Demo here... } } ``` Unfortunately, I have to copy this code to all my objects but it's always the same code, so I can use an Eclipse editor template. Advantages: 1. I can decide which constructor to call and how to initialize which field. 2. Initialization happens in a deterministic order (root class to instance class) 3. I can reuse existing objects and overwrite them 4. Type safe 5. Singletons stay singletons For standard Java types (like collections, etc), I use a utility class which can copy those. The methods have flags and callbacks, so I can control how deep a copy should be.
Deep clone utility recommendation
[ "", "java", "clone", "" ]
Is it possible to get client IP address through Flash (swf) Action Script 3 and then pass it to php file to store it in database?
No need to do it in flash, just do it on your server in php "$ip=@$REMOTE\_ADDR;"
No, the client IP address is not available in ActionScript 3. The recommended approach is to have it reflected by server-side code. See <http://www.actionscript.org/forums/showthread.php3?s=&threadid=20123>
Get IP address using Action Script?
[ "", "php", "actionscript-3", "actionscript", "ip-address", "" ]
I have: ``` {% for field in form %} {{ field }} {% end for %} ``` What I want is to put an 'if' statement to exclude a field which .label or whatever is provided. Like: ``` {% for field in form%} {% if field == title %} {% else %} {{ field }} {% endif %} {% endfor %} ``` Is it possible? I have to many fields to write them one by one and only one or two to exclude.
Yes, this should be possible: ``` {% for field in form %} {% ifnotequal field.label title %} {{ field }} {% endifnotequal %} {% endfor %} ``` Django's [template tags](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ref-templates-builtins) offer `ifequal` and `ifnotequal` variants, and you can test the field.label against either a context variable, or a string.
You might be a lot happier creating a subclass of the form, excluding the offending field. See <http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#form-inheritance> ``` class SmallerForm( MyForm ): class Meta(MyForm.Meta): exclude = [ title ] ```
'for' loop through form fields and excluding one of the fields with 'if'
[ "", "python", "django-templates", "" ]
Before the introduction to generics to the Java language I would have written classes encapsulating collections-of-collections-of-collections. For example: ``` class Account { private Map tradesByRegion; //KEY=Region, VALUE=TradeCollection } class TradeCollection { private Map tradesByInstrument; //KEY=Instrument, Value=Trade } ``` Of course, with generics, I can just do: ``` class Account { private Map<Region, Map<Instrument, Trade>> trades; } ``` I tend to now opt for option #2 (over a *generified version of option #1*) because this means I don't end up with a proliferation of classes that exist solely for the purpose of wrapping a collection. But I have a nagging feeling that this is bad design (e.g. how many nested collections should I use before declaring new classes). Opinions?
2 is better because: * Less code accomplishes the same effect (better, actually, as in #1 some of your type information exists only in comments) * It's completely clear what's going on. * Your type errors will be caught at compile time. What is there to recommend 1? admittedly the Map< Integer , < Map < String, < Map< ... generics are a bit hard to get used to, but to my eye it's much easier to understand than code with maps, and lists of maps, and maps of lists of maps, and custom objects full of lists of maps.
Combination of the two. While you can use generics to replace custom classes, you still will want to use a class to encapsulate your concepts. If you're just passing maps of maps of maps of lists to everything, who controls what you can add? who controls what you can remove? For holding the data, generics is a great thing. But you still want methods to validate when you add a trade, or add an account, and without some kind of class wrapping your collections, nobody controls that.
To use nested genericized collections or custom intermediate classes?
[ "", "java", "generics", "oop", "" ]
Responders to the question know, of course, that ColdFusion is a Java EE application and can access all underlying Java classes, supports JSP custom tag libraries, etc. But what I want to know is *when* to write code in Java, compile it as a JAR, and reference it in CFML. This is all in the context of a CF MVC app written in a framework like Fusebox, Mach-II, or Model-Glue.
We have an old CF6.1 application with java buried in it. Migrating to a newer CF version has been very painful because o the buried java. So I say dont use your own java in a Coldfusion application.
There are three obvious reasons I can see to jump into Java: * When there is existing Java functionality that does what you want (don't re-invent the wheel). * When Java can do something better (or differently) than CF does. * If you have identified a performance issue that using Java can solve. In general though, I wouldn't write *new* Java code to use in CF - I'd look for existing classes that are already more proven.
When Should I Use Java in my ColdFusion Application?
[ "", "java", "coldfusion", "" ]
``` int a = 10000000; a.ToString(); ``` How do I make the output? > 10,000,000
Try `N0` for no decimal part: ``` string formatted = a.ToString("N0"); // 10,000,000 ```
You can also do String.Format: ``` int x = 100000; string y = string.Empty; y = string.Format("{0:#,##0.##}", x); //Will output: 100,000 ``` If you have decimal, the same code will output 2 decimal places: ``` double x = 100000.2333; string y = string.Empty; y = string.Format("{0:#,##0.##}", x); //Will output: 100,000.23 ``` To make comma instead of decimal use this: ``` double x = 100000.2333; string y = string.Empty; y = string.Format(System.Globalization.CultureInfo.GetCultureInfo("de-DE"), "{0:#,##0.##}", x); ```
How do I format a number with commas?
[ "", "c#", "numbers", "tostring", "" ]
I implemented a full text search "searching in tags", using SQL server 2005, I want to describe for the client what i did, what what full text search means by simple examples? My Client is not a programmer but a good internet user.
I find when describing something to clients use a metaphor or use a very concrete domain specific example. As a metaphor you could say that Full Text Search is like Google for your site. It looks at everything and anything to try and help you. Whereas, what we had before was more like using the Find feature in XP. It works, but works well if you know a lot about what you are searching for. And isn't Google better than Find :) Or just give them an example of something they couldn't do before that they can do now! Experience and results always convey the message more than words. Show them how you made their lives easier and they will immediately understand. Best of luck.
"It now finds stuff much much faster." Everything else is technical details not interesting to a user.
How to describe Full text search for a client?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I have following classes: ``` public abstract class CustomerBase { public long CustomerNumber { get; set; } public string Name { get; set; } } public abstract class CustomerWithChildern<T> : CustomerBase where T: CustomerBase { public IList<T> Childern { get; private set; } public CustomerWithChildern() { Childern = new List<T>(); } } public class SalesOffice : CustomerWithChildern<NationalNegotiation> { } ``` The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like: ``` public void WalkHierarchy(CustomerBase start) { Print(start.CustomerNumber); if (start is CustomerWithChildern<>) { foreach(ch in start.Childern) { WalkHierarchy(ch); } } } ``` Is there any chance I could get something like this working? --- The solution based on suggested has-childern interface I implemented: ``` public interface ICustomerWithChildern { IEnumerable ChildernEnum { get; } } public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern where T: CustomerBase { public IEnumerable ChildernEnum { get { return Childern; } } public IList<T> Childern { get; private set; } public CustomerWithChildern() { Childern = new List<T>(); } } public void WalkHierarchy(CustomerBase start) { var x = start.CustomerNumber; var c = start as ICustomerWithChildern; if (c != null) { foreach(var ch in c.ChildernEnum) { WalkHierarchy((CustomerBase)ch); } } } ```
I believe that you want to make the lookup for the determination of doing to the walk an interface. So maybe add an "IWalkable" interface that exposes the information needed to do the walk, then you can create your method checking to see if the passed object implements the interface.
You could move the WalkHierarchy method to the base class and make it virtual. The base class implementation would only process the current node. For the `CustomerWithChildern<T>` class, the override would do an actual walk.
c# - cast generic class to its base non-generic class
[ "", "c#", "generics", "" ]
Is where any C++ compiler that supports C++0x features already?
Both the 2008 Visual C++ 'Feature Pack' and g++ support some features. The [list of C++0x features supported by g++](http://gcc.gnu.org/projects/cxx0x.html). --- [The Visual C++ 2008 Feature Pack](http://www.microsoft.com/DownLoads/details.aspx?FamilyID=d466226b-8dab-445f-a7b4-448b326c48e7&displaylang=en) ... includes an implementation of TR1. Portions of TR1 are scheduled for adoption in the upcoming C++0x standard as the first major addition to the ISO 2003 standard C++ library. Our implementation includes a number of important features such as: * Smart pointers * Regular expression parsing * New containers (tuple, array, unordered set, etc) * Sophisticated random number generators * Polymorphic function wrappers * Type traits * And more!
GCC has some of it supported. See [here](http://gcc.gnu.org/projects/cxx0x.html).
C++ compiler that supports C++0x features?
[ "", "c++", "c++11", "" ]
In a game, many entities should be updated every frame. Im toying with different design patterns to achieve this. Up until now, Ive had a singleton manager class to which every Logic instance is added. But Im considering the following, a static list in the Logic class itself. This is nice since it would remove a class from the project. "Engine" in this example would be the master class calling the update\_all. ``` class Logic { public: Logic() { all.push_back(this); } virtual ~Logic() { all.erase(this); } virtual void update(float deltatime) = 0; private: friend Engine; static std::list<Logic*> all; static void update_all(float deltatime) { for (std::list::iterator i = all.begin(); i!=all.end(); ++i) (*i)->update(deltatime); } }; ``` * Does this pattern have a name? * Do you consider this a nicer approach than a singleton manager class? * Any other comments or caveats?
First, you need to use `remove()` instead of `erase()` (the latter would need an iterator as argument) If you use a slightly different loop like ``` std::list<Logic*>::iterator it = all.begin(); while (it != all.end()) { Logic* current = *it; ++it; current->update(deltatime); } ``` you can even overcome the problem *siukurnin* mentioned (deletion of a Logic object during update()). `list::remove()` doesn't invalidate iterators except of the ones pointing to the removed element. Apart from this, I also vote for this being a variation of the singleton pattern. And I would suggest for keeping the original solution with a separate management class, just in case you want to have to have two loops with different delta times or explicit multithread support (different Logic objects on different threads) or whatever in the future. In my opinion this is a general advantage of the singleton class over static methods (which you could always use): You can easily multiply your functionality if you want to do so in the future ...
You can also use [observer pattern](http://www.dofactory.com/Patterns/PatternObserver.aspx) for this
Logic design pattern
[ "", "c++", "design-patterns", "logic", "" ]
Do you know of a Java library to access the native linux api? I guess something like this must use JNI. So be it.
Have a look at [JNA.](https://github.com/twall/jna) Here is the summary of JNA from their home page. > JNA provides Java programs easy access to native shared libraries (DLLs on Windows) without writing anything but Java code—no JNI or native code is required. This functionality is comparable to Windows' Platform/Invoke and Python's ctypes. Access is dynamic at runtime without code generation. See their [getting started](https://github.com/twall/jna/blob/master/www/GettingStarted.md) page for some samples. Like calling native printf.
[jtux](http://www.basepath.com/aup/jtux/) might help depending on what you want to do.
Do you know of a Java library to access the native linux api?
[ "", "java", "linux", "" ]
I have yet to find a "nice" way to do two way databinding in .Net. The one thing I don't like for example in the present asp.net two way databinding is doing the binding in the aspx page is no compile time checking, ie: ``` <asp:TextBox ID="TitleTextBox" runat="server" Text='<%# Bind("Title_oops_spelled_wrong") %>'> ``` I would like to have something like this: ``` Class Binder Public Sub BindControl(ctl As Control, objectProperty As ???????) '// Add ctl and objectProperty to a collection End Sub ``` What I don't know is possible is, how to receive the objectProperty in my example; I want to receive a *reference* (ie: a pointer) to the property, so later, via this reference, I can either read from or write to the property. Can this somehow be done with delegates perhaps?? UPDATE: Note, I want to add the control *reference* to a binding collection, this collection would then be used for binding and unbinding.
Is there a reason that you want to avoid using the .NET data binding mechanism? It handles keeping parity between the control's value and the class's property value already, and provides rich design-time support. You can interface with the data binding engine in two ways: either programatically or through the designer. To do basic data binding programatically is trivial. Say I have a class named "FooClass" with a string property named "MyString". I have a TextBox named myTxtBox on a form with an instance of FooClass called foo and I want to bind it to the MyString property: ``` myTxtBox.DataBindings.Add("Text", foo, "MyString"); ``` Executing this will cause updates to the TextBox to get assigned to the property, and changes to the property from elsewhere will be reflected in the TextBox. For more complex data binding scenarios, you'll probably want to create an Object Data Source in your project and put a BindingSource on your form. If you need help with specific steps in creating the data source I can help, but in general you'll create the source in your project and select the class to which you want to bind. You can then place a BindingSource on your form, point it at your object project data source, then use the Visual Studio designer to bind properties for your controls to properties on your object. You then set the DataSource property in your code to an instance of the class or collection to which you want to bind. As a side note, as far as I am aware there is no "property delegate", as properties are actually function pairs (a get\_ and a set\_). UPDATE: As I read your comments, I'd like to point out that .NET data binding, even at the control level, does NOT automatically use reflection. Data binding is built around type descriptors and property descriptors, both for the bound control and the data source. It's true that if one or both of these sides does not implement specific property and type description then reflection will be used, but either side is more than free to provide its own description profile which would NOT use reflection.
The Bind is not a method and there is no some object behind the scene holding binding relationship. It's just a "magic" word that page parser uses to generate code behind. Essentially, it translates into Eval and control building code. The Eval, on the other hand, will use reflection to access bound item's properties. If I understand correctly what you want, read-only property binding already works. Assuming you have a property Title in your class: ``` <asp:TextBox ID="TitleTextBox" runat="server" Text='<%# Title %>' /> ``` For two-way binding, you'd have to either create your own Template or reflect existing one and pass the ExtractTemplateValuesMethod method and assign the DataBinding event to your control. This is where .NET uses Eval, which you'd replace with the property assignment. In my opinion, that is what the DataBinding event is for. However, if you question is more about whether one can have a reference to a property, then I'm afraid not. There is no property per say. You have to methods (get and set) and an entry in the metadata. You could store a reference to the object and property name, but then you'd have to use reflection. You could use the delegates, but that would take you back to the same code as the one .NET generates, which is defining ExtractTemplateValuesMethod and doing DataBinding anyhow.
Binding controls to class properties - is this technically possible?
[ "", "c#", ".net", "asp.net", "vb.net", "data-binding", "" ]
I am using the following code to draw on a single monitor: ``` Point cursorLocation; NativeMethods.GetCursorPos(out cursorLocation); Screen screen = Screen.FromPoint(cursorLocation); Point h1 = new Point(screen.Bounds.Left, cursorLocation.Y); Point h2 = new Point(screen.Bounds.Right, cursorLocation.Y); Point v1 = new Point(cursorLocation.X, screen.Bounds.Top); Point v2 = new Point(cursorLocation.X, screen.Bounds.Bottom); using (Graphics graphics = Graphics.FromHwnd(NativeMethods.GetDesktopWindow())) { NativeMethods.SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero); graphics.DrawLine(Pens.Red, h1, h2); graphics.DrawLine(Pens.Red, v1, v2); } ``` Natively, this *should* *theoretically* draw on either monitor. However, it only draws on the primary. So, to fix this I am getting the DC of all the displays and trying to do it this way. ``` IntPtr hdc = NativeMethods.CreateDC("DISPLAY", IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); Graphics graphics = Graphics.FromHdc(hdc); graphics.DrawLine(Pens.Red, h1, h2); graphics.DrawLine(Pens.Red, v1, v2); graphics.Dispose(); NativeMethods.ReleaseDC(IntPtr.Zero, hdc); ``` Go figure, this doesn't even draw to the screen at all. I have tried various overloads for CreateDC, as well as searched SO and other resources and I'm stumped. --- Once this is resolved, anyone know how to get rid of flicker by refreshing the desktop using SHCHangeNotify? I'm only drawing two lines and it flickers like mad..)
This is not an answer to your question but if you have no problem with it, I would recomment trying using WPF to solve this. I have played with other kind of desktop interaction like transparency and WPF is lightning fast compared to the GDI alternative. You place your wpf application and resize it to fit all the area you need to be painting on. Then set it to transparent, and make sure its clickthrough (i think that is default on 100% transparency). That way as long as you dont have anything on this big WPF canvas/form all mouse events will click through to desktop. Then just start painting on it. (i liked it because it was very easy to add effects to lines and images). Guaranteed no flickering. Alternatively you could use the same scheme on normal Windows Forms instead. This way you wont have to turn to GDI to do your work. I think the only way you would be able to do this flickerfree as you are approaching it now, would be to hook into the window messaging on the desktops WM\_PAINT and do your work there.
this worked for me. i used EnumDisplayDevices to fetch the names. ``` [DllImport("gdi32.dll")] public static extern IntPtr CreateDC(string lpszDriver, string lpszDevice, string lpszOutput, IntPtr lpInitData); var hdc = CreateDC(@"\\.\DISPLAY1", "", "", IntPtr.Zero); Graphics g = Graphics.FromHdc(hdc); var pt = Cursor.Position; g.DrawEllipse(Pens.BlueViolet, pt.X - 100, pt.Y - 100, 200, 200); ``` more info here: <http://msdn.microsoft.com/en-us/library/windows/desktop/dd145179(v=vs.85).aspx>
Drawing over all windows on multiple monitors
[ "", "c#", "gdi+", "desktop", "" ]
I have a method in an object that is called from a number of places within the object. Is there a quick and easy way to get the name of the method that called this popular method. Pseudo Code EXAMPLE: ``` public Main() { PopularMethod(); } public ButtonClick(object sender, EventArgs e) { PopularMethod(); } public Button2Click(object sender, EventArgs e) { PopularMethod(); } public void PopularMethod() { //Get calling method name } ``` Within `PopularMethod()` I would like to see the value of `Main` if it was called from `Main` ... I'd like to see "`ButtonClick`" if `PopularMethod()` was called from `ButtonClick` I was looking at the `System.Reflection.MethodBase.GetCurrentMethod()` but that won't get me the calling method. I've looked at the `StackTrace` class but I really didn't relish running an entire stack trace every time that method is called.
I don't think it can be done without tracing the stack. However, it's fairly simple to do that: ``` StackTrace stackTrace = new StackTrace(); MethodBase methodBase = stackTrace.GetFrame(1).GetMethod(); Console.WriteLine(methodBase.Name); // e.g. ``` However, I think you really have to stop and ask yourself if this is necessary.
In .NET 4.5 / C# 5, this is simple: ``` public void PopularMethod([CallerMemberName] string caller = null) { // look at caller } ``` The **compiler** adds the caller's name automatically; so: ``` void Foo() { PopularMethod(); } ``` will pass in `"Foo"`.
Retrieving the calling method name from within a method
[ "", "c#", "reflection", "methods", "calling-convention", "" ]
In my Java application, I want to run a batch file that calls "`scons -Q implicit-deps-changed build\file_load_type export\file_load_type`" It seems that I can't even get my batch file to execute. I'm out of ideas. This is what I have in Java: ``` Runtime. getRuntime(). exec("build.bat", null, new File(".")); ``` Previously, I had a Python Sconscript file that I wanted to run but since that didn't work I decided I would call the script via a batch file but that method has not been successful as of yet.
Batch files are not an executable. They need an application to run them (i.e. cmd). On UNIX, the script file has shebang (#!) at the start of a file to specify the program that executes it. Double-clicking in Windows is performed by Windows Explorer. `CreateProcess` does not know anything about that. ``` Runtime. getRuntime(). exec("cmd /c start \"\" build.bat"); ``` Note: With the `start \"\"` command, a separate command window will be opened with a blank title and any output from the batch file will be displayed there. It should also work with just `cmd /c build.bat", in which case the output can be read from the sub-process in Java if desired.
Sometimes the thread execution process time is higher than JVM thread waiting process time, it use to happen when the process you're invoking takes some time to be processed, use the waitFor() command as follows: ``` try{ Process p = Runtime.getRuntime().exec("file location here, don't forget using / instead of \\ to make it interoperable"); p.waitFor(); }catch( IOException ex ){ //Validate the case the file can't be accesed (not enought permissions) }catch( InterruptedException ex ){ //Validate the case the process is being stopped by some external situation } ``` This way the JVM will stop until the process you're invoking is done before it continue with the thread execution stack.
How do I run a batch file from my Java Application?
[ "", "java", "batch-file", "runtime.exec", "" ]
I am having problems closing out a C# windows form app. It will currently just give me a blank form with no title or anything. **I need to find a way to close this little unknown window.** I Have 2 form pages one for a login screen and one for the actual app. All being run by a program.cs file. **program.cs** ``` ... static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new PROG1()); } ``` This is just the basic main created by visual studio to run my program. Then we have the main program **PROG1.cs** ``` ... public PROG1() { Login LoginForm = new Login(); DialogResult a = LoginForm.ShowDialog(); if(LoginForm.ValidLogin == 1) { InitializeComponent(); } else { Application.Exit(); //FAIL } } ``` You can see that the first the program.cs file calls PROG1.cs which calls an instance of login.cs. If you insert a valid login the login page will close and the main PROG1 will show as it should. However if you simply click the red X to close login form it comes to Prog1 and LoginForm.ValidLogin != 1 so it does not Initialize the form and will try to close the form. This will just leave me the uninitialized form instead of closing it out. If I do a this.close() instead it will give me a runtime error. Any Ideas?
Put the InitializeComponent call back at the top where it used to be. An attempt to use uninitialized variables, including trying to tell them to close themselves, is a bad idea. Configure the properties of your PROG1 form so the initial state will be hidden instead of shown. After the LoginForm returns, your PROG1 code can decide whether to show itself or close itself.
Is the reason you're not initializing the form on failure because the contents of the InitializeComponent() method take a very long time to run? It seems like you should just simplify your program to this: ``` static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); LoginForm login = new LoginForm(); if (login.ShowDialog() == DialogResult.OK && login.ValidLogin == 1) Application.Run(new PROG1()); } ``` And remove the logic from the constructor of PROG1.
Problems Closing a C# Windows Form
[ "", "c#", "winforms", "" ]
In C# how do you display an error message if both text boxes are empty? Is there a code example or validator that can be used?
You will need to use a [CustomValidator](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx).
RequiredFieldValidator should do the job? if you want to know more about validators then look here <http://www.codeproject.com/KB/validation/aspnetvalidation.aspx>
Run code when both text boxes are empty
[ "", "c#", "asp.net", "" ]
``` from i in Db.Items select new VotedItem { ItemId = i.ItemId, Points = (from v in Db.Votes where b.ItemId == v.ItemId select v.Points).Sum() } ``` I got this query, however it fails if no votes are found with exception: ``` The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type. ``` I assume its because sum returns an int and not a nullable int, giving sum a int? as input only give the same error, probably cause sum only workes on ints. Any good workaround for this?
``` from i in Db.Items select new VotedItem { ItemId = i.ItemId, Points = (from v in Db.Votes where b.ItemId == v.ItemId select v.Points ?? 0).Sum() } ``` EDIT - ok what about this... (Shooting again since I don't know your model...): ``` from i in Db.Items select new VotedItem { ItemId = i.ItemId, Points = (from v in Db.Votes where b.ItemId == v.ItemId) .Sum(v => v.Points) } ```
You want to use the nullable form of Sum, so try casting your value to a nullable: ``` from i in Db.Items select new VotedItem { ItemId = i.ItemId, Points = (from v in Db.Votes where b.ItemId == v.ItemId select v.Points).Sum(r => (decimal?) r.Points) } ``` Your issue is discussed here in more detail: <http://weblogs.asp.net/zeeshanhirani/archive/2008/07/15/applying-aggregates-to-empty-collections-causes-exception-in-linq-to-sql.aspx>
Linq query with nullable sum
[ "", "c#", "linq", "linq-to-sql", "sum", "nullable", "" ]
First of all, a disclaimer: I have experience in other languages, but am still learning the subtleties of C# On to the problem... I am looking at some code, which uses the try/catch blocks in a way that concerns me. When a parsing routine is called, rather than return an error code, the programmer used the following logic ``` catch (TclException e) { throw new TclRuntimeError("unexpected TclException: " + e.Message,e); } ``` This is caught by the caller, which throws the same error ... ... which is caught by the caller, which throws the same error ... ..... which is caught by the caller, which throws the same error ... back up about 6 levels. Am I right in thinking all these catch/throw blocks are causing a performance problem, or is this a reasonable implementation under C#?
Throw (rather than catch) is expensive. Don't put a catch block in unless you are going to do something useful (i.e. convert to a more useful exception, handle the error). Just rethrowing the exception (throw statement without argument) or, even worse, throw the same object as just caught is definitely the wrong thing. EDIT: To avoid ambiguity: Rethrow: ``` catch (SomeException) { throw; } ``` Create exception from previous exception object, where all the runtime provided state (notably stack trace) is overwritten: ``` catch (SomeException e) { throw e; } ``` The latter case is a pointless way to throw away information about the exception. and without anything preceding the throw in the catch block is doubly pointless. It can be worse: ``` catch (SomeException e) { throw new SomeException(e.Message); } ``` which loses almost all the useful state information e contained (including what was originally thrown.)
It's a bad design under any language. Exception are designed to be caught at the level which you can deal with them. Catching an exception, just to throw it again is just a pointless waste of time (it also causes you to lose valuable information about the location of the original error). Apparently, the guy who wrote that code, used to use error codes, and then switched to exceptions without actually understanding how they work. Exceptions automatically "bubble up" the stack if there is no catch at one level. Also, note that exceptions are for *exceptional* occurrences. Thing that should *never* happen. They should not be used in place to normal validity checking (i.e., don't catch a divide-by-zero exception; check to see if the divisor is zero beforehand).
Under C# how much of a performance hit is a try, throw and catch block
[ "", "c#", "performance", "catch-block", "" ]
After reading some tutorials I came to the conclusion that one should always use pointers for objects. But I have also seen a few exceptions while reading some QT tutorials (<http://zetcode.com/gui/qt4/painting/>) where QPaint object is created on the stack. So now I am confused. When should I use pointers?
**If you don't know when you should use pointers just don't use them.** It will become apparent when you need to use them, every situation is different. It is not easy to sum up concisely when they should be used. Do not get into the habit of 'always using pointers for objects', that is certainly bad advice.
Main reasons for using pointers: 1. control object lifetime; 2. can't use references (e.g. you want to store something non-copyable in vector); 3. you should pass pointer to some third party function; 4. maybe some optimization reasons, but I'm not sure.
c++: when to use pointers?
[ "", "c++", "qt", "pointers", "object", "" ]
I have a mapping along the lines of this. ``` <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Model.Entities" schema="etl" assembly="Model" default-lazy="false"> <class name="Model.Entities.DataField, Model" table="mdm_field"> <id name="FieldId" column="field_id" type="int"> <generator class="native" /> </id> <many-to-one name="KeyField" class="Model.Entities.Key, Model" column="field_id" /> </class> </hibernate-mapping> ``` Now in the database the field\_id in the mdm\_field table sometimes has a value that does not exist in the related key\_field table, so it is basically broken referential integrity. Because of this when I load the entity I get an error "No row with the given identifier exists". How do I configure the mapping to work with this situation so it will not die on this situation.
Ok, I found the answer. Add the ``` not-found="ignore" ``` attribute to the property `KeyField`: ``` <many-to-one name="KeyField" not-found="ignore" class="Model.Entities.Key, Model" column="field_id" /> ```
In my case the problem was because a foreign key constraint was not enforced by MyISAM engine and therefore one of the rows ended up pointing to a non-existant value and the proxy threw an exception. I would recommend checking your dataset is consistent in this case.
nHibernate, No row with the given identifier exists
[ "", "c#", "nhibernate", "nhibernate-mapping", "" ]
I am currently looking to detect whether an URL is encoded or not. Here are some specific examples: 1. `http://www.linxology.com/browse.php?u=Oi8vZXNwbnN0YXIuY29tL21lZGlhLXBsYXllci8%3D&b=13` 2. `http://www.linxology.com/browse.php?u=Oi8vZXNwbnN0YXIuY29tL290aGVyX2ZpbGVzL2VzcG5zdGFyL25hdl9iZy1vZmYucG5n&b=13` Can you please give me a Regular Expression for this? Is there a self learning regular expression generator out there which can filter a perfect Regex as the number of inputs are increased?
If you are interested in the base64-encoded URLs, you can do it. A little theory. If `L`, `R` are regular languages and `T` is a regular transducer, then `LR` (concatenation), `L & R` (intersection), `L | R` (union), `TR(L)` (image), `TR^-1(L)` (kernel) are all regular languages. Every regular language has a regular expression that generates it, and every regexp generates a regular language. URLs can be described by regular language (except if you need a subset of those that is not), almost every escaping scheme (and base64) is a regular transducer. Therefore, in theory, it's possible. In practice, it gets rather messy. A regex for valid base64 strings is `([A-Za-z0-9+/]{4})*(|[A-Za-z0-9+/]{2}(==|[A-Za-z0-9+/]=)` If it is embedded in a query parameter of an url, it will probably be urlencoded. Let's assume only the = will be urlencoded (because other characters can too, but don't need to). This gets us to something like `[?&][^?&#=;]+=([A-Za-z0-9+/]{4})*(|[A-Za-z0-9+/]{2}(%3D%3D|[A-Za-z0-9+/]%3D)` Another possibility is to consider only those base64 encoded URLs that have some property - in your case, thy all begin with "://", which is fortunate, because that translates exactly to 4 characters "Oi8v". Otherwise, it would be more complex. This gets `[?&][^?&#=;]+=Oi8v([A-Za-z0-9+/]{4})*(|[A-Za-z0-9+/]{2}(%3D%3D|[A-Za-z0-9+/]%3D)` As you can see, it gets messier and messier. Therefore, I'd recommend you rather to 1. break the URL in its parts (eg. protocol, host, query string) 2. get the parameters from the query string, and urldecode them 3. try base64 decode on the values of the parameters 4. apply your criterion for "good encoded URLs"
Well, depending on what is in that encoded text, you might not even need a regular expression. If there are multiple querystring parameters in that one "u" key, perhaps you could just check the length of the text on each querystring value, and if it is over (say) 50, you can assume it's probably encoded. I doubt any unencoded single parameters would be as long as these, since those would have to be string data, and therefore they would probably need to be encoded!
Can someone give me a Regular Expression to identify an encoded URL?
[ "", "c#", "regex", "linux", "url", "" ]
I have a members site which I'd like to add chat to (LAMP on a dedicated box). It doesn't need to be too complex, but must use the already-logged-in members' usernames for chat. This is a bit of a side project for me, so I'd rather not write it from scratch if possible & an existing script or class would be ideal. I've done a bit of searching and there does seem to be a leaning towards JSON/Ajax, but I can't find anything definitive. Any tips/pointers?
Here are two projects that might help you out (both AJAX/JSON based): * [jQuery Ajax Chat plugin](http://plugins.jquery.com/project/chat) - a simple, light-weight plugin for jQuery. No bells or whistles, but it gets the job done. * [Ajax IM](http://www.ajaxim.com/) - a full-blown web app that tries to emulate all features one would expect in a desktop IM client. Pretty hefty download size (324KB compressed). I'm currently using the first one for a basic IM system on one of my projects. I was able to implement it using each user's system credentials (since they're already logged into the system - instead of letting them choose their own nickname). The sample includes PHP source code for the script that gets polled by the AJAX. It works great.
There are three approaches commonly taken in building a website-based chat system. 1. **Java applet solution** - either find or build a Java applet that communicates to a chat server. The applet can be an IRC client, or a custom-made chat client with a custom server. I've even seen some websites use a Java applet as a communication front-end, where the interface is all run by Javascript and HTML in the browser, but the Javascript sends and accepts events from the applet to run the chat. 2. **AJAX** Post/Poll - Every time a use writes a message, send the message to the HTTP server, where all the users connected are periodically polling for new messages. 3. **[Comet](http://en.wikipedia.org/wiki/Comet_(programming))** - Using mainly Javascript, each client establishes a long-term connection to an HTTP server, and idles. When a message is being sent from the user, it is send over the already pre-existing connection. And instead of polling for them, new messages from other users just flow down the same connection. Personally, I find the 3rd option to be the most exciting, but the most complex as well. You will probably need to build your own version of an HTTP server to support the long-lived connection that Comet requires. And since there's a 16bit limit on the descriptors of sockets in TCP/IP, you'll be limited to about 64K sockets, per IP, on your server. (Remember, each client will need a open socket!) Finally, the techniques for building Comet client-side code are wildly different between browsers. There exist a few frameworks for that, but you'll have to maintain them while new browsers come out. If you're running a small website, and you want to face a surmountable challenge, then just go with AJAX polling. It's fun, it's not too hard, and you'll learn a lot. If you can't be bothered, then just find a Java applet. Once it's configured with a matching server, you'll never have to worry about maintaining it, since that solution is very client-agnostic. Of course, it requires that the Java Runtime Environment be installed on the client, and that's not always going to be true...
Implementing PHP chat in members site
[ "", "php", "chat", "lamp", "" ]
I have a production server with apache2, php, mysql. I have just one site right now (mysite.com) as a virtual host. I want to put phpmyadmin, webalizer, and maybe webmin on there. So far, I installed phpmyadmin, and it works but the whole internet can go to mysite.com/phpmyadmin How can I reduce the visibility to say 192.168.0.0/16 so it's just accessible to machines behind my firewall?
**1) You can do it at the Webserver level.** Use allow/deny rules for apache. If you don't have direct access to your apache configuration file, you may use a .htaccess file. ``` <Directory /docroot> Order Deny,Allow Deny from all Allow from 10.1.2.3 </Directory> ``` **2) You can do it at the application level using the phpmyadmin config file.** The configuration parameter is: `$cfg['Servers'][$i]['AllowDeny']['rules']` Examples of rules are: ``` 'all' -> 0.0.0.0/0 'localhost' -> 127.0.0.1/8 'localnetA' -> SERVER_ADDRESS/8 'localnetB' -> SERVER_ADDRESS/16 'localnetC' -> SERVER_ADDRESS/24 ``` You can see this on the official phpMyAdmin configuration documentation. <http://www.phpmyadmin.net/documentation/#servers_allowdeny_order>
You would use a module in Apache called [mod\_access](http://httpd.apache.org/docs/2.0/mod/mod_access.html) You can either configure it in your apache config file or within a .htaccess file in the directory's root. Here's a short example ``` <Directory /your_folder/location> Order Deny,Allow Deny from all Allow from 123.123.123.123 </Directory> ```
phpmyadmin security
[ "", "php", "apache2", "phpmyadmin", "" ]
I have a database-driven FAQ that is organised into sections and I am trying to get the section data for only those sections who have a question/answer associated with them. Here is the schema: ``` |---------------------| |----------------------| | Section | | Quest-Ans | |---------------------| |----------------------| | PK | id(int) |<--| | PK | id(int) | | | title(varchar) | |--| FK | Sec_id(int) | | | desc(text) | | | body(text) | |---------------------| |----------------------| ``` When I try this query: ``` SELECT DISTINCT s.id, s.title, s.desc FROM Section as s INNER JOIN Quest-Ans as q ON s.id = q.Sec_id ``` I get an error saying that DISCRETE cannot be applied to a text field. How can I get the data I want? If it matters, this is an SQL2000 database. EDIT: --- Ok, so it seems like there are two ways to go about this. Either with EXISTS and a subquery in the where clause, or with the subquery in the inner join. Which is faster?
This should do it: ``` SELECT s.id, s.title, s.desc FROM Section as s WHERE EXISTS (SELECT * FROM Quest-Ans as q where q.Sec_id = s.id) ```
``` select s.id, s.title, s.desc from Section s inner join (select distinct sec_id from Quest-Ans) dqa on s.id = dqa.sec_id ```
How can I select distinct rows when a text field is part of the returned fields in MS SQL Server 2000?
[ "", "sql", "sql-server", "sql-server-2000", "" ]
Is there a max length for class/method/variable names in Java? the JLS doesn't seem to mention that. I know very long names are problematic anyway from code readability and maintainability perspective, but just out of curiosity is there a limitation (I guess class names might be limited by the file system maximal file name limitation).
JLS: [An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter.](https://docs.oracle.com/javase/specs/jls/se15/html/jls-3.html#jls-3.8) Also found similar question (though it didn't appear in my initial search, or when I typed the question title which is weird): [Maximum Method Name Length](https://stackoverflow.com/questions/425988/maximum-method-name-length)
If I'm not mistaken, the limit is not in the language itself but in the classfile format, which limits names to 64k, so for all practical intents and purposes identifier length is not a problem. Specifically, this is the definition of a constant string in the pool, which seems to imply the maximal length is 16 bit: ``` CONSTANT_Utf8_info { u1 tag; u2 length; u1 bytes[length]; } ``` Class names may be more of an issue for file systems, I agree, I'm not sure what's currently supported.
Max name length of variable or method in Java
[ "", "java", "naming", "specifications", "name-length", "" ]
I have a C# application over MySql, using [MySQL Connector](http://www.mysql.com); I'm trying to make a DataReader request, the query executes fine, however, when trying to access a DateTime field, i'm getting MySqlConversionException {"Unable to convert MySQL date/time value to System.DateTime"} this is the prototype ``` if (dr != null && !dr.Read()) return; sesion.Id = Convert.ToInt32(dr["id"]); sesion.Usuario = Convert.ToInt32(dr["usuario"]); sesion.Estado = Convert.ToByte(dr["estado"]); // doesn't work sesion.FchCreacion = Convert.ToDateTime(dr["fch_creacion"]); ``` Any suggestions? Thanks in advance
This error sometimes occurs if you have zero datetime values in your MySQL database (00/00/0000 00:00). Try adding this to the end of your connection string: ``` Allow Zero Datetime=true ```
There are a few potential gotchas when converting between MySQL dates/times and .NET DateTimes, but there's a [useful section in the MySQL documentation](http://dev.mysql.com/doc/connector-net/en/connector-net-programming-datetime.html) with advice on how to handle the issues.
MySqlConversionException when accessing DateTime field from DataReader
[ "", "c#", "mysql", "datetime", "idatareader", "" ]