Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
For our school project, we are tasked to define a design document describing the architecture of a PHP application. We are free te decide what to include in the document. Our professor suggested, lots of (UML) diagrams. He also asked us to consider class diagrams, but with care, as PHP is not fully object oriented. My question: Is a Domain Driven Object Oriented Design feasible for a PHP application? What to consider when doing OO in PHP? What are the pro's and con's? Any helpful resources on OO in PHP and PHP best-practices?
IMHO it's pretty difficult to describe the architecture of any application without knowing what the application is supposed to do. All applications (PHP or otherwise) of any complexity look different. Secondly, PHP5 gives you classes/objects and the usual plethora of OO gubbings - so to describe it as 'not fully object orientated' is misleading I think. If you mean you can take a procedural approach with out being restricted to objects then yes, but if you wanted everything to be an object then that's your choice. Is DDD feasible for PHP? Yes, of course. A particular approach to architecture is not usually dependent on technology. Best practices, pros/cons of OO design apply to most languages - PHP leaves you pretty free to decide how to structure your code. You may find this [Best Practices](http://talks.php.net/show/tortech04) talk from the PHP site useful ;)
PHP can nowadays be described as fully object oriented by choice. It offers everything you need but you are not forced to write OO code. There are two books which helped me a lot in understanding the OO principles in relation to PHP: * PHP in Action (Manning) * Zend Study Guide for PHP5 (Zend)
Object Oriented design for PHP application
[ "", "php", "oop", "" ]
I'm trying to run PHPDocumentor on my WAMPServer setup. It runs fine, but I'd like to exclude certain directories, such as \sqlbuddy\ which don't contain my own code. Ironically, PHPDocumentor appears to be ignoring my --ignore switch. I've tried several ways of expressing the same thing, but with the same result. Below is the command I'm running it with: ``` php.exe "C:\Users\username\Documents\PhpDocumentor\phpdoc" -t "C:\Program Files\wamp\www\docs" -o HTML:default:default -d "C:\Program Files\wamp\www" --ignore sqlbuddy\ --ignore docs\ ``` Many thanks.
Which version of phpDocumentor are you using? Because the [phpDocumentor 1.4.2 release notes](http://phpdoc.org/news.php?id=57) states: > This release fixes two > Windows-specific bugs, one involving > usage of the "--ignore" option, and > one involving usage of the @filesource > tag.
I had the same problem, but different cause: ignoring more than one directory requires passing a comma-separated list i.e: `--ignore sqlbuddy/,docs/`
Unable to exclude directories from PHPDocumentor
[ "", "php", "documentation", "phpdoc", "" ]
I have a big red button and I'm trying to use javascript to perform the following: - 1. OnMouseDown change image so the button looks depressed 2. OnMouseUp return to the initial image AND reveal a hidden div I can get the onMouse Down and onMouseUp image changes part to work. I can also get the hidden div to reveal by using OnClick The problem is I can't get it all to work together. How do I do this? BTW, I'm sure its obvious, but I'm fairly new to javascript, so I appreciate your help
You can use semicolons to separate multiple script statements in an event: ``` <img src="..." alt="..." onmousedown="depressed();" onmouseup="undepressed(); revealDiv();" /> ``` Also, I believe most browsers support the onclick event: ``` <img src="..." alt="..." onmousedown="depressed();" onmouseup="undepressed();" onclick="revealDiv();" /> ``` Since you said you had already figured out each of the 3 parts separately, I just wrote function calls that you can replace with your own code for each step.
It's never recommended to attach events to elements using the attribute notation directly to an html element's tag. It is a **much better practice to seperate the view (being the rendered html) from the controller (the actions happening)** The best way to attach an event is like such: ``` <img id="abut" /> <script> var thebutton = document.getElementById('abut'); //Retrieve the button from the page thebutton.onmousedown = depressed; //depressed is a function that you declare earlier on...here, you are just passing a reference to it thebutton.onmouseup = function () { undepressed(); revealDiv(); //Invoke the two functions when the 'onmouseup' is triggered' }; </script> ```
Javascript button click + reveal
[ "", "javascript", "onclick", "onmousedown", "onmouseup", "" ]
I am using Eclipse IDE with few plug-ins for PHP dev. I am using PHPEclipse plug-in and I know there are lotsa other plugins like EasyEclipse.But is there an IDE like Visual Studio with cool drag and drop stuff for PHP?
I use APTANA. You can get it here <http://www.aptana.com/> It's my web IDE of choice.
If you're on Windows you might want to take a look at the (somewhat unfortunately named) "[Delphi for PHP](http://www.codegear.com/products/delphi/php)" from CodeGear / Emabarcadero which I hear mostly good things about - at least for new development that is as it's rather closely tied to a specific framework ([VCL for PHP](http://sourceforge.net/projects/vcl4php/), which is Open Source), which makes it somewhat less of an interesting option for maintaining existing projects.
Is there any IDE for fast drag and drop php development?
[ "", "php", "ide", "" ]
I've done a lot of research on this,but I'm unable to solve this problem. I've got a Div with several Divs within it that I want to hide before switching on a TinyMCE instance. I'm doing this via jQuery - ``` $(".drop").hide() ``` This works fine, and every browser engine except Trident (IE) hides them. If I inspect the elements in IE, the css indicates "display:none". I found a few articles and notes about how this is a feature of IE to show those elements, including this one on MSDN: <http://msdn.microsoft.com/en-us/library/aa770023(VS.85).aspx> The problem is that I need those to hide. Any ideas?
This is because inside an editable element IE makes everything, including elements hidden with display: none, editable. There's nothing you can do about it except remove the elements you wish to hide from the page's DOM. There's a reference to this behaviour of IE here: <http://msdn.microsoft.com/en-us/library/aa770023%28VS.85%29.aspx>
You could try applying a style that sets the display to something other than none, for example: ``` .drop { display: block; // or inline } ``` This sounds like its being caused by IE's need for the element to "have layout" in order to do certain operations on it, hiding being one of them. Elements given a display type of block should have layout, that is, it occupies space and forces the browser to reorganize sibling elements around it.
IE designMode Showing display:none Divs
[ "", "javascript", "jquery", "internet-explorer", "tinymce", "designmode", "" ]
I recently read a question on here about static and dynamic linking, which reminded me of some questions I've had about it. From that post, I can see what the technical difference is (including object file contents directly instead of merely pointing to it), but I'd like to know a bit more about the pros/cons of doing so. A while ago, a friend of mine who's been programming several years was lamenting that C# isn't statically linked and saying that that was the feature he desired most for a future version. Unfortunately I'm a novice and don't really understand this statement. Thanks for any enlightenment!
I am not sure if static linking is a really good idea in C# to be honest, for a million reasons. One reason is that, as opposed to languages like C or C++, C# has the concept of assemblies, which are basically executable files or DLLs. Now if you want link things statically in .NET, you either * Merge classes from multiple assemblies into a single assembly. That would break a lot of things, like the "**internal**" access modifier. * Have more than one assembly in the same executable. That would render the whole concept of assemblies useless though, and would require to redesign the approach to reflection in the .NET Framework. I'm sure there is a clever way to avoid these problems, but I don't quite see the point of statically linking in a managed environment like .NET or Java. I mean, statically linking indeed improves performance, but not THAT much. And we don't use managed languages for their execution speed anyway. Another issue is DLL hell, but in .NET, that's pretty much a solved issue anyway.
The advantage of static linking is that it removes external dependency on libraries - i.e. the behaviour of the library you're using is never going to change because someone changed the libraryon the disk. That's also one of the disadvantages of static linking; if the OS changes and a new version of the library is needed to work with it properly, you have to provide an upgraded version of your binary. Similarly if a bugfix is added to the library, you don't automatically get that bug fix if you've statically linked. Most (in fact, probably all these days) operating systems can load one copy of a dynamic library for multiple processes, which is why on UNIX they're called shared objects.
Static linking advantages
[ "", "c#", "linker", "" ]
What's pros and cons of using Enterprise Library Unity vs other IoC containers (Windsor, Spring.Net, Autofac ..)?
I am preparing a presentation for a usergroup. As such I just went through a bunch of them. Namely: AutoFac, MEF, Ninject, Spring.Net, StructureMap, Unity, and Windsor. I wanted to show off the 90% case (constructor injection, which is mainly what people use an IOC for anyway). [You can check out the solution here (VS2008)](https://cid-b0ed6c076f2f2bfe.skydrive.live.com/self.aspx/Public/IocDemo.zip) As such, there are a few key differences: * Initialization * Object retrieval Each of them have other features as well (some have AOP, and better gizmos, but generally all I want an IOC to do is create and retrieve objects for me) Note: the differences between the different libraries object retrieval can be negated by using the CommonServiceLocator: <http://www.codeplex.com/CommonServiceLocator> That leaves us with initialization, which is done in two ways: via code or via XML configuration (app.config/web.config/custom.config). Some support both, some support only one. I should note: some use attributes to help the IoC along. So here is my assessment of the differences: ### [Ninject](http://ninject.org/) Code initialization only (with attributes). I hope you like lambdas. Initialization code looks like this: ``` IKernel kernel = new StandardKernel( new InlineModule( x => x.Bind<ICustomerRepository>().To<CustomerRepository>(), x => x.Bind<ICustomerService>().To<CustomerService>(), x => x.Bind<Form1>().ToSelf() )); ``` ### [StructureMap](http://structuremap.sourceforge.net/) Initialization code or XML or Attributes. v2.5 is also very lambda'y. All in all, this is one of my favorites. Some very interesting ideas around how StructureMap uses Attributes. ``` ObjectFactory.Initialize(x => { x.UseDefaultStructureMapConfigFile = false; x.ForRequestedType<ICustomerRepository>() .TheDefaultIsConcreteType<CustomerRepository>() .CacheBy(InstanceScope.Singleton); x.ForRequestedType<ICustomerService>() .TheDefaultIsConcreteType<CustomerService>() .CacheBy(InstanceScope.Singleton); x.ForConcreteType<Form1>(); }); ``` ### [Unity](http://codeplex.com/unity) Initialization code and XML. Nice library, but XML configuration is a pain in the butt. Great library for Microsoft or the highway shops. Code initialization is easy: ``` container.RegisterType<ICustomerRepository, CustomerRepository>() .RegisterType<ICustomerService, CustomerService>(); ``` ### [Spring.NET](http://www.springframework.net/) XML only as near as I can tell. But for functionality Spring.Net does everything under the sun that an IoC can do. But because the only way to unitize is through XML it is generally avoided by .net shops. Although, many .net/Java shop use Spring.Net because of the similarity between the .net version of Spring.Net and the Java Spring project. **Note**: Configuration in the code is now possible with the introduction of [Spring.NET CodeConfig](http://www.springframework.net/codeconfig/). ### [Windsor](http://www.castleproject.org/container/index.html) XML and code. Like Spring.Net, Windsor will do anything you could want it to do. Windsor is probably one of the most popular IoC containers around. ``` IWindsorContainer container = new WindsorContainer(); container.AddComponentWithLifestyle<ICustomerRepository, CustomerRepository>("CustomerRepository", LifestyleType.Singleton); container.AddComponentWithLifestyle<ICustomerService, CustomerService>("CustomerService",LifestyleType.Singleton); container.AddComponent<Form1>("Form1"); ``` ### [Autofac](http://code.google.com/p/autofac/) Can mix both XML and code (with v1.2). Nice simple IoC library. Seems to do the basics with not much fuss. Supports nested containers with local scoping of components and a well-defined life-time management. Here is how you initialize it: ``` var builder = new ContainerBuilder(); builder.Register<CustomerRepository>() .As<ICustomerRepository>() .ContainerScoped(); builder.Register<CustomerService>() .As<ICustomerService>() .ContainerScoped(); builder.Register<Form1>(); ``` --- If I had to choose today: I would probably go with StructureMap. It has the best support for C# 3.0 language features, and the most flexibility in initialization. **Note**: Chris Brandsma turned his original answer into a [blog post](http://elegantcode.com/2009/01/07/ioc-libraries-compared/).
As far as I've seen they are pretty much the same, except for a few implementation details here and there. The biggest advantage that Unity has over the competition is that it is provided by Microsoft, there are lots of companies out there that are afraid of OSS. One disadvantage is that it's rather new so it might have bugs that the older players have already sorted out. Having said that, you might want to [check this out](http://weblogs.asp.net/podwysocki/archive/2008/02/22/ioc-and-the-unity-application-block-going-deeper.aspx).
Enterprise Library Unity vs Other IoC Containers
[ "", "c#", ".net", "inversion-of-control", "unity-container", "enterprise-library", "" ]
I have read the following properties from AD, ``` TerminalServicesProfilePath TerminalServicesHomeDirectory TerminalServicesHomeDrive ``` I've tried DirectoryEntry and DirectorySearcher. But they does not include the properties. I found some example in vbscript and VC to read them. However I failed to make it working in C#. Am I missing some tricky thing? EDIT: Am I have to run it on "Windows Server" to make it works? Can it be read from win XP?
I don't remember exactly, but it's something like this: ``` //user is a DirectoryEntry IADsTSUserEx adsiUser = (IADsTSUserEx)user.NativeObject; ``` then you can get the TerminalServices properties you want via adsiUser. From my experience you're better off developing on a Windows Server with access to AD due to the libraries you use. Then you'll probably make the above work, too :)
I think you can use the `InvokeGet` method on your `DirectoryEntry`, passing in the name of the property you want to read. *2008-12-10 11:50 CET — Edited in response to the comment* If I specify a garbage property name, I get the same COM exception. Are you sure the properties you're trying to retrieve are part of the AD schema? Just to make sure, the code I'm using is as follows: ``` using (DirectorySearcher searcher = new DirectorySearcher("(cn=Test)")) { SearchResult result = searcher.FindOne(); if (result != null) { DirectoryEntry entry = result.GetDirectoryEntry(); string s = entry.InvokeGet("TerminalServicesHomeDrive") as string; MessageBox.Show(s ?? "null"); } } ```
How to read TermainsServices IADsTSUserEx Property from LDAP in C#?
[ "", "c#", "ldap", "c#-2.0", "terminal-services", "iadstsuserex", "" ]
Sorry about the vague subject but I couldn't think what to put. Here's my problem, I'm doing a query on a table that returns me a count of items related to a day. I want to make sure that if I do a query on the DB, I always get a set number of rows. For example, imagine I have the following table that contains a log of when people log into a website: ``` **WebsiteLogin** id: Integer login_date: Datetime ``` I can then get counts of the logins for each date by doing something like: ``` SELECT DATE(login_date), COUNT(*) FROM WebsiteLogin GROUP BY DATE(login_date) ``` Which works great and will return me the data I want. But imagine my website was quite unpopular on the weekends. The data returned would look like: ``` 2008-12-10, 100 2008-12-11, 124 2008-12-12, 151 2008-12-15, 141 2008-12-16, 111 ``` The 13th & 14th are missing because there was no data for those dates. Is there any way I can change my query so that I get data that includes all the dates I query on. E.g. ``` 2008-12-10, 100 2008-12-11, 124 2008-12-12, 151 2008-12-13, 0 2008-12-14, 0 2008-12-15, 141 2008-12-16, 111 ``` I imagine I could do this if I set up a table containing all the dates in a year and then using a left/right join but that's really messy way of doing it. So any clues on a nice way to do this in SQL? Or is programmatically my only choice? Cheers for any input.
> I imagine I could do this if I set up a table containing all the dates in a year and then using a left/right join but that's really messy way of doing it. Nope. That's pretty much how to do it. On the other hand, you can use a temporary table and populate it with just the date range required. If only MS SQL had virtual tables, where you provided a generator function...
To do this you would need to write a stored procedure that returns a table result. It would use a loop that would step thru each day and get the count and store it in a row of a temp table, then return that table as the resultset. Here is a MS SQL server example of a loop: <http://www.databasejournal.com/features/mssql/article.php/3100621/T-SQL-Programming-Part-2---Building-a-T-SQL-Loop.htm>
Filling In The Blanks On A SQL Query
[ "", "sql", "mysql", "" ]
Is there local file manipulation that's been done with JavaScript? I'm looking for a solution that can be accomplished with no install footprint like requiring [Adobe AIR](http://en.wikipedia.org/wiki/Adobe_Integrated_Runtime). Specifically, I'd like to read the contents from a file and write those contents to another file. At this point I'm not worried about gaining permissions and am just assuming I already have full permissions to these files.
If the user selects a file via `<input type="file">`, you can [read](https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications) and [process](http://www.html5rocks.com/en/tutorials/file/dndfiles/) that file using the [File API](https://www.w3.org/TR/FileAPI/). Reading or writing arbitrary files is not allowed by design. It's a violation of the sandbox. From [Wikipedia -> Javascript -> Security](http://en.wikipedia.org/wiki/JavaScript#Security): > JavaScript and the DOM provide the > potential for malicious authors to > deliver scripts to run on a client > computer via the web. Browser authors > contain this risk using two > restrictions. First, scripts run in a > sandbox in which they can only perform > web-related actions, not > general-purpose programming tasks like > **creating files**. **2016 UPDATE**: Accessing the filesystem directly is possible via the [Filesystem API](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API), which is [only supported by Chrome and Opera](http://caniuse.com/#feat=filesystem) and [may end up not being implemented by other browsers](http://www.html5rocks.com/en/tutorials/file/filesystem/) (with the [exception of Edge](https://developer.microsoft.com/en-us/microsoft-edge/platform/status/filewriter/)). For details see [Kevin's answer](https://stackoverflow.com/questions/371875/local-file-access-with-javascript/38254151#38254151).
Just an update of the HTML5 features is in <http://www.html5rocks.com/en/tutorials/file/dndfiles/>. This excellent article will explain in detail the local file access in JavaScript. Summary from the mentioned article: The specification provides several interfaces for [accessing files from a 'local' filesystem](http://www.html5rocks.com/en/tutorials/file/dndfiles/): 1. File - an individual file; provides readonly information such as name, file size, MIME type, and a reference to the file handle. 2. FileList - an array-like sequence of File objects. (Think `<input type="file" multiple>` or dragging a directory of files from the desktop). 3. Blob - Allows for slicing a file into byte ranges. See Paul D. Waite's comment below.
Local file access with JavaScript
[ "", "javascript", "file-access", "" ]
If I have a few UNION Statements as a contrived example: ``` SELECT * FROM xxx WHERE z = 1 UNION SELECT * FROM xxx WHERE z = 2 UNION SELECT * FROM xxx WHERE z = 3 ``` **What is the default `order by` behaviour?** The test data I'm seeing essentially does not return the data in the order that is specified above. I.e. the data is ordered, but I wanted to know what are the rules of precedence on this. Another thing is that in this case xxx is a View. The view joins 3 different tables together to return the results I want.
There is no default order. Without an **Order By** clause the order returned is undefined. That means SQL Server can bring them back in any order it likes. EDIT: Based on what I have seen, without an Order By, the order that the results come back in depends on the query plan. So if there is an index that it is using, the result may come back in that order but again there is no guarantee.
In regards to adding an ORDER BY clause: This is probably elementary to most here but I thought I add this. Sometimes you don't want the results mixed, so you want the first query's results then the second and so on. To do that I just add a dummy first column and order by that. Because of possible issues with forgetting to alias a column in unions, I usually use ordinals in the order by clause, not column names. For example: ``` SELECT 1, * FROM xxx WHERE z = 'abc' UNION ALL SELECT 2, * FROM xxx WHERE z = 'def' UNION ALL SELECT 3, * FROM xxx WHERE z = 'ghi' ORDER BY 1 ``` The dummy ordinal column is also useful for times when I'm going to run two queries and I know only one is going to return any results. Then I can just check the ordinal of the returned results. This saves me from having to do multiple database calls and most empty resultset checking.
SQL Server UNION - What is the default ORDER BY Behaviour
[ "", "sql", "sql-server", "union", "sql-order-by", "" ]
Having read up on quite a few articles on Artificial Life (A subject I find very interesting) along with several questions right here on SO, I've begun to toy with the idea of designing a (Very, very, very) simple simulator. No graphics required, even. If I've overlooked a question, please feel free to point it out to me. Like I said, this will hardly be a Sims level simulation. I believe it will barely reach "acceptable freeware" level, it is simply a learning exercise and something to keep my skills up during a break. The basic premise is that a generic person is created. No name, height or anything like that (Like I said, simple), the only real thing it will receive is a list of "associations" and generic "use", "pick up" and "look" abilities. **My first question** is in regards to the associations. What does SO recommend as an efficient way to handle such things? I was thinking a multimap, with the relatively easy set up of the key being what it wants (Food, eat, rest, et cetera) and the other bit (Sorry, my mind has lapsed) being what it associates with that need. For example, say we have a fridge. The fridge contains food (Just a generic base object). Initially the person doesn't associate fridge with food, but it does associate food with hunger. So when its hunger grows it begins to arbitrarily look for food. If no food is within reach it "uses" objects to find food. Since it has no known associations with food it uses things willy-nilly (Probably looking for the nearest object and expanding out). Once it uses/opens the fridge it sees food, making the connection (Read: inserting the pair "food, fridge") that the fridge contains food. Now, I realise this will be far more complex than it appears, and I'm prepared to hammer it out. The question is, would a multimap be suitable for a (Possibly) exponentially expanding list of associations? If not, what would be? **The second question** I have is probably far easier. Simply put, would a generic object/item interface be suitable for most any item? In other words, would a generic "use" interface work for what I intend? I don't think I'm explaining this well. Anyway, any comments are appreciated.
If you were doing this as a hard-core development project, I'd suggest using the equivalent of Java reflection (substitute the language of your choice there). If you want to do a toy project as a starter effort, I'd suggest at least rolling your own simple version of reflection, per the following rationale. Each artifact in your environment offers certain capabilities. A simple model of that fact is to ask what "verbs" are applicable to each object your virtual character encounters (including possible dependence on the current state of that object). For instance, your character can "open" a refrigerator, a box of cereal, or a book, provided that each of them is in a "closed" state. Once a book is opened, your character can read it or close it. Once a refrigerator is opened, your character can "look-in" it to get a list of visible contents, can remove an object from it, put an object in it, etc. The point is that a typical situation might involve your character looking around to see what is visible, querying an object to determine its current state or what can be done with it (i.e. "what-state" and "what-can-i-do" are general verbs applicable to all objects), and then use knowledge about its current state, the state of the object, and the verb list for that object to try doing various things. By implementing a set of positive and negative feedback, over time your character can "learn" under what circumstances it should or should not engage in different behaviors. (You could obviously make this simulation interactive by having it ask the user to participate in providing feedback.) The above is just a sketch, but perhaps it can give you some interesting ideas to play with. Have fun! ;-)
To the first question: My understanding is that you have one-to-possibly-many relationship. So yes, a multimap seems appropriate to me. To the second question: Yes, I believe a generic interface for objects is appropriate. Perhaps use something similar to [REST](http://en.wikipedia.org/wiki/REST) to manipulate object state.
Efficient Methods for a Life Simulation
[ "", "c++", "performance", "artificial-life", "" ]
I have been programming in Java since 2004, mostly enterprise and web applications. But I have never used *short* or *byte*, other than a toy program just to know how these types work. Even in a *for loop* of 100 times, we usually go with *int*. And I don't remember if I have ever came across any code which made use of *byte* or *short*, other than some public APIs and frameworks. Yes I know, you can use a *short* or *byte* to save memory in large arrays, in situations where the memory savings actually matters. Does anyone care to practice that? Or its just something in the books. **[Edited]** Using *byte* arrays for network programming and socket communication is a quite common usage. Thanks, Darren, to point that out. Now how about *short*? Ryan, gave an excellent example. Thanks, Ryan.
Keep in mind that Java is also used on mobile devices, where memory is much more limited.
I use byte a lot. Usually in the form of byte arrays or ByteBuffer, for network communications of binary data. I rarely use float or double, and I don't think I've ever used short.
Anyone using short and byte primitive types, in real apps?
[ "", "java", "types", "primitive", "" ]
How are you supposed to unit test a web service in C# with Visual Studio 2008? When I generate a unit test it adds an actual reference to the web service class instead of a web reference. It sets the attributes specified in: <http://msdn.microsoft.com/en-us/library/ms243399(VS.80).aspx#TestingWebServiceLocally> Yet, it will complete without executing the test. I attempted to add the call to `WebServiceHelper.TryUrlRedirection(...)` but the call does not like the target since it inherits from `WebService`, not `WebClientProtocol`.
What I usually do is not test directly against the web-service, but to try and put as little code as possible in the service, and call a different class which does all the real work. Then I write unit tests for that other class. It turns out that class can sometimes be useful outside of the web-service context, so this way - you gain twice.
If you are writing a web service, try to put all logic in another (testable) layer. Each Web method should have a little code as possible. Then you will have little reason to test the web method directly because you can test the underlying layers. ``` [WebMethod] public void DoSomething() { hander.DoSomething(); } ``` If you are consuming a web method, wrap the generated caller in a class wrapper, and implement an interface for the class wrapper. Then, anytime you need to call the web service, use the interface to call the method. You want to use the interface so as to make the class wrapper swappable during testing (using Rhino Mocks, Moq, or TypeMock).
How to unit test C# Web Service with Visual Studio 2008
[ "", "c#", "web-services", "unit-testing", "" ]
This is a subjective question. I worked in Visual Basic 6.0 before coming into the .NET space. One thing I see that there are a lot of things, for which there is a need to deal with the Win32 API. As a Visual Basic 6.0 developer, there were a lot of limitations. .NET fixes some of the old problems however the need to rely on Win32 has not been taken care of. Will there be anytime that there wouldn't be the need to rely on Win32? (I guess only when .NET has support at OS level.) I understand that domain of .NET (writing [LOB](http://en.wikipedia.org/wiki/Line_of_business) applications/websites) and C/C++ is different so far. Can .NET or any other infrastructure really make C/C++ less significant? Am I expecting too much? EDIT: Doesn't it look like, building wrapper over another wrapper (and bring in new set of complexities along-with it)?
It can't go away any time soon, but in Windows, at least, new projects are going less and less with C/C++. You can even see examples of Microsoft starting to eat their own dog food. A great example of this is the C# compiler. Currently, it is written in C/C++. The C# team is currently working on re-writing it purely in managed code. A big reason for this has to do with CAS policies in .NET. Invoking unmanaged code requires FullTrust, so compiling code also requires FullTrust. As they move over to managed code, this limitation goes away. As more and more developers go to .NET as their development platform, we are seeing Microsoft follow suit. Another great example is Visual Studio 2010. They are re-writing large portions of the IDE using WPF and MEF so that it is easily extensible. Next, look at the Silverlight runtime. It doesn't rely (specifically) on Win32 at all. It runs on a Mac just as well as it runs on Windows. As Silverlight becomes more capable, we may find many of the .NET calls that currently rely on Win32 no longer do so. I guess my point is that we ARE starting to see some changes **in the Windows world** at least. Of course, as soon as you need to be more cross-platform, C/C++ becomes more appealing again...
Not any time soon. They aren't going to re-write the kernel and the core APIs in .NET in the near future, if ever. People have been expecting C to go away for a very long time, I just don't see it happening.
Will .NET take over C/C++ any time?
[ "", ".net", "c++", "c", "" ]
I am trying to insert a very long text string into a MySQL Blob column, but MySQL is only saving 64kB of the data. The string is 75360 characters long. I am connecting with PHP's `mysql_connect()`. Any ideas? Does it make a difference if it's Blob or Text. I originally had it as a Text but changed it with no affect.
Because that's the [maximum size](http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html) of a BLOB column. You need to use MEDIUMBLOB/LONGBLOB or MEDIUMTEXT/LONGTEXT.
A `BLOB` type in MySQL can store up to 65,534 bytes, if you try to store more than this much data MySQL will truncate the data. `MEDIUMBLOB` can store up to 16,777,213 bytes, and `LONGBLOB` can store up to 4,294,967,292 bytes. If you enable strict SQL mode ([MySQL modes](http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html)) you will get an error when you try to store data that doesn't fit in the column type.
Why is only 64kB of data being saved in my MySQL data column?
[ "", "php", "mysql", "text", "blob", "" ]
I have a structure which I create a custom constructor to initialize the members to 0's. I've seen in older compilers that when in release mode, without doing a memset to 0, the values are not initialized. I now want to use this structure in a union, but get errors because it has a non-trivial constructor. So, question 1. Does the default compiler implemented constructor guarantee that all members of a structure will be null initialized? The non-trivial constructor just does a memset of all the members to '0' to ensure a clean structure. Question 2: If a constructor must be specified on the base structure, how can a union be implemented to contain that element and ensure a 0 initialized base element?
Question 1: Default constructors do initialize POD members to 0 according to the C++ standard. See the quoted text below. Question 2: If a constructor must be specified in a base class, then that class cannot be part of a union. Finally, you can provide a constructor for your union: ``` union U { A a; B b; U() { memset( this, 0, sizeof( U ) ); } }; ``` For Q1: From C++03, 12.1 Constructors, pg 190 The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with an empty mem-initializer-list (12.6.2) and an empty function body. From C++03, 8.5 Initializers, pg 145 To default-initialize an object of type T means: * if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor); * if T is an array type, each element is default-initialized; * *otherwise, the object is zero-initialized*. To zero-initialize an object of type T means: * if T is a scalar type (3.9), the object is set to the value of 0 (zero) converted to T; * *if T is a non-union class type, each non static data member and each base-class subobject is zero-initialized*; * ***if T is a union type, the object’s first named data member is zero-initialized;*** * if T is an array type, each element is zero-initialized; * if T is a reference type, no initialization is performed. For Q2: From C++03, 12.1 Constructors, pg 190 A constructor is trivial if it is an implicitly-declared default constructor and if: * its class has no virtual functions (10.3) and no virtual base classes (10.1), and * all the direct base classes of its class have trivial constructors, and * for all the nonstatic data members of its class that are of class type (or array thereof), each such class has a trivial constructor From C++03, 9.5 Unions, pg 162 A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. A union shall not have base classes. A union shall not be used as a base class.An object of a class with a non-trivial constructor (12.1), a non-trivial copy constructor (12.8), a non-trivial destructor (12.4), or a non-trivial copy assignment operator (13.5.3, 12.8) cannot be a member of a union, nor can an array of such objects
**Things changed for the better in C++11.** You can now legally do this, as [described by Stroustrup](http://www.stroustrup.com/C++11FAQ.html#unions) himself (I reached that link from the [Wikipedia article on C++11](https://en.wikipedia.org/wiki/C%2B%2B11#Unrestricted_unions)). The example on Wikipedia is as follows: ``` #include <new> // Required for placement 'new'. struct Point { Point() {} Point(int x, int y): x_(x), y_(y) {} int x_, y_; }; union U { int z; double w; Point p; // Illegal in C++03; legal in C++11. U() {new(&p) Point();} // Due to the Point member, a constructor // definition is now *required*. }; ``` Stroustrup goes into a little more detail.
Initializing a union with a non-trivial constructor
[ "", "c++", "constructor", "multiplatform", "" ]
I am working with a set of data that I have converted to a list of dictionaries For example one item in my list is ``` {'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2005', 'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Bananas'} ``` Per request The second item in my list could be: ``` {'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2006', 'actionDate': u'C20070627', 'data': u'86,000', 'rowLabel': u'Sales of Bananas'} ``` The third item could be: ``` {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2005', 'actionDate': u'C20070627', 'data': u'116,000', 'rowLabel': u'Sales of Cherries'} ``` The fourth item could be: ``` {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2006', 'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Sales of Cherries'} ``` The reason I need to pickle this is because I need to find out all of the ways the columns were labeled before I consolidate the results and put them into a database. The first and second items will be one row in the results, the third and fourth would be the next line in the results (after someone decides what the uniform column header label should be) I tested pickle and was able to save and retrieve my data. However, I need to be able to preserve the order in the output. One idea I have is to add another key that would be a counter so I could retrieve my data and then sort by the counter. Is there a better way? I don't want to put this into a database because it is not permanent. I marked an answer down below. It is not what I am getting, so I need to figure out if the problem is somewhere else in my code.
So what's wrong with pickle? If you structure your data as a list of dicts, then everything should work as you want it to (if I understand your problem). ``` >>> import pickle >>> d1 = {1:'one', 2:'two', 3:'three'} >>> d2 = {1:'eleven', 2:'twelve', 3:'thirteen'} >>> d3 = {1:'twenty-one', 2:'twenty-two', 3:'twenty-three'} >>> data = [d1, d2, d3] >>> out = open('data.pickle', 'wb') >>> pickle.dump(data, out) >>> out.close() >>> input = open('data.pickle') >>> data2 = pickle.load(input) >>> data == data2 True ```
Python does not retain order in dictionaries. However, there is the [OrderedDict](http://docs.python.org/2/library/collections.html?highlight=collections#ordereddict-objects) class in the *collections* module. Another option would be to use a list of tuples: ``` [('reportDate', u'R20080501'), ('idnum', u'1078099'), ...etc] ``` You can use the built in `dict()` if you need to convert this to a dictionary later.
Does anyone know where there is a recipe for serializing data and preserving its order in the output?
[ "", "python", "serialization", "" ]
I doubt I am the only one who has come up with this solution, but if you have a better one please post it here. I simply want to leave this question here so I and others can search it later. I needed to tell whether a valid date had been entered into a text box and this is the code that I came up with. I fire this when focus leaves the text box. ``` try { DateTime.Parse(startDateTextBox.Text); } catch { startDateTextBox.Text = DateTime.Today.ToShortDateString(); } ```
``` DateTime.TryParse ``` This I believe is faster and it means you dont have to use ugly try/catches :) e.g ``` DateTime temp; if(DateTime.TryParse(startDateTextBox.Text, out temp)) { // Yay :) } else { // Aww.. :( } ```
Don't use exceptions for flow control. Use [DateTime.TryParse](http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx) and [DateTime.TryParseExact](http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx). Personally I prefer TryParseExact with a specific format, but I guess there are times when TryParse is better. Example use based on your original code: ``` DateTime value; if (!DateTime.TryParse(startDateTextBox.Text, out value)) { startDateTextox.Text = DateTime.Today.ToShortDateString(); } ``` Reasons for preferring this approach: * Clearer code (it says what it wants to do) * Better performance than catching and swallowing exceptions * This doesn't catch exceptions inappropriately - e.g. OutOfMemoryException, ThreadInterruptedException. (Your current code could be fixed to avoid this by just catching the relevant exception, but using TryParse would still be better.)
How to Validate a DateTime in C#?
[ "", "c#", "datetime", "validation", "" ]
I'm using php and I have the following code to convert an absolute path to a url. ``` function make_url($path, $secure = false){ return (!$secure ? 'http://' : 'https://').str_replace($_SERVER['DOCUMENT_ROOT'], $_SERVER['HTTP_HOST'], $path); } ``` My question is basically, is there a better way to do this in terms of security / reliability that is portable between locations and servers?
The [HTTP\_HOST variable is not a reliable or secure value](http://shiflett.org/blog/2006/mar/server-name-versus-http-host) as it is also being sent by the client. So be sure to validate its value before using it.
I don't think security is going to be effected, simply because this is a url, being printed to a browser... the worst that can happen is exposing the full directory path to the file, and potentially creating a broken link. As a little side note, if this is being printed in a HTML document, I presume you are passing the output though something like htmlentities... just in-case the input $path contains something like a [script] tag (XSS). To make this a little more reliable though, I wouldn't recommend matching on 'DOCUMENT\_ROOT', as sometimes its either not set, or won't match (e.g. when Apache rewrite rules start getting in the way). If I was to re-write it, I would simply ensure that 'HTTP\_HOST' is always printed... ``` function make_url($path, $secure = false){ return (!$secure ? 'http://' : 'https://').$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', $path); } ``` ... and if possible, update the calling code so that it just passes the path, so I don't need to even consider removing the 'DOCUMENT\_ROOT' (i.e. what happens if the path does not match the 'DOCUMENT\_ROOT')... ``` function make_url($path, $secure = false){ return (!$secure ? 'http://' : 'https://').$_SERVER['HTTP_HOST'].$path; } ``` Which does leave the question... why have this function? On my websites, I simply have a variable defined at the beggining of script execution which sets: ``` $GLOBALS['webDomain'] = 'http://' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''); $GLOBALS['webDomainSSL'] = $GLOBALS['webDomain']; ``` Where I use GLOBALS so it can be accessed anywhere (e.g. in functions)... but you may also want to consider making a constant (define), if you know this value won't change (I sometimes change these values later in a site wide configuration file, for example, if I have an HTTPS/SSL certificate for the website).
Converting a filepath to a url securely and reliably
[ "", "php", "security", "url", "robustness", "" ]
I am using google's appengine api ``` from google.appengine.api import urlfetch ``` to fetch a webpage. The result of ``` result = urlfetch.fetch("http://www.example.com/index.html") ``` is a string of the html content (in result.content). The problem is the data that I want to parse is not really in HTML form, so I don't think using a python HTML parser will work for me. I need to parse all of the plain text in the body of the html document. The only problem is that urlfetch returns a single string of the entire HTML document, removing all newlines and extra spaces. **EDIT:** Okay, I tried fetching a different URL and apparently urlfetch does not strip the newlines, it was the original webpage I was trying to parse that served the HTML file that way... **END EDIT** If the document is something like this: ``` <html><head></head><body> AAA 123 888 2008-10-30 ABC BBB 987 332 2009-01-02 JSE ... A4A 288 AAA </body></html> ``` result.content will be this, after urlfetch fetches it: ``` '<html><head></head><body>AAA 123 888 2008-10-30 ABCBBB 987 2009-01-02 JSE...A4A 288 AAA</body></html>' ``` Using an HTML parser will not help me with the data between the body tags, so I was going to use regular expresions to parse my data, but as you can see the last part of one line gets combined with the first part of the next line, and I don't know how to split it. I tried ``` result.content.split('\n') ``` and ``` result.content.split('\r') ``` but the resulting list was all just 1 element. I don't see any options in google's urlfetch function to not remove newlines. Any ideas how I can parse this data? Maybe I need to fetch it differently? Thanks in advance!
I understand that the format of the document is the one you have posted. In that case, I agree that a parser like [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) may not be a good solution. I assume that you are already getting the interesting data (between the BODY tags) with a regular expression like ``` import re data = re.findall('<body>([^\<]*)</body>', result)[0] ``` then, it should be as easy as: ``` start = 0 end = 5 while (end<len(data)): print data[start:end] start = end+1 end = end+5 print data[start:] ``` (note: I did not check this code against boundary cases, and I do expect it to fail. It is only here to show the generic idea)
Only suggestion I can think of is to parse it as if it has fixed width columns. Newlines are not taken into consideration for HTML. If you have control of the source data, put it into a text file rather than HTML.
Parsing fixed-format data embedded in HTML in python
[ "", "python", "html", "google-app-engine", "parsing", "html-content-extraction", "" ]
[Medicare Eligibility EDI Example Responses](https://medifacd.relayhealth.com/Pharmacies/MediFacD_Pharmacies_PayerSheet_E1December2006.htm#Examples "Medicare Eligibility EDI Example Responses") is what I'm trying to match. I have a string that looks like this: ``` LN:SMITHbbbbbbbbFN:SAMANTHAbbBD:19400515PD:1BN:123456PN:9876543210GP:ABCDEFGHIJKLMNOID:123456789012345bbbbbPC:123PH:8005551212CD:123456PB:123ED:20060101TD:2070101LC:NFI:12345678FE:20070101FT:20080101 ``` I need a set of matches that look like this: ``` Key | Value ------------------- LN | SMITHbbbbbbbb FN | SAMANTHAbb BD | 19400515 ... etc ``` I've been dealing with this all day, and I can't seem to get an acceptable matching scenario. I'm about to program it procedurally with a for loop and finding indexes of colons if I can't figure something out. I've tried using [negative lookahead](http://yacsharpblog.blogspot.com/2008/09/regular-expressions-in-c-negative-look.html "C# Negative Lookahead") and I'm not getting anywhere. This is C#, and I'm using [this tester](http://regexlib.com/RETester.aspx ".Net Online Regular Expression Tester") (.Net) while I'm testing, along with [The Regex Coach](http://www.weitz.de/regex-coach/ "The Regex Coach") (non .Net). I've tried using this: ``` ([\w]{2})\:(?![\w]{2}\:) ``` But that only matches the keys and their colons, like "LN:", "FN:", etc. If I use: ``` ([\w]{2})\:(.+?)([\w]{2})\: ``` It consumes the next matching two character key and colon as well, leading to me only matching every other key/value pair. Is there a way for me to match these using RegEx in .Net correctly, or am I stuck with a more procedural solution? Keep in mind, I can't assume that the keys will always be upper case letters. They could possibly include numbers, but they will always be two characters and then a colon. Thanks in advance for any help I can get.
I think what you want is positive lookahead, not negative, so that you find the key-colon combo ahead of the current position, but you don't consume it. This appears to work for your test example: ``` ([\w]{2})\:(.+?)(?=[\w]{2}\:|$) ``` Yielding: ``` LN: SMITHbbbbbbbb FN: SAMANTHAbb BD: 19400515 PD: 1 BN: 123456 PN: 9876543210 ... ``` Note: I added the colons in my test output, they aren't captured by the regex. EDIT: Thanks, Douglas, I've edited the regex to capture end-of-string so the last entry is captured, too.
Looking at the link each field is of a fixed length, so you could do something like this: ``` int pos = 0; Dictionary<string, string> parsedResults = new Dictionary<string, string>(); foreach (int length in new int[] { 13, 10, 8, 1, 6, 10, 15, 20, 3, 10, 6, 3, 8, 8, 1, 8, 8, 8, }) { string fieldId = message.Substring(pos, 2); string fieldValue = message.Substring(pos + 3, length); parsedResults.Add(fieldId, fieldValue); pos += length + 3; } ```
RegEx matching with no single letter delimiter
[ "", "c#", "regex", "regex-lookarounds", "" ]
I recently saw a bit of code that looked like this (with sock being a socket object of course): ``` sock.shutdown(socket.SHUT_RDWR) sock.close() ``` What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO.
Here's one [explanation](http://publib.boulder.ibm.com/infocenter/systems/index.jsp?topic=/com.ibm.aix.progcomm/doc/progcomc/skt_shutdn.htm): > Once a socket is no longer required, > the calling program can discard the > socket by applying a close subroutine > to the socket descriptor. If a > reliable delivery socket has data > associated with it when a close takes > place, the system continues to attempt > data transfer. However, if the data is > still undelivered, the system discards > the data. Should the application > program have no use for any pending > data, it can use the shutdown > subroutine on the socket prior to > closing it.
Calling `close` and `shutdown` have two different effects on the underlying socket. The first thing to point out is that the socket is a resource in the underlying OS and **multiple processes can have a handle for the same underlying socket.** When you call `close` it decrements the handle count by one and if the handle count has reached zero then the socket and associated connection goes through the normal close procedure (effectively sending a FIN / EOF to the peer) and the socket is deallocated. The thing to pay attention to here is that if the handle count does not reach zero because another process still has a handle to the socket then the connection **is not closed and the socket is not deallocated.** On the other hand calling `shutdown` for reading and writing closes the underlying connection and sends a FIN / EOF to the peer regardless of how many processes have handles to the socket. However, it **does not** deallocate the socket and you still need to call close afterward.
socket.shutdown vs socket.close
[ "", "python", "sockets", "asynchronous", "" ]
I'm writing a GUI application in Python using wxPython and I want to display an image in a static control (`wx.StaticBitmap`). I can use [`wx.ImageFromStream`](http://www.wxpython.org/docs/api/wx-module.html#ImageFromStream) to load an image from a file, and this works OK: ``` static_bitmap = wx.StaticBitmap(parent, wx.ID_ANY) f = open("test.jpg", "rb") image = wx.ImageFromStream(f) bitmap = wx.BitmapFromImage(image) static_bitmap.SetBitmap(bitmap) ``` But, what I really want to be able to do is create the image from data in memory. So, if I write ``` f = open("test.jpg", "rb") data = f.read() ``` how can I create a `wx.Image` object from `data`? Thanks for your help!
You should be able to use `StringIO` to wrap the buffer in a memory file object. ``` ... import StringIO buf = open("test.jpg", "rb").read() # buf = get_image_data() sbuf = StringIO.StringIO(buf) image = wx.ImageFromStream(sbuf) ... ``` `buf` can be replaced with any data string.
Since in Python you use Duck Typing you can write your own stream class and hand an instance of that class to ImageFromStream. I think you only need to implement the read method and make it return your data.
How do I create a wx.Image object from in-memory data?
[ "", "python", "wxpython", "wxwidgets", "" ]
As the topic suggests I wish to be able to pass table names as parameters using .NET (doesn't matter which language really) and SQL Server. I know how to do this for values, e.g. `command.Parameters.AddWithValue("whatever", whatever)` using `@whatever` in the query to denote the parameter. The thing is I am in a situation where I wish to be able to do this with other parts of the query such as column and table names. This is not an ideal situation but it's one I have to use, it's not really prone to SQL injection as only someone using the code can set these table names and not the end-user. It is messy however. So, is what I am asking possible? EDIT: To make the point about SQL injection clear, the table names are only passed in by source code, depending on the situation. It is the developer who specifies this. The developer will have access to the database layer anyway, so the reason I am asking is not so much for security but just to make the code cleaner.
I don't *think* I've ever seen this capability in any SQL dialect I've seen, but it's not an area of expertise. I would suggest restricting the characters to A-Z, a-z, 0-9, '.', '\_' and ' ' - and then use whatever the appropriate bracketing is for the database (e.g. [] for SQL Server, I believe) to wrap round the whole thing. Then just place it directly in the SQL. It's not entirely clear what you meant about it not being a SQL injection risk - do you mean the names will be in source code and only in source code? If so, I agree that makes things better. You may not even need to do the bracketing automatically, *if* you trust your developers not to be cretins (deliberately or not).
You cannot directly parameterize the table name. You can do it indirectly via `sp_ExecuteSQL`, but you might just as well build the (parameterized) TSQL in C# (concatenating the table-name but not the other values) and send it down as a command. You get the same security model (i.e. you need explicit SELECT etc, and assuming it isn't signed etc). Also - be sure to white-list the table name.
Parameterise table name in .NET/SQL?
[ "", "sql", ".net", "sql-server", "parameters", "" ]
Or any open source project which utilize collective intelligence extensively?.
There's a new book out from Manning, ["Collective Intelligence in Action"](http://www.manning.com/alag/). There are also code samples available written in Java. I also recommend the Toby Segaran book. Coming from a Java background I was able to follow the Python code without a problem.
Take a look at the book [Collective Intelligence](https://rads.stackoverflow.com/amzn/click/com/0596529325) by Toby Segaran. It covers lots of topics, such as how Amazon generates recommendations etc etc. There's lots of source code in the book written in Python, which should be easy to port to Java/.Net
Which are the good open source libraries for Collective Intelligence in .net/java?
[ "", "java", ".net", "collective-intelligence", "" ]
Okay, what is it, and why does it occur on Win2003 server, but not on WinXP. It doesn't seem to affect my application at all, but I get this error message when I close the application. And it's annoying (as errors messages should be). I am using pyOpenGl and wxPython to do the graphics stuff. Unfortunately, I'm a C# programmer that has taken over this Python app, and I had to learn Python to do it. I can supply code and version numbers etc, but I'm still learning the technical stuff, so any help would be appreciated. Python 2.5, wxPython and pyOpenGL
Looks like OpenGL is trying to report some error on Win2003, however you've not configured your system where to output logging info. You can add the following to the beginning of your program and you'll see details of the error in stderr. ``` import logging logging.basicConfig() ``` Checkout documentation on [logging](https://docs.python.org/2/library/logging.html) module to get more config info, conceptually it's similar to log4J.
The [proper way](https://github.com/techtonik/rainforce/blob/master/WartsOfPython.wiki#logging) to get rid of this message is to configure NullHandler for the root level logger of your library (OpenGL).
Python - No handlers could be found for logger "OpenGL.error"
[ "", "python", "logging", "opengl", "wxpython", "pyopengl", "" ]
Can we convert a hex string to a byte array using a built-in function in C# or do I have to make a custom method for this?
Here's a nice fun LINQ example. ``` public static byte[] StringToByteArray(string hex) { return Enumerable.Range(0, hex.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) .ToArray(); } ```
I did some research and found out that byte.Parse is even slower than Convert.ToByte. The fastest conversion I could come up with uses approximately 15 ticks per byte. ``` public static byte[] StringToByteArrayFastest(string hex) { if (hex.Length % 2 == 1) throw new Exception("The binary key cannot have an odd number of digits"); byte[] arr = new byte[hex.Length >> 1]; for (int i = 0; i < hex.Length >> 1; ++i) { arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1]))); } return arr; } public static int GetHexVal(char hex) { int val = (int)hex; //For uppercase A-F letters: //return val - (val < 58 ? 48 : 55); //For lowercase a-f letters: //return val - (val < 58 ? 48 : 87); //Or the two combined, but a bit slower: return val - (val < 58 ? 48 : (val < 97 ? 55 : 87)); } ``` // also works on .NET Micro Framework where (in SDK4.3) byte.Parse(string) only permits integer formats.
How can I convert a hex string to a byte array?
[ "", "c#", "encoding", "hex", "" ]
I want to register a specific instance of an object for a type in structuremap, how can I do that? For example, When I do: ``` var myObj = ObjectFactory.GetInstance(typeof(MyAbstractClass)); ``` i would like it to return a previously constructed concrete class, which i created like this: ``` var myClass = new MyConcreteClass("bla"); // MyConcreteClass : MyAbstractClass ``` so ``` myObj == myClass ``` How do i register myClass with structuremap to facilitate this? Thanks Andrew
I believe you would do this in you initialization ``` ObjectFactory.Initialize(x => { x.ForRequestedType<MyAbstractClass>().TheDefault.IsThis(myClass); }); ``` Where myClass is the instance of the object you want to return.
You can inject a concrete instance as the default by ``` ObjectFactory.Inject(typeof(MyAbstractClass), myClass); ```
How to get StructureMap to return a specific instance for a requested type
[ "", "c#", "structuremap", "" ]
What is the difference between abstract class and interface in Python?
What you'll see sometimes is the following: ``` class Abstract1: """Some description that tells you it's abstract, often listing the methods you're expected to supply.""" def aMethod(self): raise NotImplementedError("Should have implemented this") ``` Because Python doesn't have (and doesn't need) a formal Interface contract, the Java-style distinction between abstraction and interface doesn't exist. If someone goes through the effort to define a formal interface, it will also be an abstract class. The only differences would be in the stated intent in the docstring. And the difference between abstract and interface is a hairsplitting thing when you have duck typing. Java uses interfaces because it doesn't have multiple inheritance. Because Python has multiple inheritance, you may also see something like this ``` class SomeAbstraction: pass # lots of stuff - but missing something class Mixin1: def something(self): pass # one implementation class Mixin2: def something(self): pass # another class Concrete1(SomeAbstraction, Mixin1): pass class Concrete2(SomeAbstraction, Mixin2): pass ``` This uses a kind of abstract superclass with mixins to create concrete subclasses that are disjoint.
> # What is the difference between abstract class and interface in Python? An interface, for an object, is a set of methods and attributes on that object. In Python, we can use an abstract base class to define and enforce an interface. ## Using an Abstract Base Class For example, say we want to use one of the abstract base classes from the `collections` module: ``` import collections class MySet(collections.Set): pass ``` If we try to use it, we get an `TypeError` because the class we created does not support the expected behavior of sets: ``` >>> MySet() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class MySet with abstract methods __contains__, __iter__, __len__ ``` So we are required to implement at *least* `__contains__`, `__iter__`, and `__len__`. Let's use this implementation example from the [documentation](https://docs.python.org/2/library/collections.html#collections-abstract-base-classes): ``` class ListBasedSet(collections.Set): """Alternate set implementation favoring space over speed and not requiring the set elements to be hashable. """ def __init__(self, iterable): self.elements = lst = [] for value in iterable: if value not in lst: lst.append(value) def __iter__(self): return iter(self.elements) def __contains__(self, value): return value in self.elements def __len__(self): return len(self.elements) s1 = ListBasedSet('abcdef') s2 = ListBasedSet('defghi') overlap = s1 & s2 ``` ## Implementation: Creating an Abstract Base Class We can create our own Abstract Base Class by setting the metaclass to `abc.ABCMeta` and using the `abc.abstractmethod` decorator on relevant methods. The metaclass will be add the decorated functions to the `__abstractmethods__` attribute, preventing instantiation until those are defined. ``` import abc ``` For example, "effable" is defined as something that can be expressed in words. Say we wanted to define an abstract base class that is effable, in Python 2: ``` class Effable(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def __str__(self): raise NotImplementedError('users must define __str__ to use this base class') ``` Or in Python 3, with the slight change in metaclass declaration: ``` class Effable(object, metaclass=abc.ABCMeta): @abc.abstractmethod def __str__(self): raise NotImplementedError('users must define __str__ to use this base class') ``` Now if we try to create an effable object without implementing the interface: ``` class MyEffable(Effable): pass ``` and attempt to instantiate it: ``` >>> MyEffable() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class MyEffable with abstract methods __str__ ``` We are told that we haven't finished the job. Now if we comply by providing the expected interface: ``` class MyEffable(Effable): def __str__(self): return 'expressable!' ``` we are then able to use the concrete version of the class derived from the abstract one: ``` >>> me = MyEffable() >>> print(me) expressable! ``` There are other things we could do with this, like register virtual subclasses that already implement these interfaces, but I think that is beyond the scope of this question. The other methods demonstrated here would have to adapt this method using the `abc` module to do so, however. ## Conclusion We have demonstrated that the creation of an Abstract Base Class defines interfaces for custom objects in Python.
Difference between abstract class and interface in Python
[ "", "python", "interface", "abstract-class", "" ]
I'm trying to implement a comet style, long polling connection using an XMLHttpResponse object. The idea is to maintain an open connection to a server which sends data when it is available (faking push). As soon as the XHR object completes, I need to spawn a new one to wait for any fresh data. Below is a snippet of code which outlines a solution that works but, as the comment says, only because of a timeout which I need to get rid of. ``` window.onload = function(){ XHR.init(); } XHR = { init: function() { this.xhr = new XMLHttpRequest(); this.xhr.open( "GET", "proxy.php?salt="+Math.round( Math.random()*10000 ), true ); this.xhr.onreadystatechange = this.process.bind( this ); this.xhr.send( null ); }, process: function() { if( this.xhr.readyState == 4 ) { // firebug console console.log( this.xhr.responseText ); // ** Attempting to create new XMLHttpRequest object to // replace the one that's just completed // doesn't work without the timeout setTimeout( function() { this.init() }.bind( this ), 1000 ); } } } Function.prototype.bind = function( obj ) { var method = this; return function() { return method.apply( obj, arguments ); } } // proxy.php - a dummy that keeps the XHR object waiting for a response <?php $rand = mt_rand( 1, 10 ); sleep( $rand ); echo date( 'H:i:s' ).' - '.$rand; ``` I think the problem might be that you can't delete an object (xhr) from it's own event handler (process) as is the case here. especially because the 'this' within the handler is bound to an object (XHR) which contains the object (xhr) I'm trying to delete. Kinda circular! Can anyone help? The above example is the closest I can get.
Just use jquery and do something like this: ``` function getData() { $.getJSON(someUrl, gotData); } // Whenever a query stops, start a new one. $(document).ajaxStop(getData, 0); // Start the first query. getData(); ``` My [slosh](http://github.com/dustin/slosh) examples do this (since it's pretty much a comet server).
What you're doing is effectively polling, why make it more complex than it needs to be, and just poll every few seconds? Or every second, how much time are you really saving and is it really that important, and you're going to be tying up an awful lot of sockets on the server end if you have a lot of users.
Implementing a self resetting XMLHttpRequest object
[ "", "javascript", "ajax", "xmlhttprequest", "" ]
I'm new to the Mac OS X, and I'm just about ready to throw my brand new [MacBook Pro](http://en.wikipedia.org/wiki/MacBook_Pro) out the window. Every tutorial on setting up a Django development environment on [Mac OS X Leopard](http://en.wikipedia.org/wiki/Mac_OS_X_Leopard) is insidiously wrong. They are all skipping over one step, or assuming you have setup something one way, or are just assuming that I know one thing that I must not. I'm very familiar with how to setup the environment on Ubuntu/Linux, and the only part I'm getting stuck on with [OS X](https://en.wikipedia.org/wiki/OS_X) is how to install MySQL, autostart it, and install the Python MySQL bindings. I think my mistake was using a hodgepodge of tools I don't fully understand; I used fink to install MySQL and its development libraries and then tried to build the Python-MySQL bindings from source (but they won't build.) UPDATE: I installed the binary MySQL package from <http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg>, and I got MySQL server running (can access with admin.) The MySQL version I got from port was rubbish, I could not get it to run at all. I modified the source for the Python-MySQL package as per the answer I chose, but I still got compilation errors that I listed in the comments. I was able to fix these by adding /usr/local/mysql/bin/ to my path in my "~/.profile" file. " PATH=/usr/local/mysql/bin:$PATH " Thanks for the help, I was very wary about editing the source code since this operation had been so easy on Ubuntu, but I'll be more willing to try that in the future. I'm really missing Ubuntu's "apt-get" command; it makes life very easy and simple sometimes. I already have an Ubuntu [VMware](http://en.wikipedia.org/wiki/VMware) image running on my Mac, so I can always use that as a fallback (plus it more closely matches my production machines so should be a good test environment for debugging production problems.)
Did the MySQL and MySQL-dev installations go smoothly? Can you run MySQL, connect to it and so on? Does `/usr/local/mysql/include` contain lots of header files? (I've got 46 header files there, for reference). If so, MySQL should be good to go. There are still a few manual steps required to compile MySQL-python, however. [This](http://www.keningle.com/?p=11) is a decent guide: I've included the salient steps below. --- 1. Download the [MySQL-python source](https://sourceforge.net/projects/mysql-python) (v1.2.2 at time of writing: all subsequent instructions are for this version) ``` $ tar xzf MySQL-python-1.2.2.tar.gz && cd MySQL-python-1.2.2 ``` 2. Edit `_mysql.c`: remove lines 37-39 and change lines 481-482. Here's the diff: ``` 37,39d36 < #ifndef uint < #define uint unsigned int < #endif 484,485c481,482 < uint port = MYSQL_PORT; < uint client_flag = 0; --- > unsigned int port = MYSQL_PORT; > unsigned int client_flag = 0; ``` 3. Symlink the libs to where MySQL-python expects them: ``` $ sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql ``` 4. In your MySQL-python-1.2.2 directory, rebuild your package: ``` $ sudo python setup.py build ``` **Note:** You will receive a warning, ignore it. 5. Install the package: ``` $ sudo python setup.py install ``` --- As for starting MySQL, there are instructions [here](http://dev.mysql.com/doc/refman/5.0/en/mac-os-x-installation.html) on starting it as a service. Personally, I just run ``` sudo mysqld_safe ``` manually, backgrounding it with `^Z` and `bg` once I've put in my password.
You can use the BSD-alike(?) <http://macports.org>, which provides gentoo-like build-it-yourself installations of a wide swath of software you'd expect to find in a Linux distro. Alternatively you could just run Ubuntu in a virtual machine as your test stage. It's honestly a simple `# port install <pkgname>`
How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X?
[ "", "python", "mysql", "django", "macos", "system-administration", "" ]
I'm adding some lazy initialization logic to a const method, which makes the method in fact not const. Is there a way for me to do this without having to remove the "const" from the public interface? ``` int MyClass::GetSomeInt() const { // lazy logic if (m_bFirstTime) { m_bFirstTime = false; Do something once } return some int... } ``` EDIT: Does the "mutable" keyword play a role here?
Make m\_bFirstTime mutable: ``` class MyClass { : : mutable bool m_bFirstTime; }; ``` ...but this is also very often an indication of a design flaw. So beware.
Actually, you said that you didn't want to change the header file. So your only option is to cast away the constness of the this pointer... ``` int MyClass::GetSomeInt() const { MyClass* that = const_cast<MyClass*>(this); // lazy logic if (that->m_bFirstTime) { that->m_bFirstTime = false; Do something once } return some int... } ``` If using mutable raises a red flag, this launches a red flag store in to orbit. Doing stuff like this is usually a really bad idea.
In C++, I want my interface, .h to say int GetSomeInt() const;.... but actually the method *DOES* update "this".
[ "", "c++", "constants", "" ]
I've got a MenuItem whos ItemsSource is databound to a simple list of strings, its showing correctly, but I'm struggling to see how I can handle click events for them! Here's a simple app that demonstrates it: ``` <Window x:Class="WPFDataBoundMenu.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <Menu> <MenuItem Header="File" Click="MenuItem_Click" /> <MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}" /> </Menu> </Grid> ``` ``` using System.Collections.Generic; using System.Windows; namespace WPFDataBoundMenu { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public List<string> MyMenuItems { get; set;} public Window1() { InitializeComponent(); MyMenuItems = new List<string> { "Item 1", "Item 2", "Item 3" }; DataContext = this; } private void MenuItem_Click(object sender, RoutedEventArgs e) { MessageBox.Show("how do i handle the other clicks?!"); } } } ``` Many thanks! Chris.
``` <MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}" Click="DataBoundMenuItem_Click" /> ``` Code behind.. ``` private void DataBoundMenuItem_Click(object sender, RoutedEventArgs e) { MenuItem obMenuItem = e.OriginalSource as MenuItem; MessageBox.Show( String.Format("{0} just said Hi!", obMenuItem.Header)); } ``` Events will bubble up to the common handler. You can then use the Header text or better the DataContext property to switch and act as needed
You could have each menu item execute the same command, thus handling the execution centrally. If you need to distinguish menu items beyond the actual object instance, you can bind the command parameter too: ``` <MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}"> <MenuItem.ItemContainerStyle> <Style TargetType="MenuItem"> <Setter Property="Command" Value="{x:Static local:MyCommands.MyCommand}"/> <Setter Property="CommandParameter" Value="{Binding SomeProperty}"/> </Style> </MenuItem.ItemContainerStyle> </MenuItem> ``` `SomeProperty` is assumed to be a property on each item in your `MyMenuItems` collection. Your command execution handler would therefore receive the value of `SomeProperty` for the particular menu item that is clicked.
How do I handle click events in a data bound menu in WPF
[ "", "c#", "wpf", "data-binding", "" ]
I'm using PHP to generate thumbnails. The problem is that I have a set width and height the thumbnails need to be and often times the images are stretched. What I'd like is the image to remain at the same proportions and just have black filler (or any color) either on the left & right for tall images or top & bottom for wide images. Here is the code I'm currently using: (dumbed down a bit for readability) ``` $temp_image_file = imagecreatefromjpeg("http://www.example.com/image.jpg"); list($width,$height) = getimagesize("http://www.example.com/image.jpg"); $image_file = imagecreatetruecolor(166,103); imagecopyresampled($image_file,$temp_image_file,0,0,0,0,166,103,$width,$height); imagejpeg($image_file,"thumbnails/thumbnail.jpg",50); imagedestroy($temp_image_file); imagedestroy($image_file); ```
You'll need to calculate the new width & height to keep the image proportionat. Check out example 2 on this page: <https://www.php.net/imagecopyresampled>
Okay got it working, here's what I ended up doing: ``` $filename = "http://www.example.com/image.jpg"; list($width,$height) = getimagesize($filename); $width_ratio = 166 / $width; if ($height * $width_ratio <= 103) { $adjusted_width = 166; $adjusted_height = $height * $width_ratio; } else { $height_ratio = 103 / $height; $adjusted_width = $width * $height_ratio; $adjusted_height = 103; } $image_p = imagecreatetruecolor(166,103); $image = imagecreatefromjpeg($filename); imagecopyresampled($image_p,$image,ceil((166 - $adjusted_width) / 2),ceil((103 - $adjusted_height) / 2),0,0,ceil($adjusted_width),ceil($adjusted_height),$width,$height); imagejpeg($image_p,"thumbnails/thumbnail.jpg",50); ```
Having issues with GD thumbnail generator
[ "", "php", "gd", "" ]
If I want to loop over a Dictionary(Key, Value)... why cant I add a new key-value pair in the loop? ``` Dictionary<string, string> persons = new Dictionary<string, string>(); persons.Add("roger", "12"); persons.Add("mary", "13"); foreach (KeyValuePair<string,string> person in persons) { Console.WriteLine("Name: " + person.Key + ", Age: " + person.Value); persons.Add("Xico", "22"); } ```
If you want to do this you should get a copy of the Dictionary Object (can be done in many ways) then enumerate it, add what you want to the original. Simply you can't add new items while enumerating an Dictionary.
It's because of the way the enumerator is constructed. From MSDN [Dictionary.Enumerator](http://msdn.microsoft.com/en-us/library/k3z2hhax.aspx): > An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined. It's easy enough to get around this, though. Simply make a copy of the Dictionary (or it's keys) and iterate through it, adding/removing/etc. from the original Dictionary as needed.
Why can't I .add a Dictionary(Key, Value) in a foreach?
[ "", "c#", "dictionary", "foreach", "" ]
How do I check to see if a particular value has already been assigned to Smarty and if not assign a (default) value? Answer: ``` if ($this->cismarty->get_template_vars('test') === null) { $this->cismarty->assign('test', 'Default value'); } ```
**Smarty 2** ``` if ($smarty->get_template_vars('foo') === null) { $smarty->assign('foo', 'some value'); } ``` **Smarty 3** ``` if ($smarty->getTemplateVars('foo') === null) { $smarty->assign('foo', 'some value'); } ``` Note that for **Smarty 3**, you will have to use `$smarty->getTemplateVars` instead.
`get_template_vars()` will return null if you haven't set a variable, so you can do ``` if ($smarty->get_template_vars('test') === null) { echo "'test' is not assigned or is null"; } ``` However that check will fail if you have a variable assigned but set as null, in which case you could do ``` $tmp = $smarty->get_template_vars(); if (!array_key_exists('test', $tmp)) { echo "'test' is not assigned"; } ```
How do I check to see if a Smarty variable is already assigned?
[ "", "php", "smarty", "template-engine", "" ]
I was browsing the SGI STL documentation and ran into [`project1st<Arg1, Arg2>`](http://www.sgi.com/tech/stl/project1st.html). I understand its definition, but I am having a hard time imagining a practical usage. Have you ever used project1st or can you imagine a scenario?
My guess is that if you were using the strategy pattern and had a situation where you needed to pass an identity object, this would be a good choice. For example, there might be a case where an algorithm takes several such objects, and perhaps it is possible that you want one of them to do nothing under some situation.
A variant of project1st (taking a `std::pair`, and returning `.first`) is quite useful. You can use it in combination with `std::transform` to copy the keys from a `std::map<K,V>` to a `std::vector<K>`. Similarly, a variant of `project2nd` can be used to copy the values from a map to a `vector<V>`. As it happens, none of the standard algorithms really benefits from project1st. The closest is partial\_sum(project1st), which would set all output elements to the first input element. It mainly exists because the STL is heavily founded in mathematical set theory, and there operations like project1st are basic building blocks.
What is the usefulness of project1st<Arg1, Arg2> in the STL?
[ "", "c++", "stl", "functional-programming", "" ]
I'm aware that Python 3 fixes a lot of UTF issues, I am not however able to use Python 3, I am using 2.5.1 I'm trying to regex a document but the document has UTF hyphens in it – rather than -. Python can't match these and if I put them in the regex it throws a wobbly. How can I force Python to use a UTF string or in some way match a character such as that? Thanks for your help
After a quick test and visit to [PEP 0264: Defining Python Source Code Encodings](http://www.python.org/dev/peps/pep-0263/), I see you may need to tell Python the whole file is UTF-8 encoded by adding adding a comment like this to the first line. ``` # encoding: utf-8 ``` Here's the test file I created and ran on Python 2.5.1 / OS X 10.5.6 ``` # encoding: utf-8 import re x = re.compile("–") print x.search("xxx–x").start() ```
You have to escape the character in question (–) and put a u in front of the string literal to make it a unicode string. So, for example, this: ``` re.compile("–") ``` becomes this: ``` re.compile(u"\u2013") ```
UTF in Python Regex
[ "", "python", "regex", "" ]
I am building a CMS and the naming convention for classes has been debated between the other developer involved and myself. The problem arises specifically with "Page", as it is a public class available in a typical library. A natural response would be to call it MVCMSPage (where MVCMS is the to-be name of the cms) or to rely on referencing the class through the dll (can't think of the term atm..) but both seem to have a hint of codesmell to them. What would you advise? Thanks
I'd go with something other than '`Page`'. The '`Page`' class that is built into .NET is a very generic class that is commonly known as part of ASP.NET. You could easily confuse other developers (or even yourself, a few months down the road if you don't look at it for a while). I usually go with a naming convention such as: ``` ApplicationName + "Page" ``` I also like to follow the MS .NET naming guidelines of only capitalizing the first letter of an acronym longer than 2 characters. Since '`MVCMS`' can be confused for the 'MVC' architecture style if read incorrectly, I wouldn't use '`MvcmsPage`' or '`MVCmsPage`', I'd call it something like this: ``` MvCmsPage ``` This is descriptive and fairly easy to read and understand. Of course it's really up to you. Mainly it's a matter of preference. Just don't use '`Page`' as it will make some developers angry (such as myself).
I think the term you were looking for is `namespace`. I don't think I would rely on namespace differentiation for such a fundamental class in the System.Web space. If you were writing a console-based notification mechanism then it might be ok, but since you're working in the web arena, I'd avoid it. My vote would be to use the namespace as the main differentiator and name it something simple, like `ContentPage` so you would have something like `MvcCms.Web.ContentPage` as the full name of the class. If you do it this way you can import both your namespace and `System.Web` and still be able to differentiate the classes AND you have a short name that makes sense and isn't cumbersome to use or reference (when speaking about it).
Quick question about a naming convention for a C# CMS
[ "", "c#", "content-management-system", "naming-conventions", "" ]
If I had a dictionary `dict` and I wanted to check for `dict['key']` I could either do so in a `try` block (bleh!) or use the `get()` method, with `False` as a default value. I'd like to do the same thing for `object.attribute`. That is, I already have object to return `False` if it hasn't been set, but then that gives me errors like > AttributeError: 'bool' object has no attribute 'attribute'
A more direct analogue to `dict.get(key, default)` than `hasattr` is `getattr`. ``` val = getattr(obj, 'attr_to_check', default_value) ``` (Where `default_value` is optional, raising an exception on no attribute if not found.) For your example, you would pass `False`.
Do you mean `hasattr()` perhaps? ``` hasattr(object, "attribute name") #Returns True or False ``` [Python.org doc - Built in functions - hasattr()](http://docs.python.org/library/functions.html#hasattr) You can also do this, which is a bit more cluttered and doesn't work for methods. ``` "attribute" in obj.__dict__ ```
A get() like method for checking for Python attributes
[ "", "python", "attributes", "" ]
At work today we were trying to come up with any reason you would use [strspn](http://www.php.net/strspn). I searched google code to see if it's ever been implemented in a useful way and came up blank. I just can't imagine a situation in which I would really need to know the length of the first segment of a string that contains only characters from another string. Any ideas?
Although you link to the PHP manual, the `strspn()` function comes from C libraries, along with `strlen()`, `strcpy()`, `strcmp()`, etc. `strspn()` is a convenient alternative to picking through a string character by character, testing if the characters match one of a set of values. It's useful when writing tokenizers. The alternative to `strspn()` would be lots of repetitive and error-prone code like the following: ``` for (p = stringbuf; *p; p++) { if (*p == 'a' || *p == 'b' || *p = 'c' ... || *p == 'z') { /* still parsing current token */ } } ``` Can you spot the error? :-) Of course in a language with builtin support for regular expression matching, `strspn()` makes little sense. But when writing a rudimentary parser for a DSL in C, it's pretty nifty.
It's based on the the ANSI C function `strspn()`. It can be useful in low-level C parsing code, where there is no high-level string class. It's considerably less useful in PHP, which has lots of useful string parsing functions.
What's the point of strspn?
[ "", "php", "function", "built-in", "" ]
How do I split a list of arbitrary length into equal sized chunks? --- See also: [How to iterate over a list in chunks](https://stackoverflow.com/q/434287). To chunk strings, see [Split string every nth character?](https://stackoverflow.com/questions/9475241).
Here's a generator that yields evenly-sized chunks: ``` def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n] ``` ``` import pprint pprint.pprint(list(chunks(range(10, 75), 10))) [[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], [50, 51, 52, 53, 54, 55, 56, 57, 58, 59], [60, 61, 62, 63, 64, 65, 66, 67, 68, 69], [70, 71, 72, 73, 74]] ``` For Python 2, using `xrange` instead of `range`: ``` def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in xrange(0, len(lst), n): yield lst[i:i + n] ``` --- Below is a list comprehension one-liner. The method above is preferable, though, since using named functions makes code easier to understand. For Python 3: ``` [lst[i:i + n] for i in range(0, len(lst), n)] ``` For Python 2: ``` [lst[i:i + n] for i in xrange(0, len(lst), n)] ```
Something super simple: ``` def chunks(xs, n): n = max(1, n) return (xs[i:i+n] for i in range(0, len(xs), n)) ``` For Python 2, use `xrange()` instead of `range()`.
How do I split a list into equally-sized chunks?
[ "", "python", "list", "split", "chunks", "" ]
Suppose I have this code: ``` var myArray = new Object(); myArray["firstname"] = "Bob"; myArray["lastname"] = "Smith"; myArray["age"] = 25; ``` Now if I wanted to remove "lastname"?....is there some equivalent of `myArray["lastname"].remove()`? (I need the element gone because the number of elements is important and I want to keep things clean.)
Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values. To remove a property from an object in JavaScript you use the [`delete`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete) operator: ``` const o = { lastName: 'foo' } o.hasOwnProperty('lastName') // true delete o['lastName'] o.hasOwnProperty('lastName') // false ``` Note that when `delete` is applied to an index property of an [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), you will create a [sparsely populated array](https://2ality.com/2012/06/dense-arrays.html) (ie. an array with a missing index). When working with instances of `Array`, if you do not want to create a sparsely populated array - and you usually don't - then you should use [`Array#splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) or [`Array#pop`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop). Note that the `delete` operator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an object `o`, then `o` will subsequently be garbage collected in the normal way. Using the `delete` operator can affect JavaScript engines' ability to [optimise](http://www.html5rocks.com/en/tutorials/speed/v8/) [code](http://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javascript/).
All objects in JavaScript are implemented as hashtables/associative arrays. So, the following are the equivalent: ``` alert(myObj["SomeProperty"]); alert(myObj.SomeProperty); ``` And, as already indicated, you "remove" a property from an object via the `delete` keyword, which you can use in two ways: ``` delete myObj["SomeProperty"]; delete myObj.SomeProperty; ``` Hope the extra info helps...
How do I remove objects from a JavaScript associative array?
[ "", "javascript", "arrays", "associative-array", "associative", "" ]
Can any one tell the bit size of **boolean** in Java?
It's virtual machine dependent.
It depends on the virtual machine, but it's easy to adapt the code from a [similar question asking about bytes in Java](https://stackoverflow.com/questions/229886): ``` class LotsOfBooleans { boolean a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af; boolean b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf; boolean c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf; boolean d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df; boolean e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef; } class LotsOfInts { int a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af; int b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf; int c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf; int d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df; int e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef; } public class Test { private static final int SIZE = 1000000; public static void main(String[] args) throws Exception { LotsOfBooleans[] first = new LotsOfBooleans[SIZE]; LotsOfInts[] second = new LotsOfInts[SIZE]; System.gc(); long startMem = getMemory(); for (int i=0; i < SIZE; i++) { first[i] = new LotsOfBooleans(); } System.gc(); long endMem = getMemory(); System.out.println ("Size for LotsOfBooleans: " + (endMem-startMem)); System.out.println ("Average size: " + ((endMem-startMem) / ((double)SIZE))); System.gc(); startMem = getMemory(); for (int i=0; i < SIZE; i++) { second[i] = new LotsOfInts(); } System.gc(); endMem = getMemory(); System.out.println ("Size for LotsOfInts: " + (endMem-startMem)); System.out.println ("Average size: " + ((endMem-startMem) / ((double)SIZE))); // Make sure nothing gets collected long total = 0; for (int i=0; i < SIZE; i++) { total += (first[i].a0 ? 1 : 0) + second[i].a0; } System.out.println(total); } private static long getMemory() { Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } } ``` To reiterate, this is VM-dependent, but on my Windows laptop running Sun's JDK build 1.6.0\_11 I got the following results: ``` Size for LotsOfBooleans: 87978576 Average size: 87.978576 Size for LotsOfInts: 328000000 Average size: 328.0 ``` That suggests that booleans can basically be packed into a byte each by Sun's JVM.
What is the size of a boolean variable in Java?
[ "", "java", "boolean", "" ]
I'm using Python to **infinitely** iterate over a list, repeating each element in the list a number of times. For example given the list: ``` l = [1, 2, 3, 4] ``` I would like to output each element two times and then repeat the cycle: ``` 1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ... ``` I've got an idea of where to start: ``` def cycle(iterable): if not hasattr(cycle, 'state'): cycle.state = itertools.cycle(iterable) return cycle.next() >>> l = [1, 2, 3, 4] >>> cycle(l) 1 >>> cycle(l) 2 >>> cycle(l) 3 >>> cycle(l) 4 >>> cycle(l) 1 ``` But how would I repeat each element? **Edit** To clarify this should iterate infinitely. Also I've used repeating the element twice as the shortest example - **I would really like to repeat each element n times**. **Update** Will your solution lead me to what I was looking for: ``` >>> import itertools >>> def ncycle(iterable, n): ... for item in itertools.cycle(iterable): ... for i in range(n): ... yield item >>> a = ncycle([1,2], 2) >>> a.next() 1 >>> a.next() 1 >>> a.next() 2 >>> a.next() 2 >>> a.next() 1 >>> a.next() 1 >>> a.next() 2 >>> a.next() 2 ``` Thanks for the quick answers!
How about this: ``` import itertools def bicycle(iterable, repeat=1): for item in itertools.cycle(iterable): for _ in xrange(repeat): yield item c = bicycle([1,2,3,4], 2) print [c.next() for _ in xrange(10)] ``` EDIT: incorporated [bishanty's](https://stackoverflow.com/users/37522/bishanty) repeat count parameter and [Adam Rosenfield's list comprehension](https://stackoverflow.com/questions/383565/how-to-iterate-over-a-list-repeating-each-element-in-python#383574).
You could do it with a generator pretty easily: ``` def cycle(iterable): while True: for item in iterable: yield item yield item x=[1,2,3] c=cycle(x) print [c.next() for i in range(10)] // prints out [1,1,2,2,3,3,1,1,2,2] ```
How to iterate over a list repeating each element in Python
[ "", "python", "iterator", "" ]
In Java, arrays don't override `toString()`, so if you try to print one directly, you get the `className` + '@' + the hex of the [`hashCode`](https://en.wikipedia.org/wiki/Java_hashCode()) of the array, as defined by `Object.toString()`: ``` int[] intArray = new int[] {1, 2, 3, 4, 5}; System.out.println(intArray); // Prints something like '[I@3343c8b3' ``` But usually, we'd actually want something more like `[1, 2, 3, 4, 5]`. What's the simplest way of doing that? Here are some example inputs and outputs: ``` // Array of primitives: int[] intArray = new int[] {1, 2, 3, 4, 5}; // Output: [1, 2, 3, 4, 5] // Array of object references: String[] strArray = new String[] {"John", "Mary", "Bob"}; // Output: [John, Mary, Bob] ```
Since Java 5 you can use [`Arrays.toString(arr)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#toString(int%5B%5D)) or [`Arrays.deepToString(arr)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#deepToString(java.lang.Object%5B%5D)) for arrays within arrays. Note that the `Object[]` version calls `.toString()` on each object in the array. The output is even decorated in the exact way you're asking. Examples: * ### Simple Array: ``` String[] array = new String[] {"John", "Mary", "Bob"}; System.out.println(Arrays.toString(array)); ``` Output: ``` [John, Mary, Bob] ``` * ### Nested Array: ``` String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}}; // Gives undesired output: System.out.println(Arrays.toString(deepArray)); // Gives the desired output: System.out.println(Arrays.deepToString(deepArray)); ``` Output: ``` [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922] [[John, Mary], [Alice, Bob]] ``` * ### `double` Array: ``` double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 }; System.out.println(Arrays.toString(doubleArray)); ``` Output: ``` [7.0, 9.0, 5.0, 1.0, 3.0 ] ``` * ### `int` Array: ``` int[] intArray = { 7, 9, 5, 1, 3 }; System.out.println(Arrays.toString(intArray)); ``` Output: ``` [7, 9, 5, 1, 3 ] ```
Always check the standard libraries first. ``` import java.util.Arrays; ``` Then try: ``` System.out.println(Arrays.toString(array)); ``` or if your array contains other arrays as elements: ``` System.out.println(Arrays.deepToString(array)); ```
What's the simplest way to print a Java array?
[ "", "java", "arrays", "printing", "tostring", "" ]
I have two arrays in PHP. The first array ($author\_array) is comprised of user\_ids in a particular order, like so: (8, 1, 6) The second array ($user\_results) is comprised of an array of objects like so: ``` Array ( [0] => stdClass Object ( [ID] => 1 [user_login] => user1 ) [1] => stdClass Object ( [ID] => 6 [user_login] => user6 ) [2] => stdClass Object ( [ID] => 8 [user_login] => user8 ) ) ``` I'd like to "sort" the second array so it's in this order, which matches the order of the values in the first array of (8, 1, 6). So it'd look like this: ``` Array ( [0] => stdClass Object ( [ID] => 8 [user_login] => user8 ) [1] => stdClass Object ( [ID] => 1 [user_login] => user1 ) [2] => stdClass Object ( [ID] => 6 [user_login] => user6 ) ) ``` I'm weak on data structures. How could I do this? :-) Thanks in advance for your help! -Bob
Use [usort](http://php.net/uksort) and provide a custom comparison function which uses the position of the key in your "ordering" array to determine the sort order, e.g. something like: ``` function cmp($a, $b) { global $author_array; $pos1=array_search ($a->ID, $author_array); $pos2=array_search ($b->ID, $author_array); if ($pos1==$pos2) return 0; else return ($pos1 < $pos2 ? -1 : 1); } usort($user_results, "cmp"); ```
I'm not sure whether this will be significantly slower than other examples, but it seems simpler. It may be that you could build the $user\_results array as an associative one to start with, using ID as the key, then you can easily do lookups. ``` $hash = array(); $result = array(); foreach ($user_results as $obj) { $hash[$obj->ID] = $obj; } foreach ($author_array as $id) { $result[] = $hash[$id]; } ```
Sorting an Array of Objects in PHP In a Specific Order
[ "", "php", "arrays", "object", "" ]
I have a client with a LAMP website serving mostly video. He is currently on one server with all components. He is having some scaling problems. What are some of the techniques that can be used to help. I used separating out the DB to another server with a GB Ethernet between it and the webserver. Maybe adding more web servers with some load balancing and additional MySQL servers with replication? Would like some medium, large, super large examples on how to scale if possible. The video is actually coming as jpg images. Similiar to this website: <http://www.webcams.travel/webcam/1170170095> And to add some details. I figure the max visitors per hour would be 1000, and I think would be lucky to have that. Maybe closer to 1000 a day.
The advice about CloudFront and MemCache etc. is all good, assuming those address the root of your performance issues. On the database side: Profile, profile, profile. Moving the DB to a separate server was (probably) a good step, but if you haven't profiled the queries being run on this DB instance, you don't know what you need to improve. Start by doing an [EXPLAIN](http://dev.mysql.com/doc/refman/5.0/en/explain.html "MySQL EXPLAIN Documentation") on the most common queries, and check whether you're doing unnecessary sequential scans on large or growing tables. Index as necessary. Are any of the queries passing back columns that aren't used? Are you, as other commenters were worried, serving your graphic/video content from the database? Files should be kept in the filesystem, and served from there. Are all your tables MyISAM? Frequently-updated tables may show performance improvement by moving them to [InnoDB](http://dev.mysql.com/doc/refman/5.1/en/innodb.html "InnoDB Documentation"), where they can benefit from row-level locking (as opposed to MyISAM's table-level locking). These are just simple, general recommendations - without more specifics on exactly *what* is slow, it's tough to offer anything deeper.
First off, I agree that you must know what the bottleneck is before attempting to scale. Here some run of the mill suggestions to get you started: 1. Get video out of the database. I don't see how this would make sense in any situation. 2. Add one more server to only server the video content and leave the HTML/application to the original one. Not only does this reduce load, but it creates a performance improvement on the client side by overcoming any [HTTP connection limits](http://www.google.com/search?q=http+connection+limit). 3. Cache - This may mean [Memcahce](http://www.danga.com/memcached/) or just pre-building HTML output instead of dynamically processing it for every request. 4. If you are fortunate enough to reach 'super large' you might think about a [CDN](http://en.wikipedia.org/wiki/Content_Delivery_Network). I'm sure you will encounter many other hurdles before then though. Best of luck.
Scaling LAMP
[ "", "php", "mysql", "lamp", "" ]
I'm going to start maintaining an Eclipse RCP application for my current employer soon. What are your experiences with this platform? What are the pros, what are the cons, what are the caveats that I should be aware of? Also, what reading materials (books, tutorials) can you recommend? Most of the tutorials I found on the web are outdated, are there any good ones that are more up to date? I started reading [Eclipse Rich Client Platform: Designing, Coding, and Packaging Java(TM) Applications](https://rads.stackoverflow.com/amzn/click/com/0321334612) but since it's also out of date, I got stuck pretty much in the beginning, and the book actually seems to be more like a collection of recipes to do something than a genuine book on the subject (it doesn't explain the core concepts very well). So, what can you tell me about the good sides and bad sides of developing an app with Eclipse RCP, and what are your reading recommendations?
* [Eclipse Rich Client Platform (RCP) with Eclipse Ganymede (3.4) - Tutorial](http://www.vogella.de/articles/RichClientPlatform/article.html) * [JFace examples](http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/CatalogSWT-JFace-Eclipse.htm) * [Make your Eclipse applications richer with view linking](http://www-128.ibm.com/developerworks/opensource/library/os-ecllink/) * [RCP FAQ](http://wiki.eclipse.org/RCP_FAQ) * [Java Developer's Guide To Eclipse](https://rads.stackoverflow.com/amzn/click/com/0321305027) Eclipse RCP isn't as easy as people put it is. It's essentially writing an Eclipse plug-in and you have to learn a whole new JFace/Eclipse way of doing things. [![The Java Developer's Guide to Eclipse](https://i.stack.imgur.com/3LCJW.jpg)](https://i.stack.imgur.com/3LCJW.jpg)
There are many good online references included on the Eclipse Resources page, and on the Eclipse Wiki. There is also quite a bit of good material on Eclipse Live <http://live.eclipse.org/> in the form of tutorials and other presentations, some of which come from the eclipsecon conferences. I recommend starting with the most recent entries for each of these resources since RCP is much easier now than it was several years ago. Some things to try: 1) Use the Platform Command Framework rather than the older Actions framework that was the mainstay of the RCP example programs. 2) Use the databinding farmework to simplify UI wiring. 3) If you're doing a forms-based app, check out the UI Forms API, which provides a good way to control the style of the forms (and adds niceties like collapsible sections). 4) Look at EMF for building your data model - databinding now supports EMF directly.
Starting working with Eclipse RCP
[ "", "java", "eclipse", "eclipse-plugin", "eclipse-rcp", "" ]
While considering the JS framework for my next project, I can see the scale clearly tipping towards jQuery, however, Prototype is getting good reviews, too. The issue I am thinking of is how to **downscale these to have only the functionality I REALLY need.** The latest jQuery seems to be 55k compressed, for instance, and I clearly need only the very basic functionality needed mostly or cross-browser compatibility. The alternative of coding just what I need by hand sounds quite a pain in the butt. Has anyone come across some "**jQuery downscaler**" or "Prototype downscaler"? Stuff like Dlite does not quite cut it since I need the cross-browser AJAX with timeouts, and the cross-browser cookie handling, but maybe there is some other lightweight solution? ASP-related bundles won't help since I am doing a PHP-based solution. Any tips on that will be much appreciated.
Check these Frameworks out: * [Midori](http://www.midorijs.com/) (*45KB uncompressed*) * [SimpleJS](http://simplejs.bleebot.com/) (*Core File: 4KB)* * [DOMAssistant](http://www.domassistant.com/) (*7KB gzipped)* If you want a complete but light weight solution, I'd suggest you go with *Midori* or *DOMAssistant*. Finally, here is a link that will show you differences between the frameworks: <http://en.wikipedia.org/wiki/Comparison_of_JavaScript_frameworks> **[Edit]** [This post](https://stackoverflow.com/questions/74048/what-is-the-best-lightweight-javascript-framework) may also help you with your research.
jQuery is about 10k compressed and minified with YUI compressor: <http://www.julienlecomte.net/blog/2007/08/13/> That is *incredibly* tiny for the amount of functionality you get in jQuery.
Downscaled versions of jQuery or Prototype - JS framework selection
[ "", "javascript", "jquery", "ajax", "prototypejs", "javascript-framework", "" ]
I am using XML minidom (xml.dom.minidom) in Python, but any error in the XML will kill the parser. Is it possible to ignore them, like a browser for example? I am trying to write a browser in Python, but it just throws an exception if the tags aren't fully compatible.
There is a library called [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/), I think it's what you're looking for. As you're trying to parse a invalid XML, the normal XML parser won't work. BeautifulSoup is more fail-tolerant, it can still extract information from invalid XML. > Beautiful Soup is a Python HTML/XML > parser designed for quick turnaround > projects like screen-scraping. Three > features make it powerful: > > 1. Beautiful Soup won't choke if you give it bad markup. It yields a > parse tree that makes approximately as > much sense as your original document. > This is usually good enough to collect > the data you need and run away. > 2. Beautiful Soup provides a few simple methods and Pythonic idioms for > navigating, searching, and modifying a > parse tree: a toolkit for dissecting a > document and extracting what you need. > You don't have to create a custom > parser for each application. > 3. Beautiful Soup automatically converts incoming documents to Unicode > and outgoing documents to UTF-8. You > don't have to think about encodings, > unless the document doesn't specify an > encoding and Beautiful Soup can't > autodetect one. Then you just have to > specify the original encoding. > > Beautiful Soup parses anything you > give it, and does the tree traversal > stuff for you. You can tell it "Find > all the links", or "Find all the links > of class externalLink", or "Find all > the links whose urls match "foo.com", > or "Find the table heading that's got > bold text, then give me that text."
It should be noted that while HTML looks like XML it is not XML. XHTML is an XML form of HTML.
Ignoring XML errors in Python
[ "", "python", "xml", "minidom", "" ]
How do I get started doing unit testing in C++ ? I have used Junit when coding in Java and found it very useful. Is there something similar in C++ ? What do you recommend ?
Here are similar questions that you may want to look at: * [Unit testing for C++ code - Tools and methodology](https://stackoverflow.com/questions/91384/unit-testing-for-c-code-tools-and-methodology) * [C++ unit testing framework](https://stackoverflow.com/questions/87794/c-unit-testing-framework) I recommend you check out [Google's unit testing framework](http://code.google.com/p/googletest/) in addition to CppUnit.
I recently wrote a 5-part series of blog posts covering unit testing in C++ with boost. It gives step by step instructions for how to do this in Visual Studio. * [Part 1](http://legalizeadulthood.wordpress.com/2009/07/04/c-unit-tests-with-boost-test-part-1/): how to start making unit tests in C++ with Boost.Test. * [Part 2](http://legalizeadulthood.wordpress.com/2009/07/05/c-unit-tests-with-boost-test-part-2/): the assertion framework provided by Boost.Test in the context of a simple programming exercise that demonstrates test-driven development. * [Part 3](http://legalizeadulthood.wordpress.com/2009/07/05/c-unit-tests-with-boost-test-part-3/): continuing with test-driven development to complete the functionality of the PrimeFactors::Generate method. * [Part 4](http://legalizeadulthood.wordpress.com/2009/07/05/c-unit-tests-with-boost-test-part-4/): test-driven UI development. * [Part 5](http://legalizeadulthood.wordpress.com/2009/07/05/c-unit-tests-with-boost-test-part-5/): the facilities in Boost.Test for sharing common setup and teardown actions between tests and organizing tests into suites.
Unit testing in C++
[ "", "c++", "unit-testing", "" ]
I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out. Specifically, I *want to use*: * The models and database abstraction * The [caching API](http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api), although I want to avoid database lookups by caching, not HTML generation, and since the caching framework in Django is intended for the latter, I'm not sure yet whether that's really appropriate. I would *not use*: * Templating * urlconfigs Or, more exactly, I'm neither using HTTP nor HTML. So basically, I have a different input / output chain than usual. Can this work? My personal killer feature in Django is the Object / database mapping that I can do with the models, so if there's another technology (doesn't have to be Python, I'm in the design phase and I'm pretty agnostic about languages and platforms) that gives me the same abilities, that would be great, too.
I myself use Django for its object/db mapping without using its urlconfigs. Simply create a file called `djangosettings.py` and insert the necessary configuration, for example: ``` DATABASE_ENGINE = 'oracle' DATABASE_HOST = 'localhost' DATABASE_NAME = 'ORCL' DATABASE_USER = 'scott' DATABASE_PASSWORD = 'tiger' ``` Then in your regular Python code, do ``` import os os.environ["DJANGO_SETTINGS_MODULE"] = "djangosettings" ``` before you import any Django modules. This will let you use Django's object/db mappings without actually having a Django project, so you can use it for standalone scripts or other web applications or whatever you want. As for caching, if you don't want to use Django then you should probably decide what you are using and go from there. I recommend using CherryPy, which doesn't use Django-style regular expression URL mapping, but instead automatically maps URLs to functions based on the function names. There's an example right at the top of the CherryPy home page: <http://cherrypy.org/> CherryPy has its own caching system, so you can accomplish exactly the same thing as what Django does but without needing to use Django's urlconfig system.
Django, being a web framework, is extremely efficient at creating websites. However, it's also equally well-suited to tackling problems off the web. This is the *loose coupling* that the project prides itself on. Nothing stops you from installing a complete version of Django, and just using what you need. As a rule, very few components of Django make broad assumptions about their usage. Specifically: * Django models don't know anything about HTML or HTTP. * Templates don't know anything about HTML or HTTP. * The cache system can be used to [store *anything that can be pickled*](http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api). One of the main things you'll face when trying to use Django without a web server is setting up the environment properly. The ORM and cache system still need to be configured in settings.py. There are docs on [using django without a settings module](http://docs.djangoproject.com/en/dev/topics/settings/#using-settings-without-setting-django-settings-module) that you may find useful.
Use only some parts of Django?
[ "", "python", "django", "" ]
Given a java.util.Date object how do I go about finding what Quarter it's in? Assuming Q1 = Jan Feb Mar, Q2 = Apr, May, Jun, etc.
Since Java 8, the quarter is accessible as a field using classes in the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) package. ``` import java.time.LocalDate; import java.time.temporal.IsoFields; LocalDate myLocal = LocalDate.now(); int quarter = myLocal.get(IsoFields.QUARTER_OF_YEAR); ``` --- In older versions of Java, you could use: ``` import java.util.Date; Date myDate = new Date(); int quarter = (myDate.getMonth() / 3) + 1; ``` Be warned, though that [getMonth](https://docs.oracle.com/javase/7/docs/api/java/util/Date.html#getMonth()) was deprecated early on: > As of JDK version 1.1, replaced by Calendar.get(Calendar.MONTH). Instead you could use a `Calendar` object like this: ``` import java.util.Calendar; import java.util.GregorianCalendar; Calendar myCal = new GregorianCalendar(); int quarter = (myCal.get(Calendar.MONTH) / 3) + 1; ```
In Java 8 and later, the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes have a more simple version of it. Use [`LocalDate`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) and [`IsoFields`](https://docs.oracle.com/javase/8/docs/api/java/time/temporal/IsoFields.html) ``` LocalDate.now().get(IsoFields.QUARTER_OF_YEAR) ```
How do I discover the Quarter of a given Date?
[ "", "java", "calendar", "" ]
Is there a difference between `Cursor.Current` and `this.Cursor` (where `this` is a WinForm) in .Net? I've always used `this.Cursor` and have had very good luck with it but I've recently started using CodeRush and just embedded some code in a "Wait Cursor" block and CodeRush used the `Cursor.Current` property. I've seen on the Internet and at work where other programmers have had some problems with the `Cursor.Current` property. It just got me to wondering if there is a difference in the two. Thanks in advance. I did a little test. I have two winforms. I click a button on form1, set the `Cursor.Current` property to `Cursors.WaitCursor` and then show form2. The cursor doesn't change on either form. It remains `Cursors.Default` (pointer) cursor. If I set `this.Cursor` to `Cursors.WaitCursor` in the button click event on form1 and show form2, the wait cursor only shows on form1 and the default cursor is on form2 which is expected. So, I still don't know what `Cursor.Current` does.
Windows sends the window that contains the mouse cursor the WM\_SETCURSOR message, giving it an opportunity to change the cursor shape. A control like TextBox takes advantage of that, changing the cursor into a I-bar. The Control.Cursor property determines what shape will be used. The Cursor.Current property changes the shape directly, without waiting for a WM\_SETCURSOR response. In most cases, that shape is unlikely to survive for long. As soon as the user moves the mouse, WM\_SETCURSOR changes it back to Control.Cursor. The UseWaitCursor property was added in .NET 2.0 to make it easier to display an hourglass. Unfortunately, it doesn't work very well. It requires a WM\_SETCURSOR message to change the shape and that won't happen when you set the property to true and then do something that takes a while. Try this code for example: ``` private void button1_Click(object sender, EventArgs e) { this.UseWaitCursor = true; System.Threading.Thread.Sleep(3000); this.UseWaitCursor = false; } ``` The cursor never changes. To whack that into shape, you'll need to use Cursor.Current as well. Here is a little helper class to make it easy: ``` using System; using System.Windows.Forms; public class HourGlass : IDisposable { public HourGlass() { Enabled = true; } public void Dispose() { Enabled = false; } public static bool Enabled { get { return Application.UseWaitCursor; } set { if (value == Application.UseWaitCursor) return; Application.UseWaitCursor = value; Form f = Form.ActiveForm; if (f != null && f.Handle != IntPtr.Zero) // Send WM_SETCURSOR SendMessage(f.Handle, 0x20, f.Handle, (IntPtr)1); } } [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp); } ``` And use it like this: ``` private void button1_Click(object sender, EventArgs e) { using (new HourGlass()) { System.Threading.Thread.Sleep(3000); } } ```
I believe that Cursor.Current is the mouse cursor currently being used (regardless of where it is on the screen), while this.Cursor is the cursor it will be set to, when the mouse passes over your window.
Cursor.Current vs. this.Cursor
[ "", "c#", ".net", "winforms", "mouse-cursor", "" ]
What are the C++ coding and file organization guidelines you suggest for people who have to deal with lots of interdependent classes spread over several source and header files? I have this situation in my project and solving class definition related errors crossing over several header files has become quite a headache.
Some general guidelines: * Pair up your interfaces with implementations. If you have `foo.cxx`, everything defined in there had better be declared in `foo.h`. * Ensure that every header file #includes all other necessary headers or forward-declarations necessary for independent compilation. * Resist the temptation to create an "everything" header. They're always trouble down the road. * Put a set of related (and interdependent) functionality into a single file. Java and other environments encourage one-class-per-file. With C++, you often want one *set of* classes per file. It depends on the structure of your code. * Prefer forward declaration over `#include`s whenever possible. This allows you to break the cyclic header dependencies. Essentially, for cyclical dependencies across separate files, you want a file-dependency graph that looks something like this: + `A.cxx` requires `A.h` and `B.h` + `B.cxx` requires `A.h` and `B.h` + `A.h` requires `B.h` + `B.h` is independent (and forward-declares classes defined in `A.h`) If your code is intended to be a library consumed by other developers, there are some additional steps that are important to take: * If necessary, use the concept of "private headers". That is, header files that are required by several source files, but never required by the public interface. This could be a file with common inline functions, macros, or internal constants. * Separate your public interface from your private implementation at the filesystem level. I tend to use `include/` and `src/` subdirectories in my C or C++ projects, where `include/` has all of my public headers, and `src/` has all of my sources. and private headers. I'd recommend finding a copy of John Lakos' book *Large-Scale C++ Software Design*. It's a pretty hefty book, but if you just skim through some of his discussions on physical architecture, you'll learn a lot.
Check out the C and C++ coding standards at the [NASA Goddard Space Flight Center](http://software.gsfc.nasa.gov/assetsbytype.cfm?TypeAsset=Standard). The one rule that I specially noted in the C standard and have adopted in my own code is the one that enforces the 'standalone' nature of header files. In the implementation file xxx.cpp for the header xxx.h, ensure that xxx.h is the first header included. If the header is not self-contained at any time, then compilation will fail. It is a beautifully simple and effective rule. The only time it fails you is if you port between machines, and the xxx.h header includes, say, `<pqr.h>`, but `<pqr.h>` requires facilities that happen to be made available by a header `<abc.h>` on the original platform (so `<pqr.h>` includes `<abc.h>`), but the facilities are not made available by `<abc.h>` on the other platform (they are in `def.h` instead, but `<pqr.h>` does not include `<def.h>`). This isn't a fault of the rule, and the problem is more easily diagnosed and fixed if you follow the rule.
C++ class header files organization
[ "", "c++", "class", "file", "header", "organization", "" ]
In the Fibonacci sequence, I have seen conventional implementations which recursively call the same method twice: ``` public void fibonacci(int i) { fibonacci(1) + fibonacci(2); } ``` Now this method is not the exact copy of what I have seen or the right way of solving the problem, but I've seen the two methods added together like above. So the method isn't recursively called, but recursively called twice. What exactly happens when writing code like this in C#? Are the two methods run on seperate threads? What is happening under the hood?
This is one of those times when it's useful to think about the way the computer does it. Let's start with the function. I'm going to write it in Python flavored pseudocode because I want you to get away from thinking about the LANGUAGE for a second. ``` def fib(n): if n == 0: return 0 if n == 1: return 1 if n > 1: return fib(n-2) + fib(n-1) ``` Now let's walk through this for fib(2) `fib(2)` has *n>1*, so it takes the third branch, ``` return fib(2-2) + fib(2-1) ``` so it calls *fib()* with 0, which is 0 ``` return 0 + fib(2-1) ``` calls *fib()* with 1 ``` return 0 + 1 ``` and we see the result 1. Now consider fib(3): n>1, so ``` return fib(3-2)+fib(3-1) ``` and since 3-2 is 1, we get fib(1) for the first term, which is 1: ``` return 1 + fib(3-1) ``` and now when we call fib(3-1), which is to say fib(2), we don't have the direct answer yet; n>1. So it becomes ``` return 1 + return fib(2-2) + fib(2-1) ``` which becomes ``` return 0 + 1 ``` ans we pop back to the earlier call ``` return 1 + 1 ``` and get the value 2. So, you see, there's no separate thread, it just works its way across the expression. I'll leave it as an exercise to work out an example for fib(4); I bet if you do, though, you'll have it nailed. Pop quiz: *why* is the iterative version so dramatically more efficient?
No, they are called one after another. No additional threads are made unless you explicitly ask for it (with System.Threading stuff). I'm not sure on the order they are called, but I would guess that from left to the right. C# specification definately has it in it.
Recursively calling the same method twice
[ "", "c#", ".net", "fibonacci", "" ]
Explain why a nullable int can't be assigned the value of null e.g ``` int? accom = (accomStr == "noval" ? null : Convert.ToInt32(accomStr)); ``` What's wrong with that code?
The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead: ``` int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr)); ```
What Harry S says is exactly right, but ``` int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr)); ``` would also do the trick. (We Resharper users can always spot each other in crowds...)
c# why can't a nullable int be assigned null as a value
[ "", "c#", "nullable", "" ]
Given this: ``` Interface IBase {string X {get;set;}} Interface ISuper {string Y {get;set;}} class Base : IBase {etc...} class Super : Base, ISuper {etc...} void Questionable (Base b) { Console.WriteLine ("The class supports the following interfaces... ") // The Magic Happens Here } ``` What can I replace "The Magic" with to display the supported interfaces on object b? Yes, I know by being of class Base it supports "IBase", the real hierarchy is more complex that this. :) Thanks! -DF5 EDIT: Now that I've seen the answer I feel stupid for not tripping over that via Intellisense. :) Thanks All! -DF5
The Magic : ``` foreach (Type iface in b.GetType().GetInterfaces()) Console.WriteLine(iface.Name); ```
b.GetType().[GetInterfaces](http://msdn.microsoft.com/en-us/library/system.type.getinterfaces.aspx)()
Given an Object, How can I programatically tell what Interfaces it supports?
[ "", "c#", ".net", "reflection", "interface", "" ]
I'd like to know when i should and shouldn't be wrapping things in a USING block. From what I understand, the compiler translates it into a try/finally, where the finally calls Dispose() on the object. I always use a USING around database connections and file access, but its more out of habit rather than a 100% understanding. I know you should explicity (or with a using) Dispose() objects which control resources, to ensure they are released instantly rather than whenever the CLR feels like it, but thats where my understanding breaks down. Are IDisposables not disposed of when they go out of scope? Do I only need to use a USING when my object makes use of Dispose to tidy itself up? Thanks Edit: I know there are a couple of other posts on the USING keyword, but I'm more interested in answers relating the the CLR and exactly whats going on internally Andrew
No, `IDisposable` items are not disposed when they go out of scope. It is for precisely this reason that we need `IDisposable` - for deterministic cleanup. They will *eventually* get garbage collected, and if there is a finalizer it will (maybe) be called - but that could be a long time in the future (not good for connection pools etc). Garbage collection is dependent on memory pressure - if nothing wants extra memory, there is no need to run a GC cycle. Interestingly (perhaps) there are some cases where "using" is a pain - when the offending class throws an exception on `Dispose()` sometimes. WCF is an offender of this. I have discussed this topic (with a simple workaround) [here](http://marcgravell.blogspot.com/2008/11/dontdontuse-using.html). Basically - if the class implements `IDisposable`, and you *own* an instance (i.e. you created it or whatever), it is your job to ensure that it gets disposed. That might mean via "using", or it might mean passing it to another piece of code that assumes responsibility. I've actually seen debug code of the type: ``` #if DEBUG ~Foo() { // complain loudly that smoebody forgot to dispose... } #endif ``` (where the `Dispose` calls `GC.SuppressFinalize`)
> "Are IDisposables not disposed of when > they go out of scope?" No. If the IDisposable object is *finalizable*, which is not the same thing, then it will be finalized when it's garbage collected. Which might be soon or might be almost never. Jeff Richter's C#/CLR book is very good on all this stuff, and the Framework Design Guidelines book is also useful. > Do I only need to use a USING when my > object makes use of Dispose to tidy > itself up? You can *only* use 'using' when the object implements IDisposable. The compiler will object if you try to do otherwise.
C# USING keyword - when and when not to use it?
[ "", "c#", "dispose", "" ]
Here's the purpose of my console program: Make a web request > Save results from web request > Use QueryString to get next page from web request > Save those results > Use QueryString to get next page from web request, etc. So here's some pseudocode for how I set the code up. ``` for (int i = 0; i < 3; i++) { strPageNo = Convert.ToString(i); //creates the url I want, with incrementing pages strURL = "http://www.website.com/results.aspx?page=" + strPageNo; //makes the web request wrGETURL = WebRequest.Create(strURL); //gets the web page for me objStream = wrGETURL.GetResponse().GetResponseStream(); //for reading web page objReader = new StreamReader(objStream); //-------- // -snip- code that saves it to file, etc. //-------- objStream.Close(); objReader.Close(); //so the server doesn't get hammered System.Threading.Thread.Sleep(1000); } ``` Pretty simple, right? **The problem is**, even though it increments the page number to get a different web page, I'm getting the *exact same results page* each time the loop runs. `i` IS incrementing correctly, and I can cut/paste the url `strURL` creates into a web browser and it works just fine. I can manually type in `&page=1`, `&page=2`, `&page=3`, and it'll return the correct pages. Somehow putting the increment in there screws it up. Does it have anything to do with sessions, or what? I make sure I close both the stream and the reader before it loops again...
Have you tried creating a new WebRequest object for each time during the loop, it could be the Create() method isn't adequately flushing out all of its old data. Another thing to check is that the ResponseStream is adequately flushed out before the next loop iteration.
This code works fine for me: ``` var urls = new [] { "http://www.google.com", "http://www.yahoo.com", "http://www.live.com" }; foreach (var url in urls) { WebRequest request = WebRequest.Create(url); using (Stream responseStream = request.GetResponse().GetResponseStream()) using (Stream outputStream = new FileStream("file" + DateTime.Now.Ticks.ToString(), FileMode.Create, FileAccess.Write, FileShare.None)) { const int chunkSize = 1024; byte[] buffer = new byte[chunkSize]; int bytesRead; while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0) { byte[] actual = new byte[bytesRead]; Buffer.BlockCopy(buffer, 0, actual, 0, bytesRead); outputStream.Write(actual, 0, actual.Length); } } Thread.Sleep(1000); } ```
C# - WebRequest Doesn't Return Different Pages
[ "", "c#", "html", "" ]
I'm trying to get my head around tuples (thanks @litb), and the common suggestion for their use is for functions returning > 1 value. This is something that I'd normally use a struct for , and I can't understand the advantages to tuples in this case - it seems an error-prone approach for the terminally lazy. [Borrowing an example](https://stackoverflow.com/questions/321068/returning-multiple-values-from-a-c-function), I'd use this ``` struct divide_result { int quotient; int remainder; }; ``` Using a tuple, you'd have ``` typedef boost::tuple<int, int> divide_result; ``` But without reading the code of the function you're calling (or the comments, if you're dumb enough to trust them) you have no idea which int is quotient and vice-versa. It seems rather like... ``` struct divide_result { int results[2]; // 0 is quotient, 1 is remainder, I think }; ``` ...which wouldn't fill me with confidence. So, what *are* the advantages of tuples over structs that compensate for the ambiguity?
### tuples I think i agree with you that the issue with what position corresponds to what variable can introduce confusion. But i think there are two sides. One is the *call-side* and the other is the *callee-side*: ``` int remainder; int quotient; tie(quotient, remainder) = div(10, 3); ``` I think it's crystal clear what we got, but it can become confusing if you have to return more values at once. Once the caller's programmer has looked up the documentation of `div`, he will know what position is what, and can write effective code. As a rule of thumb, i would say not to return more than 4 values at once. For anything beyond, prefer a struct. ### output parameters Output parameters can be used too, of course: ``` int remainder; int quotient; div(10, 3, &quotient, &remainder); ``` Now i think that illustrates how tuples are better than output parameters. We have mixed the input of `div` with its output, while not gaining any advantage. Worse, we leave the reader of that code in doubt on what could be the *actual* return value of `div` be. There *are* wonderful examples when output parameters are useful. In my opinion, you should use them only when you've got no other way, because the return value is already taken and can't be changed to either a tuple or struct. `operator>>` is a good example on where you use output parameters, because the return value is already reserved for the stream, so you can chain `operator>>` calls. If you've not to do with operators, and the context is not crystal clear, i recommend you to use pointers, to signal at the call side that the object is actually used as an output parameter, in addition to comments where appropriate. ### returning a struct The third option is to use a struct: ``` div_result d = div(10, 3); ``` I think that definitely wins the award for **clearness**. But note you have still to access the result within that struct, and the result is not "laid bare" on the table, as it was the case for the output parameters and the tuple used with `tie`. I think a major point these days is to make everything as generic as possible. So, say you have got a function that can print out tuples. You can just do ``` cout << div(10, 3); ``` And have your result displayed. I think that tuples, on the other side, clearly win for their **versatile** nature. Doing that with div\_result, you need to overload operator<<, or need to output each member separately.
Another option is to use a Boost Fusion map (code untested): ``` struct quotient; struct remainder; using boost::fusion::map; using boost::fusion::pair; typedef map< pair< quotient, int >, pair< remainder, int > > div_result; ``` You can access the results relatively intuitively: ``` using boost::fusion::at_key; res = div(x, y); int q = at_key<quotient>(res); int r = at_key<remainder>(res); ``` There are other advantages too, such as the ability to *iterate* over the fields of the map, etc etc. See the [doco](http://www.boost.org/doc/libs/1_37_0/libs/fusion/doc/html/index.html) for more information.
Boost::Tuples vs Structs for return values
[ "", "c++", "tuples", "boost-tuples", "" ]
Are there any good reasons not to use \u0000 as a delimiter within a Java String? I would be encoding and decoding the string myself. This is for saving a list of user-inputted (I'm expecting input to be typed?) strings to an Eclipse preference and reading it back. The list may be variable size so I don't think I can save each item to its own preference.
There used to be some libraries which erroneously handled Java strings as null terminated. I don't know if it's still true but it's worth keeping such things in mind. Especially if you interop with external libraries that will handle strings as null terminated.
If the data stays in Java, why don't you use an array or a List instead?
Null \u0000 in Java String?
[ "", "java", "string", "null", "" ]
If `UNION ALL` is an *addition* in T-SQL. What is the equivalent of subtraction? For example, if I have a table `PEOPLE` and a table `EMPLOYEES`. And I know if I remove `EMPLOYEES` records from `PEOPLE` I will be left with my companies `CONTRACTORS`. Is there a way of doing this that is similar to `UNION ALL`? One where I don't have to specify any field names? The reason I ask is this is just one hypothetical example. I need to do this several times to many different tables. Assume that the schema of `EMPLOYEES` and `PEOPLE` are the same.
Instead of using UNION, use EXCEPT, ( or INTERSECT to get only records in both ) as described in [msdn EXCEPT Link for Sql2k8](http://msdn.microsoft.com/en-us/library/ms188055.aspx) [msdn EXCEPT Link for Sql2k5](http://msdn.microsoft.com/en-us/library/ms188055(SQL.90).aspx)
You can use the [EXCEPT operator](http://msdn.microsoft.com/en-us/library/ms188055.aspx) to subtract one set from another. Here's a sample of code using EMPLOYEES and PEOPLE temporary tables. You'll need to use the field names with the EXCEPT operator as far as I know. ``` CREATE TABLE #PEOPLE (ID INTEGER, Name NVARCHAR(50)) CREATE TABLE #EMPLOYEE (ID INTEGER, Name NVARCHAR(50)) GO INSERT #PEOPLE VALUES (1, 'Bob') INSERT #PEOPLE VALUES (2, 'Steve') INSERT #PEOPLE VALUES (3, 'Jim') INSERT #EMPLOYEE VALUES (1, 'Bob') GO SELECT ID, Name FROM #PEOPLE EXCEPT SELECT ID, Name FROM #EMPLOYEE GO ``` The final query will return the two rows in the PEOPLE table which do not exist in the EMPLOYEE table.
T-SQL: Comparing Two Tables - Records that don't exist in second table
[ "", "sql", "sql-server-2005", "t-sql", "" ]
I am using the [SQLite](http://www.sqlite.org/) database and have the following persistent class (simplified): ``` public class Project { public virtual int Id { get; set; } public virtual DateTime StartDate { get; set; } } ``` which is mapped to this table in the database: ``` CREATE TABLE projects ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, start_date DATETIME ) ``` Now I need to write a query that will select all the projects that have started in a given month. In SQL I could use: ``` SELECT id FROM projects WHERE strftime('%m', start_date) = '12' ``` What I dislike about this query is that it uses the database specific function "[strftime](http://www.sqlite.org/lang_datefunc.html)". So the following HQL is dependent on the underlying database: ``` // Get all projects that started in December (no matter which year) var projects = session .CreateQuery( "from Project p " + "where strftime('%m', p.StartDate) = :month") .SetParameter("month", "12") .List<Project>(); ``` I have also tried "from Project p where p.StartDate.Month = 12" but it didn't work. So using HQL or criteria API is it possible to write such a query in a database agnostic way?
If you're regularly querying against months, days, years, you shouldn't really be storing your date as a DateTime column - it makes the queries incredibly inefficient. You could easily create a "Month" column and query against that (and your DBA would love you again)
I would highly recommend you to write a custom function. <http://ayende.com/Blog/archive/2006/10/01/UsingSQLFunctionsInNHibernate.aspx> I don't mean the sql function, I mean the NHibernate function that is registered with RegisterFunction to enhance the NHibernate dialect. Another probably better example: <http://ayende.com/Blog/archive/2007/04/27/Paged-data--Count-with-NHibernate-The-really-easy-way.aspx>
Using dates in the "where" clause of HQL query
[ "", "c#", "nhibernate", "" ]
I am trying to run my Django sites with mod\_wsgi instead of mod\_python (RHEL 5). I tried this with all my sites, but get the same problem. I configured it the standard way everyone recommends, but requests to the site simply time out. Apache conf: ``` <VirtualHost 74.54.144.34> DocumentRoot /wwwclients/thymeandagain ServerName thymeandagain4corners.com ServerAlias www.thymeandagain4corners.com LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined CustomLog /var/log/httpd/thymeandagain_access_log combined ErrorLog /var/log/httpd/thymeandagain_error_log LogLevel error WSGIScriptAlias / /wwwclients/thymeandagain/wsgi_handler.py WSGIDaemonProcess thymeandagain user=admin group=admin processes=1 threads=16 WSGIProcessGroup thymeandagain </VirtualHost> ``` wsgi\_handler.py: ``` import sys import os sys.path.append("/wwwclients") os.environ['DJANGO_SETTINGS_MODULE'] = 'thymeandagain.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() ``` The daemon mod\_wsgi is supposed to spawn off is not there, so requests just time out and I get a bunch of "Unable to connect to WSGI daemon process" errors in the logs. Is there something about the WSGIDaemonProcess directive that is preventing creation of the daemon? Thanks in advance for any help... EDIT: I get this in the error log: ``` [WARN@1227228322.174175] mcm_server_readable():2582: timeout: Operation now in progress: select(2) call timed out for read(2)able fds [INFO@1227228322.174263] mcm_get_line():1592 [WARN@1227227903.249626] mcm_server_readable():2582: timeout: Operation now in progress: select(2) call timed out for read(2)able fds [INFO@1227227903.249712] mcm_get_line():1592 [Thu Nov 20 21:18:17 2008] [notice] caught SIGTERM, shutting down [Thu Nov 20 21:18:18 2008] [notice] Digest: generating secret for digest authentication ... [Thu Nov 20 21:18:18 2008] [notice] Digest: done [Thu Nov 20 21:18:18 2008] [notice] mod_python: Creating 4 session mutexes based on 8 max processes and 64 max threads. [Thu Nov 20 21:18:18 2008] [notice] Apache/2.2.3 (Red Hat) mod_python/3.2.8 Python/2.4.3 mod_wsgi/2.1-BRANCH configured -- resuming normal operations ```
The problem is that mod\_python doesn't go well together with mod\_wsgi. I got into similar issue few weeks ago and everything started working for me shortly after I commented out mod\_python inclusion. Try to search [modwsgi.org](http://modwsgi.org) wiki for "mod\_python", I believe there was someone talking about this somewhere in comments
The real problem is permissions on Apache log directory. It is necessary to tell Apache/mod\_wsgi to use an alternate location for the UNIX sockets used to communicate with the daemon processes. See: <http://code.google.com/p/modwsgi/wiki/ConfigurationIssues#Location_Of_UNIX_Sockets>
Running a Django site under mod_wsgi
[ "", "python", "django", "apache", "mod-wsgi", "" ]
How can I obtain the .NET Framework directory path inside my C# application? The folder that I refer is "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727"
The path to the installation directory of the CLR active for the current .NET application can be obtained by using the following method: ``` System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() ``` I would **strongly** advice against reading the registry directly. For example, when a .NET application is running in 64bit systems, the CLR can either be loaded from "C:\Windows\Microsoft.NET\Framework64\v2.0.50727" (AnyCPU, x64 compilation targets) or from "C:\Windows\Microsoft.NET\Framework\v2.0.50727" (x86 compilation target). Reading registry will **not** tell you which one of the two directories was used by the current CLR. Another important fact is that "the current CLR" will be "2.0" for .NET 2.0, .NET 3.0 and .NET 3.5 applications. This means that the GetRuntimeDirectory() call will return 2.0 directory even within .NET 3.5 applications (that load some of their assemblies from 3.5 directory). Depending on your interpretation of the term ".NET Framework directory path", GetRuntimeDirectory might not be the information you are looking for ("CLR directory" versus "directory from which 3.5 assemblies are coming from").
An easier way is to include the Microsoft.Build.Utilities assembly and use ``` using Microsoft.Build.Utilities; ToolLocationHelper.GetPathToDotNetFramework( TargetDotNetFrameworkVersion.VersionLatest); ```
Getting the .NET Framework directory path
[ "", "c#", ".net", "frameworks", "directory", "" ]
I'd like to use regex with Java. What I want to do is find the first integer in a string. Example: ``` String = "the 14 dogs ate 12 bones" ``` Would return 14. ``` String = "djakld;asjl14ajdka;sdj" ``` Would also return 14. This is what I have so far. ``` Pattern intsOnly = Pattern.compile("\\d*"); Matcher makeMatch = intsOnly.matcher("dadsad14 dssaf jfdkasl;fj"); makeMatch.find(); String inputInt = makeMatch.group(); System.out.println(inputInt); ``` What am I doing wrong?
You're asking for 0 or more digits. You need to ask for 1 or more: ``` "\\d+" ```
It looks like the other solutions failed to handle `+/-` and cases like `2e3`, which `java.lang.Integer.parseInt(String)` supports, so I'll take my go at the problem. I'm somewhat inexperienced at regex, so I may have made a few mistakes, used something that Java's regex parser doesn't support, or made it overly complicated, but the statements seemed to work in [Kiki 0.5.6](http://code.google.com/p/kiki-re/). *All regular expressions are provided in both an unescaped format for reading, and an escaped format that you can use as a string literal in Java.* **To get a byte, short, int, or long from a string:** ``` unescaped: ([\+-]?\d+)([eE][\+-]?\d+)? escaped: ([\\+-]?\\d+)([eE][\\+-]?\\d+)? ``` ...and for bonus points... **To get a double or float from a string:** ``` unescaped: ([\+-]?\d(\.\d*)?|\.\d+)([eE][\+-]?(\d(\.\d*)?|\.\d+))? escaped: ([\\+-]?\\d(\\.\\d*)?|\\.\d+)([eE][\\+-]?(\\d(\\.\\d*)?|\\.\\d+))? ```
Regex to find an integer within a string
[ "", "java", "regex", "integer", "" ]
I'm looking to have a simple custom dialog box, like a message box, that has a label and a TextBox. If there's a simple way to do this, sorry! I'm really not well versed in the dialog stuff. Thanks for any help, guys!
Here is how to make a small custom dialog box in Windows Mobile that looks like this: [alt text http://www.freeimagehosting.net/uploads/b8fb5421d6.jpg](http://www.freeimagehosting.net/uploads/b8fb5421d6.jpg) Add a form to your project, and set its FormBorderStyle property to None. This allows the form to be resized and positioned, but also means it has no border or titlebar, and there's no way for the user to move it. So you have to fake all three. The easiest way to fake the border and the title bar is to make the BackColor of your form SystemColors.WindowFrame, then put a label (where it says "Dialog" in the picture) with BackColor = SystemColors.Highlight and ForeColor = SystemColor.HighlightText (and bold the font), then put a panel with BackColor = SystemColors.Window where you see white in the picture. You have to tweak the positions and sizes of the label and the panel so you have a 1-pixel border (which is just the BackColor of your form showing through). To enable the form to be dragged around by its fake titlebar, add this code to the form (and of course you have to wire up the events, too): ``` private bool _Moving = false; private Point _Offset; private void Form1_MouseDown(object sender, MouseEventArgs e) { _Moving = true; _Offset = new Point(e.X, e.Y); } private void Form1_MouseMove(object sender, MouseEventArgs e) { if (_Moving) { Point newlocation = this.Location; newlocation.X += e.X - _Offset.X; newlocation.Y += e.Y - _Offset.Y; this.Location = newlocation; } } private void Form1_MouseUp(object sender, MouseEventArgs e) { if (_Moving) { _Moving = false; } } ``` One other problem is that because there isn't a real titlebar, there's no way for the user to close the form. You have to add an OK (or Close) button, and put this in the button's Click event: ``` this.DialogResult = DialogResult.OK; ``` Normally you would use the mouse event on the title bar to facilitate dragging, but the label control doesn't have any mouse events. With this code you could actually grab anywhere on the form and drag it, except the panel blocks this and makes the title bar the only place to grab and drag. My other answer has more details on getting information back from custom dialogs. Update: actually, there's only no *obvious* way to close a borderless form without adding your own OK button. As long as you don't set your form's ControlBox property to False, the OK or X button in the upper right corner of the Today screen will close your dialog, even if it doesn't look like it will since it's not actually on the form.
If you want a super-simple but[t] ugly solution, you can include a reference in your project to Microsoft.VisualBasic, which lets you use the VB function InputBox like this: ``` string s = Microsoft.VisualBasic.Interaction.InputBox("prompt text", "title text", "default value", 0, 0); ``` The dialog takes up the entire screen, but is simple to use. But is incredibly ugly, as I mentioned.
custom dialog with a text field in winmobile
[ "", "c#", "windows-mobile", "smartphone", "" ]
I have a huge number of mail archives that I want to de-duplicate and sort out. The archives are either in mbox format or contain a single mail message. To add a bit of complication, some of the files have windows EOL sequences, and some have the unix EOL. Using C#. how do I read an archive and split it into its individual messages, or read a single message file? In python, I would use the *mailbox.mbox* class, but I cannot see the matching functionality in the C# documentation.
It is unlikely that you will find a library to read that file for C# - there aren't that many Unix users who also use C#. What I would do would be either to: 1. Read the Python code, and then port it to C# 2. Find the description of the mbox format online. As it is a Unix system, chances are that the format is just a plain text file, which should be easy enough to parse.
Most standard Unix mail files delimit entries with a line starting "From " So if you read in the mail file as a text file and switch to a new mail entry every time you see the string "From " at the start of a line it should work - Any strings elsewhere should already have been delimited by the email program
Reading email from a mail file
[ "", "c#", ".net", "email", "" ]
What the difference between `LPCSTR`, `LPCTSTR` and `LPTSTR`? Why do we need to do this to convert a string into a `LV` / `_ITEM` structure variable `pszText`: ``` LV_DISPINFO dispinfo; dispinfo.item.pszText = LPTSTR((LPCTSTR)string); ```
To answer the first part of your question: `LPCSTR` is a pointer to a const string (LP means [Long Pointer](https://stackoverflow.com/questions/2315311/what-is-a-long-pointer)) `LPCTSTR` is a pointer to a `const TCHAR` string, (`TCHAR` being either a wide char or char depending on whether UNICODE is defined in your project) `LPTSTR` is a pointer to a (non-const) `TCHAR` string In practice when talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers. This is a great [codeproject article](http://www.codeproject.com/KB/string/cppstringguide1.aspx) describing C++ strings (see 2/3 the way down for a chart comparing the different types)
Quick and dirty: `LP` == **L**ong **P**ointer. Just think pointer or char\* `C` = **C**onst, in this case, I think they mean the character string is a const, not the pointer being const. `STR` is **string** the `T` is for a wide character or char (TCHAR) depending on compiler options. ## Bonus Reading From [What does the letter "T" in LPTSTR stand for?](https://devblogs.microsoft.com/oldnewthing/20061017-03/?p=29363): [archive](https://archive.ph/3lqLY) > # What does the letter "T" in LPTSTR stand for? > > October 17th, 2006 > > The “T” in LPTSTR comes from the “T” in TCHAR. I don’t know for certain, but it seems pretty likely that it stands for “text”. By comparison, the “W” in WCHAR probably comes from the C language standard, where it stands for “wide”.
LPCSTR, LPCTSTR and LPTSTR
[ "", "c++", "windows", "visual-c++", "mfc", "" ]
Anyone know a good lib where i can run the strings before they are inserted, that can strip out sql/javascript code? To be run in jsp pages. Idealy the lib would be: * Free * Lightweight * Easy to use Thanks in advance to the SO community who will happily reply :)
Apache Commons lang StringEscapeUtils will get you some of the way. It escapes, doesnt strip. <http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html> Edit: Escaping can save you from injection attacks because it makes sure that the data the user has entered is not executed as code, but always presented as data to the user.
You need to rely on the your database api's mechanism for using parameterized queries. If you're *first* building an sql string dynamically and *then* want to sanitize the completed query string, you're doing it wrong. That's just asking for trouble. --- Edit: after re-reading your question, it seems I mis-understood what you were asking. I stand by my initial comments as accurate for the sql injection part of your question. For that, you definitely want real query parameters. As for filtering out javascript, I don't think there's a real *standard* way to do it yet. I know Jeff posted the code they use here at SO, but I don't have the link handy. If I can find it I'll post it.
Lib to protect SQL/javascript injection for java/jsp
[ "", "java", "security", "jsp", "sql-injection", "javascript-injection", "" ]
AFAIK, you never need to specify the protocol in an onclick: `onclick="javascript:myFunction()"` **Bad** `onclick="myFunction()"` **Good** Today I noticed in [this article](http://web.archive.org/web/20080428095515/http://www.google.com/support/analytics/bin/answer.py?answer=55527) on Google Anallytics that *they* are using it: ``` <a href="http://www.example.com" onClick="javascript: pageTracker._trackPageview('/outgoing/example.com');"> ``` Is this example just plain wrong, or is there ever a reason to specify `javascript:` in anything other than a `href`?
Some of the responses here claim that the "javascript:" prefix is a "leftover from the old days", implying that it's intentionally, specially handled by the browsers for backwards compatibility. Is there solid evidence that this is the case (has anyone checked source code)? ``` <span onclick="javascript:alert(42)">Test</span> ``` To me, this just reads as: ``` javascript: alert(42); ``` Meaning, that "javascript:" is just a label and has no effect. This works, too: ``` <span onclick="foobar:alert(42)">Test</span> ``` **Update:** I did a little experiment and it turns out that, yes, "javascript:" is handled specially by IE, but definitely not so by Firefox, Safari, Opera or Chrome: ``` <span onclick="javascript:while (true) { alert('once'); break javascript; }">Test</span> ``` On non-IE, this will just alert "once", once and then break out of the loop. On IE, I get a "Label not found" error. The following works fine in all browsers: ``` <span onclick="foo:while (true) { alert('once'); break foo; }">Test</span> ``` **Update 2:** I just realized the link <http://crisp.tweakblogs.net/blog/the-useless-javascript-pseudo-protocol.html> in one of the answers above pretty much talks about the same thing.
It's never needed on anchors and is never good practice. An anchor is for navigation only. An article about this topic is *[The useless JavaScript: pseudo-protocol](http://crisp.tweakblogs.net/blog/the-useless-javascript-pseudo-protocol.html)*.
Do you ever need to specify 'javascript:' in an onclick?
[ "", "javascript", "google-api", "" ]
Consider the code: ``` PreparedStatement ps = null; ResultSet rs = null; try { ps = conn.createStatement(myQueryString); rs = ps.executeQuery(); // process the results... } catch (java.sql.SQLException e) { log.error("an error!", e); throw new MyAppException("I'm sorry. Your query did not work."); } finally { ps.close(); rs.close(); } ``` The above does not compile, because both `PreparedStatement.close()` and `ResultSet.close()` throw a `java.sql.SQLException`. So do I add a try/catch block to the finally clause? Or move the close statements into the try clause? Or just not bother calling close?
For file I/O, I generally add a try/catch to the finally block. However, you must be careful not to throw any exceptions from the finally block, since they will cause the original exception (if any) to be lost. See [this article](http://accu.org/index.php/journals/236) for a more specific example of database connection closing.
In Java 7, you should not close them explicitly, but use [automatic resource management](http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html) to ensure that [resources](http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html) are closed and exceptions are handled appropriately. Exception handling works like this: ``` Exception in try | Exception in close | Result -----------------+--------------------+---------------------------------------- No | No | Continue normally No | Yes | Throw the close() exception Yes | No | Throw the exception from try block Yes | Yes | Add close() exception to main exception | | as "suppressed", throw main exception ``` Hopefully that makes sense. In allows pretty code, like this: ``` private void doEverythingInOneSillyMethod(String key) throws MyAppException { try (Connection db = ds.getConnection()) { db.setReadOnly(true); ... try (PreparedStatement ps = db.prepareStatement(...)) { ps.setString(1, key); ... try (ResultSet rs = ps.executeQuery()) { ... } } } catch (SQLException ex) { throw new MyAppException("Query failed.", ex); } } ``` --- Prior to Java 7, it's best to use nested finally blocks, rather than testing references for null. The example I'll show might look ugly with the deep nesting, but in practice, well-designed code probably isn't going to create a connection, statement, and results all in the same method; often, each level of nesting involves passing a resource to another method, which uses it as a factory for another resource. With this approach, exceptions from a `close()` will mask an exception from inside the `try` block. That can be overcome, but it results in even more messy code, and requires a custom exception class that provides the "suppressed" exception chaining present in Java 7. ``` Connection db = ds.getConnection(); try { PreparedStatement ps = ...; try { ResultSet rs = ... try { ... } finally { rs.close(); } } finally { ps.close(); } } finally { db.close(); } ```
Where to close java PreparedStatements and ResultSets?
[ "", "java", "jdbc", "resource-management", "" ]
What is the best was to evaluate an expression like the following: (A And B) Or (A And C) Or (Not B And C) or (A && B) || (A && C) || (!B && C) At runtime, I was planning on converting the above expressions to the following: (True And False) Or (True And False) Or (Not False And True) or (True && False) || (True && False) || (! False && True) Conditions: 1) The logical expression is not known until runtime. 2) The number variable and their values are not known until runtime. 3) Variable values are never null. I know I could create a simple assemble with a class and a method that I generate at runtime based on the inputs, but is there a better way. I have done this before. Use a string builder to write the code, then call the compiler. After that, you load the assembly and call the method. Suggestions? Thanks.
If you're using .NET3.5 then you can parse the text and create an abstract sytax tree using the Expression classes. Then create a suitable LambdaExpression instance and compile it into a delegate, which you can then execute. Constructing a parser and syntax tree builder for this kind of fairly simple grammer is quite an interesting exercise, and will execute somewhat faster than invoking the compiler (and it's neater in my view as well). If you're not using .NET3.5, then it's also not complicated to implement an interpreted abstract syntax tree yourself.
Be warned: the two final conditions you're talking about are not necessarily equivalent. The && operators in C# will use short-circuit evalution, while the logical `And` operator in VB does not. If you want to be sure the statements are equivalent, translate a user `And` to `AndAlso` and a user `Or` to `OrElse`. For simple expresssions you probably won't notice a difference. But if the conditions can have side effects or if the performance difference between the two is a concern, this can be important.
Dynamic logical expression parsing/evaluation in C# or VB?
[ "", "c#", "vb.net", "expression", "" ]
I have two processes one will query other for data.There will be huge amount of queries in a limited time (10000 per second) and data (>100 mb) will be transferred per second.Type of data will be an integral type(double,int) My question is in which way to connect this process? Shared memory , message queue , lpc(Local Procedure call) or others.... And also i want to ask which library you suggest? by the way please do not suggest MPI. edit : under windows xp 32 bit
One Word: [Boost.InterProcess](https://www.boost.org/doc/libs/1_74_0/doc/html/interprocess.html). If it really needs to be fast, shared memory is the way to go. You nearly have zero overhead as the operation system does the usual mapping between virtual and physical addresses and no copy is required for the data. You just have to lookout for concurrency issues. For actually sending commands like *shutdown* and *query*, I would use message queues. I previously used localhost network programming to do that, and used manual shared memory allocation, before i knew about boost. Damn if i would need to rewrite the app, I would immediately pick boost. Boost.InterProcess makes this more easy for you. Check it out.
I would use shared memory to store the data, and message queues to send the queries.
Best way for interprocess communication in C++
[ "", "c++", "memory", "boost", "ipc", "shared", "" ]
I have been doing a lot of research on this lately, but have yet to get a really good solid answer. I read somewhere that a new Function() object is created when the JavaScript engine comes across a function statement, which would lead me to believe it could be a child of an object (thus becoming one). So I emailed Douglas Crockford, and his answer was: > Not exactly, because a function > statement does not call the compiler. > > But it produces a similar result. Also, to my knowledge, you can't call members on a function constructor unless it has been instantiated as a new object. So this will not work: ``` function myFunction(){ this.myProperty = "Am I an object!"; } myFunction.myProperty; // myFunction is not a function myFunction().myProperty; // myFunction has no properties ``` However, this will work: ``` function myFunction(){ this.myProperty = "Am I an object!"; } var myFunctionVar = new myFunction(); myFunctionVar.myProperty; ``` Is this just a matter of semantics... in the whole of the programming world, when does an object really become an object, and how does that map to JavaScript?
Your understanding is wrong: ``` myFunction().myProperty; // myFunction has no properties ``` The reason it does not work is because ".myProperty" is applied to the returned value of "myFunction()", not to the object "myFunction". To wit: ``` $ js js> function a() { this.b=1;return {b: 2};} js> a().b 2 js> ``` Remember, "()" is an operator. "myFunction" is not the same as "myFunction()". You don't need a "return" when instanciang with new: ``` js> function a() { this.b=1;} js> d = new a(); [object Object] js> d.b; 1 ```
There is nothing magical about functions and constructors. All objects in JavaScript are … well, objects. But some objects are more special than the others: namely built-in objects. The difference lies mostly in following aspects: 1. General treatment of objects. Examples: * Numbers and Strings are immutable (⇒ constants). No methods are defined to change them internally — new objects are always produced as the result. While they have some innate methods, you cannot change them, or add new methods. Any attempts to do so will be ignored. * `null` and `undefined` are special objects. Any attempt to use a method on these objects or define new methods causes an exception. 2. Applicable operators. JavaScript doesn't allow to (re)define operators, so we stuck with what's available. * Numbers have a special way with arithmetic operators: `+`, `-`, `*`, `/`. * Strings have a special way to handle the concatenation operator: `+`. * Functions have a special way to handle the "call" operator: `()`, and the `new` operator. The latter has the innate knowledge on how to use the `prototype` property of the constructor, construct an object with proper internal links to the prototype, and call the constructor function on it setting up `this` correctly. If you look into the ECMAScript standard ([PDF](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf)) you will see that all these "extra" functionality is defined as methods and properties, but many of them are not available to programmers directly. Some of them will be exposed in the new revision of the standard ES3.1 (draft as of 15 Dec 2008: [PDF](http://wiki.ecmascript.org/lib/exe/fetch.php?id=es3.1%3Aes3.1_proposal_working_draft&cache=cache&media=es3.1:tc39-es31-draft15dec08.pdf)). One property (`__proto__`) is [already exposed in Firefox](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Property_Inheritance_Revisited/Determining_Instance_Relationships). Now we can answer your question directly. Yes, a function object has properties, and we can add/remove them at will: ``` var fun = function(){/* ... */}; fun.foo = 2; console.log(fun.foo); // 2 fun.bar = "Ha!"; console.log(fun.bar); // Ha! ``` It really doesn't matter what the function actually does — it never comes to play because we don't call it! Now let's define it: ``` fun = function(){ this.life = 42; }; ``` By itself it is not a constructor, it is a function that operates on its context. And we can easily provide it: ``` var context = {ford: "perfect"}; // now let's call our function on our context fun.call(context); // it didn't create new object, it modified the context: console.log(context.ford); // perfect console.log(context.life); // 42 console.log(context instanceof fun); // false ``` As you can see it added one more property to the already existing object. In order to use our function as a constructor we have to use the `new` operator: ``` var baz = new fun(); // new empty object was created, and fun() was executed on it: console.log(baz.life); // 42 console.log(baz instanceof fun); // true ``` As you can see `new` made our function a constructor. Following actions were done by `new`: 1. New empty object (`{}`) was created. 2. Its internal prototype property was set to `fun.prototype`. In our case it will be an empty object (`{}`) because we didn't modify it in any way. 3. `fun()` was called with this new object as a context. It is up to our function to modify the new object. Commonly it sets up properties of the object, but it can do whatever it likes. Fun trivia: * Because the constructor is just an object we can calculate it: ``` var A = function(val){ this.a = val; }; var B = function(val){ this.b = val; }; var C = function(flag){ return flag ? A : B; }; // now let's create an object: var x = new (C(true))(42); // what kind of object is that? console.log(x instanceof C); // false console.log(x instanceof B); // false console.log(x instanceof A); // true // it is of A // let's inspect it console.log(x.a); // 42 console.log(x.b); // undefined // now let's create another object: var y = new (C(false))(33); // what kind of object is that? console.log(y instanceof C); // false console.log(y instanceof B); // true console.log(y instanceof A); // false // it is of B // let's inspect it console.log(y.a); // undefined console.log(y.b); // 33 // cool, heh? ``` * Constructor can return a value overriding the newly created object: ``` var A = function(flag){ if(flag){ // let's return something completely different return {ford: "perfect"}; } // let's modify the object this.life = 42; }; // now let's create two objects: var x = new A(false); var y = new A(true); // let's inspect x console.log(x instanceof A); // true console.log(x.ford); // undefined console.log(x.life); // 42 // let's inspect y console.log(y instanceof A); // false console.log(y.ford); // perfect console.log(y.life); // undefined ``` As you can see `x` is of `A` with the prototype and all, while `y` is our "naked" object we returned from the constructor.
Why in JavaScript is a function considered both a constructor and an object?
[ "", "javascript", "object", "constructor", "" ]
On some websites or forums I usually go to, entries that I havn't read yet are marked as "new". I would like to implement this feature on a website I have developed (with news being posted from time to time) -- php/mySQL. How is this usually done ? Does it require using a cookie remembering the last visit date/time ? Or the last viewed posts/urls ? How can I identify the users ?
Cookies are just one possible way of identifying the user for the session, or between visits for those without authentication. Though a very common and useful way. (PHP can also use the sid or another parameter, though its not common anymore.) You need to store either which threads/posts the user have read, or which he/she has not. You can sum things up with read everything before 'date' or postId for certain subforums. This all depends on the lay out of your forums, posts and news, and how dynamic they are. You might also only want to show new posts since last visit, show new posts while the user is currently at your site, then use the new posts since last visit if the user is away for more then a predefined (x hours)/calculated (y hours if weekend, z hours if admin) time. Edit: CSS for visited links will not help you with new comments for news, new posts in a thread, go directly to the first unread post or accessing the site at work/school and home.
A side note: doing so would actually be duplicating browser functionality: (as long as you use fixed urls) the browser will give links a different style on visited links. Of course this will reset if you clear history, but then again a cookie only based solution will allso clear if the cookie is deleted (with many browsers having a "delete private data" function wich deletes both by default, it would usually be reset at the same time)... *This site* have fixed url's (for questions) and doen't set the visited color the same as normal link color, so you can see the questions you've visited by the link color. EDIT: You can also use CSS to [add an icon to visited links](http://webdesign.about.com/od/css/a/aa041904.htm).
Marking latest news as ... "new"
[ "", "php", "mysql", "" ]
For our site, Im using a lot of jQuery - right now Im looking at 340 lines of jQuery code on top of the base library. How much is too much? I will be adding more, when do I start trying to condense the code and eventually move to OOP?
Optimally, you should keep you script size as minimum as possible, but with today's 'Web 2.0' websites, you will most probably accumulate quite a lot of JavaScript code. The important thing is that before you deploy your website, **make sure to [minify](http://www.crockford.com/javascript/jsmin.html) and [gzip](http://www.gzip.org/) your script files** as to reduce the size of your script files as much as possible. If you are really interested in optimizing and improving your website performance, I highly recommend taking a look at Steve Souders' [High Performance Web Sites: Essential Knowledge for Front-End Engineers](https://rads.stackoverflow.com/amzn/click/com/0596529309)
The number of lines doesn't mean anything - what matters is what you're actually doing. You could have 10 lines of supremely inefficient code that would do much more damage than a meticulously crafted 1000 lines of code.
How many lines of code is in your custom jQuery script on your site? And how much is too much?
[ "", "javascript", "design-patterns", "jquery-plugins", "jquery", "" ]
Is it alright to expect that the user using the back end will have Javascript enabled? I guess the answer I'll get is 'it depends on your target users'. I am developing a system for fun that will hopefully be used by other people. I would like to hear from other people developing back end systems, and what did they decide to do and why? SEO I'm not concerned with, and semantics aern't of as much importance.
Personally I would expect the failover, but there are circumstances (particularly low profile sites, intranets, e-learning content) where you can assume JS. Mostly you can even go with a simple "You require JS / This works better with JS" and I would consider that good enough, but there's a couple of instances where I would demand real failover: * .gov or other public service sites (legal requirements) * sites for web-tech companies (you need to demonstrate your ability to do this) * very high traffic sites (where the 3% of non-JS users becomes a high absolute number) * sites (or pages) for mobile devices (most of these haven't got JS reliably) In general, it's reasonably easy to provide *some* kind of noscript, so why not do it anyway?
if its for fun please go ahead and require javascript.
When writing a web backend for a system, is it important the code can still work without Javascript?
[ "", "javascript", "xhtml", "" ]
I am looking for template/generator libraries for C++ that are similar to eg. Ruby's Erb, Haml, PHP's Smarty, etc. It would be great if I it would sport some basic features like loops, if/else, int conversion to strings, etc. Parameter passing to template rendering engine is also important if I could pass all of them in a hash map instead of calling some function for each of parameters. Do you have any recommendations? I can see also the possibility of embedding languages like Lua, however I haven't found a templatizing library for that either.
A quick review of the mentioned project. <http://rgrz.tumblr.com/post/13808947359/review-of-html-template-engines-in-c-language> ## ClearSilver * Site: <http://www.clearsilver.net> * Project: <https://code.google.com/p/clearsilver/> * Group: <http://tech.groups.yahoo.com/group/ClearSilver> * License: New BSD License * Language: C * Last Update: Nov 28, 2011 * Last Release: 0.10.5 on July 12, 2007 * Document: Rich * Community: Medium (<10 discussion per month) ## Teng * Site: <http://teng.sourceforge.net> * Code: <http://teng.svn.sourceforge.net/teng/> * Group: <http://sourceforge.net/projects/teng/> * License: New BSD License * Language: C++ * Binding: php, python * Last Update: Mar 8, 2011 * Last Release: 2.1.1 on Mar 8, 2011 * Document: Rich * Community: Low (rare discussion since 2010) ## Templatizer * Site: <http://www.lazarusid.com/libtemplate.shtml> * Project: download only * Group: none * License: free to use * Language: C (low level)/C++ (interface) mixed * Last Update: unknown * Last Release: unknown * Document: none * Community: none ## HTML Template C++ * Site: <http://nulidex.com/code/docs/html_template/> * Project: <http://sourceforge.net/projects/htmltemplatec> * Group: <http://sourceforge.net/projects/htmltemplatec> * License: GPL * Language: C++ * Last Update: Mar 27, 2011 * Last Release: Beta 0.7.4, Mar 27, 2011 * Document: Medium * Community: none ## ctpp * Site: <http://ctpp.havoc.ru/en/> * Project: download only * Group: none * License: BSD License * Language: C++ with C API * Last Update: Oct 5, 2011 * Last Release: Version 2.7.2 on Oct 5, 2011 * Document: Rich * Community: none ## Wt * Site: <http://www.webtoolkit.eu/wt/> * Project: <http://www.webtoolkit.eu/wt/> * Group: <http://www.webtoolkit.eu/wt/community> * License: GPL and Commercial * Language: C++ * Last Update: Nov 29, 2011 * Last Release: 3.2.0 on Nov 29, 2011 * Document: Rich * Community: Low (rare activity) ## Flate * Site: <http://flate.dead-inside.org/> * Project: none * Group: none * License: LGPL v2.1 * Language: C * Last Update: Sep 4, 2010 * Last Release: 2.0 on Sep 4, 2010 * Document: Poor * Community: none ## Jinja2C++ * Site: <https://jinja2cpp.dev> * Project: <https://github.com/jinja2cpp> * Group: <https://gitter.im/Jinja2Cpp/Lobby> * Conan packages: <https://bintray.com/beta/#/flexferrum/conan-packages/jinja2cpp:flexferrum?tab=overview> * License: MPL-2.0 * Language: C++14/17 * Last Update: Oct 01, 2019 * Last Release: 1.0.0 on Oct 01, 2019 * Document: Moderate * Community: none
[Grantlee](https://github.com/steveire/grantlee) is a string template engine based on the Django template system. It is ported to C++/Qt.
C++ HTML template framework, templatizing library, HTML generator library
[ "", "c++", "template-engine", "" ]
I want place ads in my website, but I'm unsure about the common practices to place thes ads. By example, some cool asp.net articles sites shows ads in the middle of the article! So you read 2-3 paragraphs, read some ad, then finish the article reading... Another worry is about sabotage. One of mine customers get their Google adsense account banned, due some rival that clicked a lot of times in the goodle ads... there is some javascript techniques to block *[edit] the undesirable click flood! [/edit]*?
Google (unsurprisingly) knows a fair amount about where people look on a page. They have [an article about where to place ads](https://www.google.com/adsense/support/bin/answer.py?hl=en&answer=17954). Personally, I have the ads on my C# articles right at the bottom - by the time you get there, you've received all the benefit of the page already. That way I don't feel I'm disrupting my users. Then again, I'm not really trying to make significant money from them.
I find the ads in the middle of an article to be very annoying. Avoid this if possible. Place the ads on sides and top, but remember to leave plenty of space for contents too. Remember that >90% users will come for the contents anyway and will not care for the ads no matter where you put them. Those who want them, will spot them on the sides just as easily. But those who don't (and that's the vast majority) will just be very annoyed if the ads bother them - thus less likely to come back to your site.
What the best practices to place ads in a website?
[ "", "asp.net", "javascript", "html", "design-patterns", "seo", "" ]
I had a little bit of budget left at year end and I wanted to start a little skunk works project to display build status what everyone was working on (our team is aobut 10 folks all told). I am thinking to buy a 47" LCD HD TV and drive it from a small pc via a browser/.NET web application. I was going to build the software over the christmas break since we are closed for 2 weeks starting this Friday. I thought I would solicit advise/feedback on what other teams had done. a lot of the tools we use SVN, Mantis have RSS feeds that I was thinking to render. Is this the way to go ? Thanks for any feedback in advance.
A friend of mine is teaching himself how to work with Arduino so that he can build a computer-controlled LED sculpture for Burning Man next year. His first project? Using Arduino to control a little array of red and green LEDs so that everyone on his team can look up at it and see if the build is broken and who broke it. But really, unless that's a road you're interested in going down, in your case I'd write a simple WinForms app that used a FileSystemWatcher to check for changes in the RSS file, an XSLT transform to turn it into HTML, and a WebBrowser to display it. If you know XSLT and understand the contents of your RSS feed, that's about 2-3 hours of work tops.
Would it really benefit your team in any way? I'd rather brought something like a table hockey machine to make lunch time more fun.
Software to simplify displaying build status on a big visible monitor for team?
[ "", "c#", "asp.net", "rss", "" ]
How do I find areas of my code that run slowly in a C++ application running on Linux?
If your goal is to use a profiler, use one of the suggested ones. However, if you're in a hurry and you can manually interrupt your program under the debugger while it's being subjectively slow, there's a simple way to find performance problems. Execute your code in a debugger like gdb, halt it and each time look at the call stack (e.g. backtrace) several times. If there is some code that is wasting some percentage of the time, 20% or 50% or whatever, that is the probability that you will catch it in the act on each sample. So, that is roughly the percentage of samples on which you will see it. There is no educated guesswork required. If you do have a guess as to what the problem is, this will prove or disprove it. You probably have multiple performance problems of different sizes. If you clean out any one of them, the remaining ones will take a larger percentage, and be easier to spot, on subsequent passes. This *magnification effect*, when compounded over multiple problems, can lead to truly massive speedup factors. **Caveat**: Programmers tend to be skeptical of this technique unless they've used it themselves. They will say that profilers give you this information, but that is only true if they sample the entire call stack, and then let you examine a random set of samples. (The summaries are where the insight is lost.) Call graphs don't give you the same information, because 1. They don't summarize at the instruction level, and 2. They give confusing summaries in the presence of recursion. They will also say it only works on toy programs, when actually it works on any program, and it seems to work better on bigger programs, because they tend to have more problems to find. They will say it sometimes finds things that aren't problems, but that is only true if you see something *once*. If you see a problem on more than one sample, it is real. **P.S.** This can also be done on multi-thread programs if there is a way to collect call-stack samples of the thread pool at a point in time, as there is in Java. **P.P.S** As a rough generality, the more layers of abstraction you have in your software, the more likely you are to find that that is the cause of performance problems (and the opportunity to get speedup). **Added**: It might not be obvious, but the stack sampling technique works equally well in the presence of recursion. The reason is that the time that would be saved by removal of an instruction is approximated by the fraction of samples containing it, regardless of the number of times it may occur within a sample. Another objection I often hear is: "*It will stop someplace random, and it will miss the real problem*". This comes from having a prior concept of what the real problem is. A key property of performance problems is that they defy expectations. Sampling tells you something is a problem, and your first reaction is disbelief. That is natural, but you can be sure if it finds a problem it is real, and vice-versa. **Added**: Let me make a Bayesian explanation of how it works. Suppose there is some instruction `I` (call or otherwise) which is on the call stack some fraction `f` of the time (and thus costs that much). For simplicity, suppose we don't know what `f` is, but assume it is either 0.1, 0.2, 0.3, ... 0.9, 1.0, and the prior probability of each of these possibilities is 0.1, so all of these costs are equally likely a-priori. Then suppose we take just 2 stack samples, and we see instruction `I` on both samples, designated observation `o=2/2`. This gives us new estimates of the frequency `f` of `I`, according to this: ``` Prior P(f=x) x P(o=2/2|f=x) P(o=2/2&&f=x) P(o=2/2&&f >= x) P(f >= x | o=2/2) 0.1 1 1 0.1 0.1 0.25974026 0.1 0.9 0.81 0.081 0.181 0.47012987 0.1 0.8 0.64 0.064 0.245 0.636363636 0.1 0.7 0.49 0.049 0.294 0.763636364 0.1 0.6 0.36 0.036 0.33 0.857142857 0.1 0.5 0.25 0.025 0.355 0.922077922 0.1 0.4 0.16 0.016 0.371 0.963636364 0.1 0.3 0.09 0.009 0.38 0.987012987 0.1 0.2 0.04 0.004 0.384 0.997402597 0.1 0.1 0.01 0.001 0.385 1 P(o=2/2) 0.385 ``` The last column says that, for example, the probability that `f` >= 0.5 is 92%, up from the prior assumption of 60%. Suppose the prior assumptions are different. Suppose we assume `P(f=0.1)` is .991 (nearly certain), and all the other possibilities are almost impossible (0.001). In other words, our prior certainty is that `I` is cheap. Then we get: ``` Prior P(f=x) x P(o=2/2|f=x) P(o=2/2&& f=x) P(o=2/2&&f >= x) P(f >= x | o=2/2) 0.001 1 1 0.001 0.001 0.072727273 0.001 0.9 0.81 0.00081 0.00181 0.131636364 0.001 0.8 0.64 0.00064 0.00245 0.178181818 0.001 0.7 0.49 0.00049 0.00294 0.213818182 0.001 0.6 0.36 0.00036 0.0033 0.24 0.001 0.5 0.25 0.00025 0.00355 0.258181818 0.001 0.4 0.16 0.00016 0.00371 0.269818182 0.001 0.3 0.09 0.00009 0.0038 0.276363636 0.001 0.2 0.04 0.00004 0.00384 0.279272727 0.991 0.1 0.01 0.00991 0.01375 1 P(o=2/2) 0.01375 ``` Now it says `P(f >= 0.5)` is 26%, up from the prior assumption of 0.6%. So Bayes allows us to update our estimate of the probable cost of `I`. If the amount of data is small, it doesn't tell us accurately what the cost is, only that it is big enough to be worth fixing. Yet another way to look at it is called the [Rule Of Succession](http://en.wikipedia.org/wiki/Rule_of_succession). If you flip a coin 2 times, and it comes up heads both times, what does that tell you about the probable weighting of the coin? The respected way to answer is to say that it's a Beta distribution, with average value `(number of hits + 1) / (number of tries + 2) = (2+1)/(2+2) = 75%`. (The key is that we see `I` more than once. If we only see it once, that doesn't tell us much except that `f` > 0.) So, even a very small number of samples can tell us a lot about the cost of instructions that it sees. (And it will see them with a frequency, on average, proportional to their cost. If `n` samples are taken, and `f` is the cost, then `I` will appear on `nf+/-sqrt(nf(1-f))` samples. Example, `n=10`, `f=0.3`, that is `3+/-1.4` samples.) --- **Added**: To give an intuitive feel for the difference between measuring and random stack sampling: There are profilers now that sample the stack, even on wall-clock time, but *what comes out* is measurements (or hot path, or hot spot, from which a "bottleneck" can easily hide). What they don't show you (and they easily could) is the actual samples themselves. And if your goal is to *find* the bottleneck, the number of them you need to see is, *on average*, 2 divided by the fraction of time it takes. So if it takes 30% of time, 2/.3 = 6.7 samples, on average, will show it, and the chance that 20 samples will show it is 99.2%. Here is an off-the-cuff illustration of the difference between examining measurements and examining stack samples. The bottleneck could be one big blob like this, or numerous small ones, it makes no difference. [![enter image description here](https://i.stack.imgur.com/FpWuS.png)](https://i.stack.imgur.com/FpWuS.png) Measurement is horizontal; it tells you what fraction of time specific routines take. Sampling is vertical. If there is any way to avoid what the whole program is doing at that moment, *and if you see it on a second sample*, you've found the bottleneck. That's what makes the difference - seeing the whole reason for the time being spent, not just how much.
Use [Valgrind](http://en.wikipedia.org/wiki/Valgrind) with the following options: ``` valgrind --tool=callgrind ./(Your binary) ``` This generates a file called `callgrind.out.x`. Use the `kcachegrind` tool to read this file. It will give you a graphical analysis of things with results like which lines cost how much.
How do I profile C++ code running on Linux?
[ "", "c++", "linux", "profiling", "" ]
While researching the issue of [JSON vs XML](http://www.subbu.org/blog/2006/08/json-vs-xml), I came across [this question](https://stackoverflow.com/questions/325085/when-to-prefer-json-over-xml). Now one of the reasons to prefer JSON was listed as the ease of conversion in Javascript, namely with the `eval()`. Now this immediately struck me as potentially problematic from a security perspective. So I started doing some research into the security aspects of JSON and across this blog post about how [JSON is not as safe as people think it is](http://incompleteness.me/blog/2007/03/05/json-is-not-as-safe-as-people-think-it-is/). This part stuck out: > **Update:** If you are doing JSON 100% > properly, then you will only have > objects at the top level. Arrays, > Strings, Numbers, etc will all be > wrapped. A JSON object will then fail > to eval() because the JavaScript > interpreter will think it's looking at > a block rather than an object. This > goes a long way to protecting against > these attacks, however it's still best > to protect your secure data with > un-predictable URLs. Ok, so that's a good rule to start with: JSON objects at the top level should always be objects and never arrays, numbers or strings. Sounds like a good rule to me. Is there anything else to do or avoid when it comes to JSON and AJAX related security? The last part of the above quote mentions unpredictable URLs. Does anyone have more information on this, especially how you do it in PHP? I'm far more experienced in Java than PHP and in Java it's easy (in that you can map a whole range of URLs to a single servlet) whereas all the PHP I've done have mapped a single URL to the PHP script. Also, how exactly do you use unpredictable URLs to increase security?
The main security hole from the blog (CSRF), is not JSON specific. It's just as big a hole using XML instead. Indeed, it's just as bad with no asynchronous calls at all; regular links are just as vulnerable. When people talk about unique URLs, they generally DON'T mean <http://yourbank.com/json-api/your-name/big-long-key-unique-to-you/statement>. Instead, it's more common to make something else about the request unique; namely a value in the FORM post, or a URL parameter. Usually this involves a random token inserted into the FORM on the server side, and then checked when a request is made. The array/object thing is news to me: > Script-Tags: The attacker can embed a > script tag pointing at a remote server > and the browser will effectively > eval() the reply for you, however it > throws away the response and since > JSON is all response, you're safe. In that case, your site doesn't need to use JSON at all to be vulnerable. But yeah, if an attacker can insert random HTML into your site, you're toast.
There are a number of security attacks against JSON, especially XSRF. The vulnerability occurs when a web service uses cookies for authentication, and responds with a JSON array containing sensitive data in response to a GET request. If an attacker can trick a user who is logged into a service, naive-webapp.com, into visiting their site (or any site that embeds an IFRAME they control, e.g. via embedded ads) then they can insert a `<script>` tag with a SRC to the naive-webapp.com, and potentially steal the user's data. This depends on a javascript quirk with the JavaScript `Array` constructor like this: ``` <script> // Overload the Array constructor so we can intercept data var stolenArrays = []; var RealArray = Array; Array = function () { var arr = RealArray.apply(arguments); stolenArrays.push(arr); return arr; } </script> <!-- even though the attacker can't access the cookies, - he can cause the browser to send them to naive-webapp.com --> <script src="//naive-webapp.com/..."></script> <script> // now stolenArrays contains any data from the parsed JSON </script> ``` EcmaScript 5 has fixed the confusing behavior that caused `[]` to look up `Array` on the global object and many modern browsers are no longer susceptible to this attack. Incidentally, Oil is wrong about unpredictable URLs. Cryptographically secure random identifiers in URLs are a fine way to protect resources. Identity based security is not a panacea as Oil suggests. See <http://waterken.sourceforge.net/> for an example of a secure distributed application scheme based on cryptographically secure identifiers in URLs that does not require a concept of identity. EDIT: When considering JSON vs XML, you should be aware of XML specific attack vectors as well. [XXE](http://projects.webappsec.org/w/page/13247003/XML%20External%20Entities), XML External entities attacks, use crafted XML to access file system and network resources through the firewall. > ``` > <!DOCTYPE root > [ > <!ENTITY foo SYSTEM "file:///c:/winnt/win.ini"> > ]> > ... > <in>&foo;</in> > ``` > > The Application embeds the input (parameter "in", which contains the win.ini file) to the web service response.
JSON security best practices?
[ "", "javascript", "ajax", "security", "json", "" ]
I have a database which holds the residents of each house in a certain street. I have a 'house view' php web page which can display an individual house and residents when given the house number using 'post'. I also have a 'street view' web page which gives a list of houses. What I want to know is if you can have links on the street view which will link to the house view and post the house number at the same time without setting up a form for each? Regards
I assume that each house is stored in its own table and has an 'id' field, e.g house id. So when you loop through the houses and display them, you could do something like this: ``` <a href="house.php?id=<?php echo $house_id;?>"> <?php echo $house_name;?> </a> ``` Then in house.php, you would get the house id using `$_GET['id']`, validate it using `is_numeric()` and then display its info.
If you want to pass the data using POST instead of GET, you can do it using a combination of PHP and JavaScript, like this: ``` function formSubmit(house_number) { document.forms[0].house_number.value = house_number; document.forms[0].submit(); } ``` Then in PHP you loop through the house-numbers, and create links to the JavaScript function, like this: ``` <form action="house.php" method="POST"> <input type="hidden" name="house_number" value="-1"> <?php foreach ($houses as $id => name) { echo "<a href=\"javascript:formSubmit($id);\">$name</a>\n"; } ?> </form> ``` That way you just have one form whose hidden variable(s) get modified according to which link you click on. Then JavaScript submits the form.
How do you post data with a link
[ "", "php", "html", "" ]
What is the easiest way in Java to map strings (Java `String`) to (positive) integers (Java `int`), so that * equal strings map to equal integers, and * different strings map to different integers? So, similar to `hashCode()` but different strings are required to produce different integers. So, in a sense, it would be a hasCode() without the collision possibility. An obvious solution would maintain a mapping table from strings to integers, and a counter to guarantee that new strings are assigned a new integer. I'm just wondering how is this problem usually solved. Would also be interesting to extend it to other objects than strings.
This is impossible to achieve without any restrictions, simply because there are more possible Strings than there are integers, so eventually you will run out of numbers. A solution is only possible when you limit the number of usable Strings. Then you can use a simple counter. Here is a simple implementation where all (2^32 = 4294967296 different strings) can be used. Never mind that it uses lots of memory. ``` import java.util.HashMap; import java.util.Map; public class StringToInt { private Map<String, Integer> map; private int counter = Integer.MIN_VALUE; public StringToInt() { map = new HashMap<String, Integer>(); } public int toInt(String s) { Integer i = map.get(s); if (i == null) { map.put(s, counter); i = counter; ++counter; } return i; } } ```
Have a look at [perfect hashing](http://en.wikipedia.org/wiki/Perfect_hash_function).
Mapping of strings to integers
[ "", "java", "" ]
``` <form action="/Villa/Add" method="post"> <table> <tr> <td> Name: </td> <td> <%= Html.TextBox("name") %> <%= Html.ValidationMessage("Name") %> </td> </tr> <tr> <td> </td> <td> <input type="submit" value="Add" /> </td> </tr> </table> </form> ``` My form is above, how do I retrieve the values in my controller? Thanks a lot in advance! Hard to find the right material because of different Previews of MVC being released and being different.
This works for ASP.Net MVC Beta. ``` public ActionResult Add( string name ) { .... } or public ActionResult Add( FormCollection form ) { string name = form["Name"]; } or public ActionResult Add( [Bind(Prefix="")]Villa villa ) { villa.Name ... } ```
Have you tried something like this? Pseudocode... ``` public class VillaController : Controller { public ActionResult Add(string name) { // Code... } } ```
ASP.NET MVC Form Post
[ "", "c#", "asp.net-mvc", "" ]
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file. So I have this .py file that reads like: ``` starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 ``` Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way. I can also write a similar file very easily: ``` def writeoptions(directory): options="" options+="starting_length=%s%s"%(starting_length,os.linesep) options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep) options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep) ... open("%s%soptions.py"%(directory,os.sep),'w').write(options) ``` I want to pass a function as one of the parameters: ``` starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 def pippo(a,b): return a+b functionoperator=pippo ``` And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment. But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question. How do you get python to write down the code of a function, as it writes down the value of a variable?
``` vinko@mithril$ more a.py def foo(a): print a vinko@mithril$ more b.py import a import inspect a.foo(89) print inspect.getsource(a.foo) vinko@mithril$ python b.py 89 def foo(a): print a ```
You might also consider some other means of data persistence. In my own (astronomy) research, I've been experimenting with two different means of storing scripts for reproducibility. The first is to have them exclusively inside a subversion repository, and then have the job submission script automatically commit them. For instance, if you just wanted to do this in bash: ``` alias run_py='svn ci -m "Commit before running"; python2.5 $*' ``` and inside the script, have the output prefixed by the [current subversion revision number](http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.keywords.html) for that file, you'd have a record of each script that was run and what the input was. You could pull this back out of subversion as need be. Another, substantially less full-featured, means of tracking the input to a function could be via something like [LodgeIt](http://paste.pocoo.org/), a pastebin that accepts XML-RPC input and comes with Python bindings. (It can be installed locally, and has support for replying to and updating existing pastes.) But, if you are looking for a relatively small amount of code to be included, Vinko's solution using inspect should work quite well. Doug Hellman [covered the `inspect` module](http://www.doughellmann.com/PyMOTW/inspect/index.html) in his [Python Module of the Week](http://www.doughellmann.com/PyMOTW/) series. You could create a decorator that examines each option and argument and then prints it out as appropriate (I'll use `inspect.getargspec` to get the names of the arguments.) ``` import inspect from functools import wraps def option_printer(func): @wraps(func) def run_func(*args, **kwargs): for name, arg in zip(inspect.getargspec(func)[0], args) \ + sorted(kwargs.items()): if isinstance(arg, types.FunctionType): print "Function argument '%s' named '%s':\n" % (name, func.func_name) print inspect.getsource(func) else: print "%s: %s" % (name, arg) return func(*args, **kwargs) return run_func ``` This could probably be made a bit more elegant, but in my tests it works for simple sets of arguments and variables. Additionally, it might have some trouble with lambdas.
How do you get Python to write down the code of a function it has in memory?
[ "", "python", "artificial-intelligence", "" ]
I am currently doing a code review and the following code made me jump. I see multiple issues with this code. Do you agree with me? If so, how do I explain to my colleague that this is wrong (stubborn type...)? * Catch a generic exception (Exception ex) * The use of "if (ex is something)" instead of having another catch block * We eat SoapException, HttpException and WebException. But if the Web Service failed, there not much to do. Code: ``` try { // Call to a WebService } catch (Exception ex) { if (ex is SoapException || ex is HttpException || ex is WebException) { // Log Error and eat it. } else { throw; } } ```
The mantra is: * You should only catch exceptions if you can properly handle them Thus: * You should not catch general exceptions. --- In your case, yes, you should just catch those exceptions and do something helpful (probably not just eat them--you could `throw` after you log them). Your coder is using `throw` (not `throw ex`) which is *good*. This is how you can catch multiple, specific exceptions: ``` try { // Call to a WebService } catch (SoapException ex) { // Log Error and eat it } catch (HttpException ex) { // Log Error and eat it } catch (WebException ex) { // Log Error and eat it } ``` This is pretty much equivalent to what your code does. Your dev probably did it that way to avoid duplicating the "log error and eat it" blocks.
> I am currently doing a code review and the following code made me jump. I see multiple issues with this code. Do you agree with me? Not totally, see below. > * Catch a generic exception (Exception ex) In general, catching a generic exception is actually ok as long as you rethrow it (with throw;) when you come to the conclusion that you can't handle it. The code does that, so no immediate problem here. > * The use of "if (ex is something)" instead of having another catch block The net effect of the catch block is that only SoapException, HttpException, etc. are actually handled and all other exceptions are propagated up the call stack. I guess functionality-wise this is what the code is supposed to do, so there's no problem here either. However, from a aesthetics & readability POV I would prefer multiple catch blocks to the "if (ex is SoapException || ..)". Once you refactor the common handling code into a method, the multiple catch blocks are only slightly more typing and are easier to read for most developers. Also, the final throw is easily overlooked. > * We eat SoapException, HttpException and WebException. But if the Web Service failed, there not much to do. Here possibly lurks the biggest problem of the code, but it's hard to give advice without knowing more about the nature of the application. If the web service call is doing something that you depend on later then it's probably wrong to just log & eat the exceptions. Typically, you let the exception propagate to the caller (usually after wrapping it into e.g. a XyzWebServiceDownException), maybe even after retrying the webservice call a few times (to be more robust when there are spurious network issues).
Is this a bad practice to catch a non-specific exception such as System.Exception? Why?
[ "", "c#", ".net", "exception", "" ]
Is it possible to embed a DOS console in a Windows Form or User Control in C# 2.0? We have a legacy DOS product that my Windows app has to interact with, and it's been requested that an instance of the legacy product should run within the Windows application. At the moment, I'm using the user32.dll to locate the window that the DOS product is running in, minimising then maximising the window, and typing characters into the window. This isn't a very good solution to the problem, as it means my application has to store the window name in application settings, and requires that the user returns to the correct page of the DOS app before using the interaction function. EDIT: Some more information The legacy app needs to be visible to the user, but not in a separate window. I've tried TimothyP's answer and it works very well, but is it possible to achieve the same functionality, but with the DOS window visually embedded in a windows form or user control instead of popping up in it's own window? Preferably in a ShowDialog() way so that the user cannot interact with the app wile they are in 'Legacy Mode', so to speak.
It's possible to redirect the standard input/output of console/dos applications using the Process class. It might look something like this: ``` var processStartInfo = new ProcessStartInfo("someoldapp.exe", "-p someparameters"); processStartInfo.UseShellExecute = false; processStartInfo.ErrorDialog = false; processStartInfo.RedirectStandardError = true; processStartInfo.RedirectStandardInput = true; processStartInfo.RedirectStandardOutput = true; processStartInfo.CreateNoWindow = true; Process process = new Process(); process.StartInfo = processStartInfo; bool processStarted = process.Start(); StreamWriter inputWriter = process.StandardInput; StreamReader outputReader = process.StandardOutput; StreamReader errorReader = process.StandardError; process.WaitForExit(); ``` You can now use the streams to interact with the application. By setting processStartInfo.CreateNoWindow to true the original application will be hidden. I hope this helps.
Concerning your question on how to display the DOS app inside the Windows app. There are a few solutions. * The first one is to simply not display the DOS app (with CreateNoWindow) and "simulate" the UI of the DOS app in your Windows application by reading and writing to the streams. * The other solution would be to use the Win32API, get the Windows Handle (Whnd) of the Console/DOS application window and set its parent to your form. I'm currently not at home and since it has been ages since I've done this, I can't remember by heart how it is done. If I'm not mistaken you'll need to use the following Win32 API calls: + [FindWindow](http://www.pinvoke.net/default.aspx/user32/FindWindow.html) + [GetWindow](http://www.pinvoke.net/default.aspx/user32/GetWindow.html) + [SetParent](http://www.pinvoke.net/default.aspx/user32/SetParent.html) If I have some time left later today, I'll see if I can find better samples.
Embedding a DOS console in a windows form
[ "", "c#", "winforms", "c#-2.0", "dos", "" ]
What I'd like to do is provide a link on an intranet web page that will launch a telnet session and pass context information to a shell script that will take the user to a specific "green screen." This "pseudolink" might help show what I'm looking for: ``` <a href="telnet://<user>:<password>@<host>?showdetail%20123">detail for 123</a> ``` Part of this solution might be a suggested telnet client that could interact with browsers (perhaps through JavaScript) to accomplish this. Bonus points for obfuscating the credentials (but this is envisioned at this point to be a "read only" login). Thanks!
You cannot do this with a telnet: URL in most browsers (IE, FF, afaik). The telnet URL was originally described in RFC 1738, and it provided only information for a hostname, port, username and password. When you click on it, the browser will usually ask the OS for the default "telnet" handler, which is an external application that is run. Most modern telnet clients accept these parameters and put them to use. This architecture varies a bit between browsers, but the application is usually external. There was the occasional request in bugzilla.mozilla.org for support for a telnet plugin or a native telnet client, but it never got much attention. There might be inline solutions like a java applet, but I doubt they are called with a telnet: URL.
In my opinion, and I'd love to be proved wrong, you will have sandbox (security) problems. Check out [my question here which got little interest](https://stackoverflow.com/questions/376600), but I think it's basically the same thing: you cannot open external apps from the browser unless they are **already** associated with the mime-type, protocol, or something.
How do I launch a specific telnet-based app from a web browser?
[ "", "javascript", "html", "browser", "telnet", "" ]
I quite like Rails' database migration management system. It is not 100% perfect, but it does the trick. Django does not ship with such a database migration system (yet?) but there are a number of open source projects to do just that, such as django-evolution and south for example. So I am wondering, what database migration management solution for django do you prefer? (one option per answer please)
I've been using [South](http://south.aeracode.org/), but [Migratory](http://bitbucket.org/DeadWisdom/migratory/) looks promising as well.
[Migratory](http://bitbucket.org/DeadWisdom/migratory/) looks nice and simple.
What is your favorite solution for managing database migrations in django?
[ "", "python", "database", "django", "data-migration", "schema-migration", "" ]
So I purchased myself an iPhone ... everybody has one ... so I figured I'd **see** what the big deal was. To my surprise ... and overall skepticism ... I must say that I am **very** impressed with the iPhone. There's not any **real** magic going on here ... it just seems to be a **very clean and very easy** to use device. So now I'd like to take our internal project management application and create another user interface specifically targeted to iPhone. I googled some sites and most of them seem very kool-aidish, not real meat or substance. I did see where you can use some additional Html attributes to get certain things to appear iPhonish as well as a User Interface library to help out with the rendering. Do you know of any good sites or having any recommendations for getting started creating an iPhone web user interface using ASP.NET? Is there any references out there that explain all the the Html tricks or syntax you can use that the iPhone/Safari will recognize?
If you are talking about webpages, yes it can be done. See Aaron Rocks post here:[Rock the iPhone with ASP.NET MVC](http://weblogs.asp.net/aaronlerch/archive/2008/06/08/rock-the-iphone-with-asp-net-mvc.aspx) (via [Scott Hanselman](http://www.hanselman.com/blog/TheWeeklySourceCode28IPhoneWithASPNETMVCEdition.aspx)) He's using MVC for it. I've yet to try it, but it looks good. Hope this helps. **EDIT:** The [MVC 4 roadmap](http://aspnet.codeplex.com/wikipage?title=ASP.NET%20MVC%204%20RoadMap) indicates that MVC 4 should have support for Mobile views.
The apple [developer site](http://developer.apple.com/webapps/) is the best starting point. You don't need to use a mac for development if you're just doing a web app and you're happy with a browser based interface. I don't use ASP.NET myself, however there should be nothing special about using it for this, you just need to follow the guidelines for the HTML / javascript interface so it should be no different than using any other javascript library.
What can I do to optimize my web page for a mobile phone, specifically the iPhone?
[ "", "c#", "asp.net", "iphone", "" ]
I have a script that forces a download and I make a call to this via Javascript. However, the dialog box doesn't pop up, here is the download.php script: ``` header("Pragma: public"); // required header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); // required for certain browsers header("Content-Type: $ctype"); // change, added quotes to allow spaces in filenames, by Rajkumar Singh header("Content-Disposition: attachment; filename=\"".basename($properFilename)."\";" ); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($filename)); readfile("$filename"); exit(); ``` Here is the Javascript (using JQuery): ``` ///force download $.ajax({ type: "GET", url: "download.php", data: 'file=' + msg + '&properFilename=' + properFileName, success: function(msg){ window.location.href = msg; });//ajax ``` This redirects my browser to another page rather than showing the down dialog box. I know the JS variable msg contains the file with the right headers but I don't know what to do with it to get it to display the download dialog box. Thanks all p.s. Didn't know where to put this thread JS or PHP. ## EDIT: I have the right approach I am sure of that :) - A user comes to my site, they fill in a form and they press submit. After a few seconds their fle should show up in a dialog box that they can download. To do this: I make an AJAX call to get the file and download it. I use the PHP script to send the headers. Now all I need is a way to get the dowload dialog box to show up!!
It's not showing the dialog box for the very fact that its an Ajax call. ``` window.location.href = msg; ``` Thats what's redirecting you. I don't think you need an ajax call here, just call the page normally with an href link. **edit** If you want the form to submit and show the dialog box for the download, do this: ``` <script> function showDialogBox(form) { form.submit(); window.location.href = "/download.php?file=XXX&properFilename=XXX"; } </script> <form onsubmit="showDialogBox(this);"> </form> ```
If it full download.php script I can't find in it variable $file (only a $filename) - but in JS you send a $file variable. Second: something wrong in JS - why you use such variable name `msg` in `data:` and in `success:`?
Pushing Headers and AJAX
[ "", "php", "ajax", "http-headers", "" ]
I'm developing an application which currently have hundreds of objects created. Is it possible to determine (or approximate) the memory allocated by an object (class instance)?
You could use a memory profiler like .NET Memory Profiler (<http://memprofiler.com/>) or CLR Profiler (free) (<http://clrprofiler.codeplex.com/>)
A coarse way could be this in-case you wanna know whats happening with a particular object ``` // Measure starting point memory use GC_MemoryStart = System.GC.GetTotalMemory(true); // Allocate a new byte array of 20000 elements (about 20000 bytes) MyByteArray = new byte[20000]; // Obtain measurements after creating the new byte[] GC_MemoryEnd = System.GC.GetTotalMemory(true); // Ensure that the Array stays in memory and doesn't get optimized away GC.KeepAlive(MyByteArray); ``` process wide stuff could be obtained perhaps like this ``` long Process_MemoryStart = 0; Process MyProcess = System.Diagnostics.Process.GetCurrentProcess(); Process_MemoryStart = MyProcess.PrivateMemorySize64; ``` hope this helps ;)
How much memory does a C#/.NET object use?
[ "", "c#", ".net", "object", "memory", "profiling", "" ]
What is the best way to store instances of a class to file/database? We have a base class called Command and loads of derived classes. Users create instances of these classes by adding commands to a graphical designer where they can configure them. (Set the properties). We then need a way to store these "commands" to a file without losing any information. One idea was to use db4o, but the GPL license is not acceptable for this project. Any suggestions or code samples? Update: (In order to "de-blurryfie" my question :p) The generated code might look something like: ``` command[i++] = new DelayInSecondsCommand(2); command[i++] = new DaliRequestCommand(1, false, 254); command[i++] = new DaliRequestCommand(2, false, 254); command[i++] = new DaliRequestCommand(3, false, 254); command[i++] = new WaitInSecondsCommand(2); command[i++] = new DaliRequestCommand(1, false, 0); command[i++] = new DaliRequestCommand(2, false, 0); command[i++] = new DaliRequestCommand(3, false, 0); command[i++] = new JumpCommand(0); ``` But then with loads of different commands. I know it's possible with .NET serialization, altough I've never used it before, but I was wondering if there are better alternatives, like I said db4o seems nice but the license doesn't fit the project. Update 2: Thank you for the replies. I'll probably go with the serialization solution now, but I'll look into the other options as well. F.Y.I. data is stored in a SQL Compact database.
serialization does the trick! Serialization is nothing more than converting an object or a connected graph of objects into a stream of bytes (in order to persist the current state of the object). This can be a binary stream, XML or whatever. You don't have to do this conversion by your own since .Net has great support for serialization. Once you serialized an object, you are free to store this data to a file or database. Likewise, a stream of bytes representing a serialized object can be deserialized into an object which will have the same state as the original one. Btw: Once you have a serialized stream of bytes, you can apply some more functions on it, e.g. compression or encryption.
Are you trying to save the data in tables? or as blob/clob data? Since you mention files, I assume the latter: any of the standard .NET serializers should be fine - they all support inheritance etc. I'd consider for `DataContractSerializer`, as this combines the field-level support (like `BinaryFormatter`), and the assembly-independence of `XmlSerializer`. You could also consider more esoteric things like [protobuf-net](http://code.google.com/p/protobuf-net/). So: what is it you need to do that won't work under the standard serializers?
The best way to store class instances to a file/database
[ "", "c#", ".net", "serialization", "persistence", "object-oriented-database", "" ]
For example, java.io.File is just a concrete class. My replacement for it supports resolving Windows shortcuts. I need to preprocess constructor parameters to resolve possible .lnk files because the FileSystem object that does normalizing/canonicalision/resolving on the abstract paths is not accessible. The need for preprocessing rules out pure subclassing - can't do preprocessing before calling super(...) and File is immutable. So I extend File and use a delegate, overriding all of File's constructors and methods (calling super("") in all constructors). This works nicely, but is obviously not ideal - if File changes, I will not have overridden any new methods or constructors and this will expose the underlying empty abstract pathname. Am I missing something obvious? It seems like there should be a simpler/better way.
In the specific case you suggest it looks to me like you're better off with a separate factory class that makes the decisions about normalizing/canonicalision/resolving. Then you can just let File be File. Simpler.
If you really want the subclass route, you can cheat the requirement that a call to `super()` has to be the first line of a subclass constructor by placing your cleanup code outside of your class, or in a static block: ``` public class MyFile extends File { public MyFile(String path) { // static blocks aren't ideal, this is just for demo purposes: super(cleanPath(path)); } private static String cleanPath(String uncleanPath) {...} } ``` The factory pattern suggested by krosenvold is another good solution.
Using subclassing to replace a Java class that doesn't implement an interface
[ "", "java", "file", "delegates", "subclass", "" ]
The built-in `Math.Pow()` function in .NET raises a `double` base to a `double` exponent and returns a `double` result. What's the best way to do the same with integers? Added: It seems that one can just cast `Math.Pow()` result to (int), but will this always produce the correct number and no rounding errors?
A pretty fast one might be something like this: ``` int IntPow(int x, uint pow) { int ret = 1; while ( pow != 0 ) { if ( (pow & 1) == 1 ) ret *= x; x *= x; pow >>= 1; } return ret; } ``` Note that this does not allow negative powers. I'll leave that as an exercise to you. :) **Added:** Oh yes, almost forgot - also add overflow/underflow checking, or you might be in for a few nasty surprises down the road.
LINQ anyone? ``` public static int Pow(this int bas, int exp) { return Enumerable .Repeat(bas, exp) .Aggregate(1, (a, b) => a * b); } ``` usage as extension: ``` var threeToThePowerOfNine = 3.Pow(9); ```
How do you do *integer* exponentiation in C#?
[ "", "c#", "math", "integer", "exponentiation", "" ]