Friday, May 6, 2011

Unable to make an iterable decimal function in Python

I want to calculate the sum of

1/1 + 1/2 + 1/3 + ... + 1/30

I run the code unsuccessfully

import decimal
import math
var=decimal.Decimal(1/i)

for i in range(1,31):
   print(sum(var))

I get the error

'Decimal' object is not iterable

How can you make the iterable function in Python?

From stackoverflow
  • What you want is this:

    print(sum(decimal.Decimal(1) / i for i in range(1, 31)))
    

    The reason your code doesn't work, is that you try to iterate over one Decimal instance (through the use of sum). Furthermore, your definition of var is invalid. Your intention was probably something like this:

    var = lambda i: decimal.Decimal(str(1.0 / i))
    

    (Note the use of str, Decimal does not permit a floating point argument). But even then your loop would not work, because the use of sum inside the loop is inherently flawed. sum should be used after the loop has created all fractions that you want to sum. So that would be either of:

    print(sum(var(i) for i in range(1,31)))
    print(sum(map(var, range(1, 31))))
    

    For completeness, yet another way to do this is the following:

    one = decimal.Decimal(1)
    unitFractions = (one / i for i in itertools.count(1))
    print(sum(itertools.islice(unitFractions, 30)))
    

    However, as mentioned by gs, the fractions provides an alternative method that yields a fractional answer:

    >>> unitFractions = (fractions.Fraction(1, i) for i in itertools.count(1))
    >>> print(sum(itertools.islice(unitFractions, 30)))
    9304682830147/2329089562800
    
    Masi : Thank you for your answer!
  • You write:

    var=decimal.Decimal(1/i)
    

    which is weird since 'i' is not defined at that point. How about:

    one = decimal.Decimal( "1" )
    total = decimal.Decimal( "0" )
    for i in range( 1, 31 ):
        total += one / decimal.Decimal( "%d" % i )
    
  • Your mistake is, that decimal.Decimal(4) isn't a function, but an object.


    BTW: It looks like the Fractions (Python 2.6) module is what you really need.

    newacct : I agree about Fraction. Decimal is just supposed to represent finite base-10 decimals. It won't represent stuff like 1/3 precisely. So why use it? Fraction is what you want to do arithmetic with fractions.

Is there a way to enable both Objective-C mode and C++-mode at the same time in emacs?

I'm working with some Objective-C++ code (.mm files), and I'm curious if it's possible to get emacs to use proper syntax highlighting for both the Objective-C parts and the C++ parts. objc-mode and c++-mode are both major modes (built on top of cc-mode), so they can't be used at the same time.

Are there any minor modes or elisp hacks available to enable both Objective-C and C++ syntax highlighting at the same time?

From stackoverflow
  • I have not done this myself, but since all those modes are based around cc-mode it seems as though you could get the source code for objc-mode styles and c++-mode and combine them.

    Another possibility would be to try out an alternate objc-mode that it supposed to be more advanced, perhaps it would better take c++ into account:

    http://www.foldr.org/~michaelw/objective-c/

    (scroll to the end and look for obj-c-mode.el)

  • Here's a page that has information about running multiple major modes. As far as I know it's mostly used for doing web-type stuff where you might have several different languages in a single document, but It could probably work for others as well.

Zend Framework: right way to retrieve data from database

hello guys,

am working on a project with zend framework and i need your advise on the right way to fetch data from the database.

Am making use of Zend_Layout to load my template. The appropriate view is then loaded into the template.

On the template, there is supposed to be a section that displays data from the database (e.g Categories). Since i am using one template, the data will be displayed on every page requested irrespective of the controller or action called.

I know its not a good practise to fetch the data from the template and it wouldn't be a good idea to fetch the data from each action executed. I dont know if the right thing to do is to use helpers to fetch the data from the database, but wouldn't that go against the whole idea of MVC.

I need advise from you guys.

From stackoverflow
  • You haven't mentioned the option of using a Model class to fetch the data. That's the "M" in MVC. :-)

    A Model class is one that has an interface the View can use to request specific fragments of data. Inside the Model class, it may use a mix of using Zend_Db_Table methods, and also custom SQL queries (executed directly through Zend_Db_Adapter's query() method). Whatever works to get the data.

    The point is that a Model encapsulates all the logic needed to supply data in a format the View can use.

    See also

    War Coder : thanks very much for the response. actually when i said fetch data from the database, i meant through the Model class. So u are saying it is okay for me to call the appropriate Model class directly from the template.
    Bill Karwin : Yeah. My rule of thumb is that the View can call methods on the Model class, as long as the View treats the Model as effectively 'read-only'. Whether the Model has the data fetched from the database already, or has to run an SQL query at the time the View requests the information, is an implementation detail -- the View shouldn't avoid requesting data it needs based on that.

JSTL taglib URI is obsolete?

I've been checking out Spring MVC tutorial and copied this small JSP code from there:

<%@ page session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
    <head><title>Training, Inc.</title></head>
    <body>
        <h2><c:out value="${message}" /></h2>
    </body>
</html>

There is a string set for message and the c:out tag just prints literally

${message}

I was hitting my head for a while until I remembered an issue I had before and changed the taglib URI to:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

This solved my little problem

Some time ago I had a similar issue with XSLT transforming but in that case I had to change from http://java.sun.com/jstl/xml to http://java.sun.com/jsp/jstl/xml

According with this link my spring example should've worked just as I pasted from spring tutorial

The question is: Any of you guys know where is all this taglib URI confusion documented? Why in the some cases I got the last version from http://java.sun.com/jsp/jstl and in other ones I got the last version from http://java.sun.com/jstl

From stackoverflow
  • Yes, it's well known that the URI for taglibs changed between JSTL versions 1.0 and 1.1. If you happen to get examples that use the old standard and try to use them with the new taglib JAR you'll have this problem.

  • You can find a discussion about this issue here.

    victor hugo : Good link, thanks! My problem was so simple! Although I loaded servlet-api-2.5 dependency I never checked my webapp version in web.xml and I was using 2.3, doh! Thanks a lot!
  • It would be nice to put some reference on the old page with note: hey guys this is obsolate for 1.1...

    Igor

How to write a vb.net code to compile and execute C programs?

I'm trying to make a vb.net application that has got 2 textboxes, 2 radio buttons and 2 buttons(one named compile and the other 'run'). How can I load the content of a C/C++ file into the 1st textbox and on clicking the compile button, i should be able to show the errors or the C/C++ program in the 2nd textbox. On clicking Run, I should be able to show the output in the 2nd textbox. In short, I want to use the 2nd textbox as a terminal/console. The radio buttons are 4 selecting the language C or C++.

From stackoverflow
  • Why would you want to? What are you trying to do. Do you just want to execute the commandline compilers from a VB.NET Application ?

    If so have a look at the System.Diagnostics.Process.Start() method which allows you to execute another application.

  • I don't think writing a C++ compiler in VB.NET is something an absolute beginner should be undertaking. Writing a compiler is a very advanced field.

  • Look at this article - good examples on calling external programs (which is what your c++ compiler would be unless you intend to write your own) from VB.Net.

What are your strategies for using Expression Blend on complex, decoupled WPF applications?

I've been doing WPF applications with the MVVM pattern using Visual Studio, coding C# and XAML mostly by hand.

Now I've gotten up to speed with Expression Blend so that I can click together WPF applications quickly just using the GUI, which is very nice, much more control of the layout than fiddling around with all the XAML elements 80% of your time.

But it seems that my applications in Expression Blend are simpler and necessarily coupled, using events that are handled in the code behind, etc.

I find it hard to imagine how I would go from this simpler approach of Expression Blend to a decoupled MVVM application with Views, ViewModels, routed events and commands, etc. other than to just take my whole project into Visual Studio and rearrange it to the point that I couldn't really edit it visually anymore in Blend, but would be back to using Blend to create little pieces of XAML that I paste into Visual Studio.

For those of you who are working with more complex applications with Expression Blend, what are your strategies for keeping your projects decoupled in an MVVM way, yet at the same time structured "in the Expression Blend way" (where you can still see and edit whole parts of your application in a way that makes sense visually) so that you can continue to edit them in the Blend GUI as they scale?

From stackoverflow
  • I've been using Blend first and foremost as a rapid-prototyping tool. For this purpose, I really like it. In particular, I find it very helpful when I'm not sure how to set things up to get the layout/behavior that I want.

    I rarely edit my main project files directly in Blend. I find it creates markup that is unnecessarily complex or verbose. Also, as I become more familiar with WPF/XAML, I find myself using Blend less and less.

    Bryan Anderson : +1 for the second paragraph.
    Edward Tanguay : have you tried Blend 3? I find that its XAML is quite readable, sometimes an extra attribute here and there, but the worst it does is jack the margin on some control up to 500+ or so, but other than that, I really enjoy having my Views editable in Blend so I can change the properties in the GUI, especially with the property search feature, it is almost always faster in Blend
    Daniel Pratt : @Edward: If it's beta and it's from Microsoft, safe bet that I've tried it ;-) I actually like Blend quite a bit. It's slick and for some tasks it's almost invaluable. The thing is...day to day XAML for me is layout, and generally I find that, for layout, less is more. I find that I have to do more work in Blend, removing all the extraneous property assignments, to get the behavior/layout I want. Also, when doing a purely data-driven layout, it can be difficult to see or change the layout in the designer.
  • I have not been able to successfully use Blend end to end for that.

    I find in the general case, it's faster to edit xaml by hand in VS (exception would include anything with non-standard brushes for example). Blend is very click-happy, and it's not really fast to top it off.

    Another area where Blend is really useful is creating styles/templates from existing controls.

    Other than that, I'm not sold yet. Its capabilities drop when using code-instantiated datacontexts so it's no help there, and it tends to generate useless markup, static sizes and such, which I really don't like.

  • Blend is great for giving you an idea about how things can be done, but the xaml it makes is terrible and tightly coupled. As you learn the xaml side of things better you'll find it's much faster to just write the xaml than use Blend. Until you get to that point you can make your changes in Blend but then you should refactor the xaml it creates to make it less tightly coupled and take out the extraneous UI elements.

  • I have been using Blend for the UI of my projects since version 1. Being that my goal is to fully integrate the designer to the project, I have plowed through whatever gets in the way of this goal. While not being aware of MVVM for some time now, I naturally arrived at the same conclusion, and have been making ViewModels without knowing there was a pattern for them. Now with the help of others that are working towards MVVM, it's getting better all the time. I have now developed 3 applications with rich UI and functionality where all the UI was done in Blend. Read Josh Smith's MSDN article, look at Jason Dolinger's work, and Karl Shifflett's work to mention just a few.

    Look closely at using ICommand, INotifyPropertyChanged, the ObservableCollections.

    Also, look for how you can manipulate controls from your ViewModel. As an example, there is ICollectionView. Assume that you have a list of animals, and you have a set of types that you want to filter them by (birds, mammals, etc.)

    By using ICommand and ICollectionView, you could expose enough control where a designer could construct a listbox to show the animals, and a menu to show the filter list. There is enough functionality in ICollectionView to know what the current selection is, and if you had ICommand-based commands for "SortByBird", "SortByMammal", etc then when the designer made the menu, it (assuming the window's context was your ViewModel for this window) would supply the designer with the proper options to bind to.

    I am currently working with another team at my company explaining how my projects have been set up, and they are responding positively to the new role of the designer using Blend.

    Edward Tanguay : those sound like good directions to go (I'll check out ICollectionView), do you have some public examples of this application structure? I have found many MVVM examples which create little theoretical WPF samples (http://tanguay.info/web/index.php?pg=notesItems&id=28) and some MVVM examples that show how to create a WPF application but they don't take Blend into effect. Please post links if you have them, thanks.
  • I'm a little late to this party, but hope that someone can still respond. I've yet to find a search result that outlines the process for drawing a line between the designer and programmer. The first part of it is MVVM so there isn't any coupling between the GUI and the underlying "business logic", and I'm working hard on learning that right now. The other part that I haven't seen anyone write about is, how do you actually go about designing a project in Blend so that the developer can basically give you a GUI DLL of sorts, and then your application's GUI magically changes?

    Here's what I'm looking for -- the developer writes his code as usual, and also writes a very basic GUI that proves everything works as expected. Meanwhile, the designer is creating his cool little GUI with all of the usability features people have come to expect. Now, the developer can run his application with his GUI, but then can also switch to the designer's GUI on the fly.

    I guess if it can't be done on the fly, does that mean in the ideal case that the developer would have his VS solution include the XAML from the Blend solution? Then in App.xaml just reference a different start file?

    Dave : I also didn't mention the importance of testability, but I think this topic has been well-covered in several posts.

getting a Webkit executeSql transaction to return a value

How can I get the following JavaScript to return row so I can access it outside the transaction? All of Apple's example code seems to have HTML written to the browser within the transaction instead of ever passing data back to a calling function.

Along the lines of:

function getData() {
  db.transaction(function(tx) {
    tx.executeSql("SELECT id FROM table LIMIT 1", [], function(tx, result) {
      row = result.rows.item(0);
    }, function(tx, error) {
    });
  });

  return row;
}

Is this even possible? Can the Webkit storage API be set to synchronous instead of asynchronous execution?

From stackoverflow
  • I think you want to create a closure here as values are being garbage collected/moved away from the scope chain before you can access them. Pass row to a closure for access later or to some other function that can handle the value while it's still in scope.

    More info: Working With Closures

  • Can the Webkit storage API be set to synchronous instead of asynchronous execution?

    as far as I know, Webkit implements only asynchronous API of Web storage database API. There is no way to make it synchronous. Google Gears database API is synchronous.

  • I wrote an example of this and other SQL transactions at: http://wecreategames.com/blog/?p=219

    You have to do the WebKit executeSql calls in an asynchronous style. To get around this, you should have your:

    function(tx, error) {
    }
    

    execute something to update your data. Something like:

    function(tx, results) {
       console.log("Results returned: "+results.rows.length);
       for (var i=0; i<results.rows.length; i++) {
          var row = results.rows.item(i);
          document.getElementById('latestUpdated').innerHTML = row;
       } 
    }
    

    Notice that the second variable into the function isn't an error, it's the results.

    I put in a for loop to show that there could be multiple results returned (probably not with that SQL statement, though) -- so hopefully you see the utility of it.