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.

MVP dependency injection

using MVP, what is the normal order of construction and dependency injection.

normally you create a presenter for each view and pass the view into the presenter on constructor. But what if you have:

  1. A Service that multiple views need to listen to events on.
  2. Multiple views all pointing to the same data model cache.

can someone display a normal flow of info from a user click to data coming back in a service from a server.

From stackoverflow
  • Here is what I do:

    First, I define theses interfaces:

    public interface IView<TPresenter>
    {
        TPresenter Presenter { get; set; }
    }
    
    public interface IPresenter<TView, TPresenter>
        where TView : IView<TPresenter>
        where TPresenter : IPresenter<TView, TPresenter>
    {
        TView View { get; set; }
    }
    

    Then this abstract presenter class:

    public abstract class AbstractPresenter<TView, TPresenter> : IPresenter<TView, TPresenter>
        where TView : IView<TPresenter>
        where TPresenter : class, IPresenter<TView, TPresenter>
    {
        protected TView view;
    
        public TView View
        {
            get { return this.view; }
            set
            {
                this.view = value;
                this.view.Presenter = this as TPresenter;
            }
        }
    }
    

    The view is injected via a property, instead of the constructor, to allow the bi-directional affection in the setter. Notice that a safe cast is needed...

    Then, my concrete presenter is something like :

    public class MyPresenter : AbstractPresenter<IMyView, MyPresenter>
    {
        //...
    }
    

    Where IMyView implements IView. A concrete view type must exists (e.g. MyView), but it's the container that resolves it:

    1. I register MyPresenter type as itself in the container, with a transient behavior.
    2. I register MyView as an IMyView in the container with a transient behavior.
    3. I then asks for a MyPresenter to the container.
    4. Container instanciate a MyView
    5. It instanciates a MyPresenter
    6. It inject the view into the presenter through the AbstractPresenter.View property.
    7. The setter code completes the bi-directional association
    8. The container returns the couple Presenter/View

    It allows you to inject other dependencies (services, repos) into both your view and your presenter. But in the scenario you described, I recommend you to inject services and caches into the presenter, instead of the view.

  • In WinForms, I prefer a simple approach. Usually you're dealing with a few UserControls on a design surface -- make these your view classes. .NET creates the control hierarchy for you (via InitializeComponent). If you use the Passive View pattern, each view then instantiates it's presenter. (You can do this either directly or by asking an IOC container.) Use constructor injection to pass a reference to the view's interface to the presenter's constructor. The presenter can then wire itself up to view events. Repeat the process for the model: the presenter instantiates a model and wires up to its events. (In this case you don't need the constructor injection since Passive View says the presenter keeps a reference to the model, not vice versa.)

    The only nit I've found with this approach is properly managing lifetimes of the model and presenter. You want to keep the view as simple as possible, so you probably don't want it maintaining a reference to the presenter. However, that means you've got this presenter object hanging around with event handlers tied to your view. This setup prevents your view from being garbage collected. One solution is to have your view publish an event that indicates it's closing. The presenter would receive the event and remove both its model and view subscriptions. The objects in your web are now properly dereferenced and the garbage collector can go about its work.

    You wind up with something like the following:

    public interface IView
    {
       ...
       event Action SomeEvent;
       event EventHandler Disposed;
       ...
    }
    
    // Note that the IView.Disposed event is implemented by the 
    // UserControl.Disposed event. 
    public class View : UserControl, IView
    {
       public event Action SomeEvent;
    
       public View()
       {
          var presenter = new Presenter(this);
       }
    }
    
    public interface IModel
    {
       ...
       event Action ModelChanged;
       ...
    }
    
    public class Model : IModel
    {
       ...
       public event Action ModelChanged;
       ...
    }
    
    public class Presenter
    {
       private IView MyView;
       private IModel MyModel;
    
       public Presenter(View view)
       {
          MyView = view;
          MyView.SomeEvent += RespondToSomeEvent;
          MyView.Disposed += ViewDisposed;
    
          MyModel = new Model();
          MyModel.ModelChanged += RespondToModelChanged;
       }
    
       // You could take this a step further by implementing IDisposable on the
       // presenter and having View.Dispose() trigger Presenter.Dispose().
       private void ViewDisposed(object sender, EventArgs e)
       {
          MyView.SomeEvent -= RespondToSomeEvent;
          MyView.Disposed -= ViewDisposed;
          MyView = null;
    
          MyModel.Modelchanged -= RespondToModelChanged;
          MyModel = null;
       }
    }
    

    You can decouple this example a step further by using IOC and asking your IOC container for implementations of IModel (in the Presenter class) and IPresenter (in the View class).

Direct3D9ex and Direct3D10 resource sharing

It is possible, with the Direct3D9ex, to share resources between devices. Is it also possible to use those shared resources with Direct3D10 devices?

From stackoverflow
  • Someone correct me if I'm wrong but, No and No.

    What is you intend? Have a static texture on two devices? If so, it's easily achieved by loading the same texture twice into the two different default pools. Just be aware that modifying one won't necessarily modify the other.

    If you are trying to share a managed texture on two devices, I don't think this is achievable with any sort of control. SLI might do it behind the scene but you won't have any control over it.

    If you want to use a texture generated from one device on the other device explicitly, you will have to download it from the source device and upload it to the target device every frame. This will be slow but if absolutely necessary it can be done that way.

  • You can share Direct3D9 resources between devices or processes.

    Feature Summary (Direct3D 9 for Windows Vista) - Sharing Resources

    Similar technique works for Direct3D10 resources (you also specify the sharing handle).

    This GameDev.net topic discusses sharing between D3D9Ex and D3D10 in detail. The conclusions in that topic seems to be that while based on documentation it should be possible (with some limitations), in practice it does not work at all (perhaps the restrictions are that severe they prevent any practical usage scenario?)

  • Yes, you can share resources between D3D9Ex and D3D10 devices using the technique described here:

    Feature Summary (Direct3D 9 for Windows Vista) - Sharing Resources

    Note that GPU access to shared surfaces is not synchronized - for example, if you render to the same render surface on two devices simultaneously, expect all sorts of corruptions and races.

    To work around it, make sure one device is completed rendering to the shared surface before the other one uses it. One option is event query (IDirect3DQuery9) , the other is doing a StretchRect to a small surface and Lock it (if Lock succeeds, GPU completed all previous work)

Is there a function that returns the ASCII value of a character? (C++)

I need a function that returns the ASCII value of a character, including spaces, tabs, newlines, etc...

On a similar note, what is the function that converts between hexadecimal, decimal, and binary numbers?

From stackoverflow
  • char c;
    int ascii = (int) c;
    

    A char is an integer, no need for conversion functions.

    Maybe you are looking for functions that display integers as a string - using hex, binary or decimal representations?

  • If you want to get the ASCII value of a character in your code, just put the character in quotes

    char c = 'a';
    
  • You don't need a function to get the ASCII value -- just convert to an integer by an (implicit) cast:

    int x = 'A';  // x = 65
    int y = '\t'; // x = 9
    

    To convert a number to hexadecimal or decimal, you can use any of the members of the printf family:

    char buffer[32];  // make sure this is big enough!
    sprintf(buffer, "%d", 12345);  // decimal: buffer is assigned "12345"
    sprintf(buffer, "%x", 12345);  // hex: buffer is assigned "3039"
    

    There is no built-in function to convert to binary; you'll have to roll your own.

  • You may be confusing internal representation with output. To see what value a character has:

    char c = 'A';
    cout << c << " has code " << int(c) << endl;
    

    Similarly fo hex valuwes - all numbers are hexadecimal numbers, so it's just a question of output:

    int n = 42;
    cout << n << " in hex is " << hex << n << endl;
    

    The "hex" in the output statement is a C++ manipulator. There are manipulators for hex and decimal (dec), but unfortunately not for binary.

  • As far as hex & binary - those are just representations of integers. What you probably want is something like printf("%d",n), and printf("%x",n) - the first prints the decimal, the second the hex version of the same number. Clarify what you are trying to do -

API Documentation Manager/Aggregator

Hi,

I've been using vim and c++/php for university and personal projects.

Lately, while programming, I've been finding myself browsing (the internet) a lot through the generated APIs of the libraries/frameworks/languages I use.

I consider this a waste of time, because, as I don't like too many tabs open in my browser, I tend to close as many tabs as I can closing (most of the times, without realizing) the API documentation pages.

Also, as I write with vim, I don't like to take my hand out of the keyboard, and browsing the internet does exactly that (I tried the firefox mouse-less addon and I didn't quite like it).

I know that a lot of IDEs does exactly this and as you type, but it does not include all the frameworks nor libraries. For instance, QtCreator includes the Qt framework, but not the libQGLViewer api documentation nor the openmesh api documentation (or maybe I don't know how to add them).

Also, I know that vim can use exhuberant-ctags to find/complete method declarations, but it doesn't work with the documentation (or I can't make it work with the documentation).

So, I was wondering if you know of an application or tool that "aggregates" api documentations where I can quicly find classes/methods documentations? Maybe with a search option where I can write the name of the class and it displays it's documentation?

From stackoverflow
  • I know that with DOxygen, there is a search box with the generated documentation

Split a html into words

Assume I have the following string:

Hellotoevryone<img height="115" width="150" alt="" src="/Content/Edt/image/b4976875-8dfb-444c-8b32-cc b47b2d81e0.jpg" />Iamsogladtoseeall.

This string represents a sequence of chars that are not separated by a space, in this string there is also an html image inserted. Now I want to separate the string into words , each having the length of 10 chars, so the aoutput should be:

1)Hellotoevr
2)yone<img height="115" width="150" alt="" src="/Content/Edt/image/b4976875-8dfb-444c-8b32-cc b47b2d81e0.jpg" />Iamsog
3)ladtoseeal
4)l.

So the idea is to keep any html tag content as 0 length char.

I had written such a method, but it does not take into consideration the html tags:

public static string EnsureWordLength(this string target, int length)
{
    string[] words = target.Split(' ');
    for (int i = 0; i < words.Length; i++)
        if (words[i].Length > length)
        {
            var possible = true;
            var ord = 1;
            do
            {
                var lengthTmp = length*ord+ord-1;
                if (lengthTmp < words[i].Length) words[i] = words[i].Insert(lengthTmp, " ");
                else possible = false;
                ord++;
            } while (possible); 

        }

    return string.Join(" ", words);
}

I would like to see a code that performs the splitting as I described.Thanks.

From stackoverflow
  • This following code will handle the case you provided, but will break for anything more complex. Also, since you did not specify how it should handle long-form tags with inner text or HTML, it treats all tags as short-form ones (Run the code to see what I mean).

    Works with this input:

    Hellotoevryone<img height="115" width="150" alt="" src="/Content/Edt/image/b4976875-8dfb-444c-8b32-cc b47b2d81e0.jpg" />Iamsogladtoseeall.
    Hellotoevryone<img src="/Content/Edt/image/b4976875-8dfb-444c-8b32-cc b47b2d81e0.jpg" />Iamsoglad<img src="baz.jpeg" />toseeall.
    Hello<span class="foo">toevryone</span>Iamso<em>glad</em>toseeallTheQuickBrown<img src="bar.jpeg" />FoxJumpsOverTheLazyDog.
    Hello<span class="foo">toevryone</span>Iamso<em>glad</em>toseeall.
    Loremipsumdolorsitamet,consecteturadipiscingelit.Nullamacnibhelit,quisvolutpatnunc.Donecultrices,ipsumquisaccumsanconvallis,tortortortorgravidaante,etsollicitudinipsumnequeeulorem.
    

    Breaks with this input (note the incomplete tag):

    Hellotoevryone<img height="115" width="150" alt="" src="/Content/Edt/image/b4976875-8dfb-444c-8b32-cc b47b2d81e0.jpg" /Iamsogladtoseeall.
    
    using System;
    using System.Text.RegularExpressions;
    using System.IO;
    using System.Collections.Generic;
    
    public static class CustomSplit {
      public static void Main(String[] args) {
        if (args.Length > 0 && File.Exists(args[0])) {
          StreamReader sr = new StreamReader(args[0]);
          String[] lines = sr.ReadToEnd().Split(new String[]{Environment.NewLine}, StringSplitOptions.None);
    
          int counter = 0;
          foreach (String line in lines) {
            Console.WriteLine("########### Line {0} ###########", ++counter);
            Console.WriteLine(line);
            Console.WriteLine(line.EnsureWordLength(10));
          }
        }
      }
    
    }
    
    public static class EnsureWordLengthExtension {
      public static String EnsureWordLength(this String target, int length) {
        List<List<Char>> words = new List<List<Char>>();
    
        words.Add(new List<Char>());
    
        for (int i = 0; i < target.Length; i++) {
          words[words.Count - 1].Add(target[i]);
    
          if (target[i] == '<') {
            do {
              i++;
              words[words.Count - 1].Add(target[i]);
            } while(target[i] != '>');
          }
    
          if ((new String(words[words.Count - 1].ToArray())).CountCharsWithoutTags() == length) {
            words.Add(new List<Char>());
          }
        }
    
        String[] result = new String[words.Count];
        for (int j = 0; j < words.Count; j++) {
          result[j] = new String(words[j].ToArray());
        }
    
        return String.Join(" ", result);
      }
    
      private static int CountCharsWithoutTags(this String target) {
        return Regex.Replace(target, "<.*?>", "").Length;
      }
    }
    
  • Here's a regular expressions solution matching your requirements. Bear in mind that this will probably not work if you decide to alter your requirements in the slightest bit, which is faithful to the well known quote here.

    using System.Text.RegularExpressions;
    
    string[] samples = {
        @"Hellotoevryone<img height=""115"" width=""150"" alt="""" src=""/Content/Edt/image/b4976875-8dfb-444c-8b32-cc b47b2d81e0.jpg"" />Iamsogladtoseeall.",
        "Testing123Hello.World",
        @"Test<a href=""http://stackoverflow.com"">StackOverflow</a>",
        @"Blah<a href=""http://stackoverflow.com"">StackOverflow</a>Blah<a href=""http://serverfault.com"">ServerFault</a>",
        @"Test<a href=""http://serverfault.com"">Server Fault</a>", // has a space, not matched
        "Stack Overflow" // has a space, not matched
    };
    
    // use these 2 lines if you don't want to use regex comments
    //string pattern = @"^((?:\S(?:\<[^>]+\>)?){1,10})+$";
    //Regex rx = new Regex(pattern);
    
    // regex comments spanning multiple lines requires use of RegexOptions.IgnorePatternWhitespace
    string pattern = @"^(               # match line/string start, begin group
                        (?:\S           # match (but don't capture) non-whitespace chars
                        (?:\<[^>]+\>)?  # optionally match (doesn't capture) an html <...> tag
                                        # to match img tags only change to (?:\<img[^>]+\>)?
                        ){1,10}         # match upto 10 chars (tags don't count per your example)
                        )+$             # match at least once, and match end of line/string
                        ";
    Regex rx = new Regex(pattern, RegexOptions.IgnorePatternWhitespace);
    
    foreach (string sample in samples)
    {
        if (rx.IsMatch(sample))
        {
            foreach (Match m in rx.Matches(sample))
            {
                // using group index 1, group 0 is the entire match which I'm not interested in
                foreach (Capture c in m.Groups[1].Captures)
                {
                    Console.WriteLine("Capture: {0} -- ({1})", c.Value, c.Value.Length);
                }
            }
        }
        else
        {
            Console.WriteLine("Not a match: {0}", sample);
        }
    
        Console.WriteLine();
    }
    

    Using the samples above, here's the output (numbers in parentheses = string length):

    Capture: Hellotoevr -- (10)
    Capture: yone<img height="115" width="150" alt="" src="/Content/Edt/image/b49768
    75-8dfb-444c-8b32-cc b47b2d81e0.jpg" />Iamsog -- (116)
    Capture: ladtoseeal -- (10)
    Capture: l. -- (2)
    
    Capture: Testing123 -- (10)
    Capture: Hello.Worl -- (10)
    Capture: d -- (1)
    
    Capture: Test<a href="http://stackoverflow.com">StackO -- (45)
    Capture: verflow</a> -- (11)
    
    Capture: Blah<a href="http://stackoverflow.com">StackO -- (45)
    Capture: verflow</a>Bla -- (14)
    Capture: h<a href="http://serverfault.com">ServerFau -- (43)
    Capture: lt</a> -- (6)
    
    Not a match: Test<a href="http://serverfault.com">Server Fault</a>
    
    Not a match: Stack Overflow
    

Securing WCF service using basicHttpBinding which supports streaming

My question is in regards to the best (aka "least painful") way to secure access to a WCF service that is only exposed to our company's internal users. The goal is to ensure that the service is only accessed via a single windows forms application that each of our users has installed. When the service is called, I want the service to be able to validate that it was called from the permitted application.

The service to be secured uses basicHttpBinding which supports streaming so I believe I am limited to Transport level security.

Below are simplified versions of the <bindings> and <services> sections from my service's config file.

<bindings>
  <basicHttpBinding>
    <binding name="Service1Binding" transferMode="Streamed"/>    
  </basicHttpBinding>
</bindings>

<services>
    <service name="WCFServiceSecurity.Service1" 
           behaviorConfiguration="WCFServiceSecurity.Service1Behavior">
    <endpoint address=""
              binding="basicHttpBinding"
              contract="WCFServiceSecurity.IService1"
              bindingConfiguration="Service1Binding"/>
     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  </service>
</services>

Can anyone offer some details as to what actions I would need to take in order to implement security on this service?

Note: I'm new to WCF and am not familiar with security at all, so let me know if I haven't provided enough detail.


UPDATE:
As suggested by marc_s, I'd like to secure the WCF service using some sort of username/password mechanism. This gives a little more direction towards an answer, but I'm still somewhat blurry on how to actually do this.

Because my service requires streaming to be enabled, I have to use basicHttpBinding and Transport level security (right?); further to that, the method contained in my service can only accept a Stream object.

Taking those constraints into consideration along with my preference to use username/password validation...

How should I modify my service's config file to force username/password credentials to be supplied?
How will my service validate the supplied credentials?
How will my client application pass credentials the service when making a call?
Will this require using SSL and, if so, will all client machines require a certificate as well?


UPDATE:
After explaining the trouble I've been having with securing this service to my boss, I was given the go-ahead to try the Windows Authentication route. Sadly, I've had no luck in implementing this type of authentication with my Streamed service (argh). After making the appropriate changes (as outlined here - the only exception being that my transferMode="Streamed") and accessing my service, I was presented with the following error:

"HTTP request streaming cannot be used in conjunction with HTTP authentication. Either disable request streaming or specify anonymous HTTP authentication."

I then stumbled upon the following quote here which offers some clarification:

"You can't do transport auth. with streaming. If you have to use HTTP request streaming, you'll have to run without security.
The way security works is:
WCF Client makes an http request to the Server.
The Server responds with something saying, "You aren't authorized, send me a basic/digest/etc credential."
The Client gets that response and resends it's message with the credentials t

From stackoverflow
  • There's a number of things you could do:

    • add a certificate to each and every machine that's allowed to use your service, and check for that certificate. That only allows you to exclude "unauthorized" machines - you cannot limit it to a specific application
    • same as above, but include the certificate embedded in your winforms app and send it from there (do not store it in the machine's certificate store)
    • require a username / password that only that particular app of yours knows about and can transmit to your service; e.g. someone else would not be able to present the appropriate credentials

    EDIT 2: OK, so the username/password approach seems to get out of hand.... what if you just have basic transport security (SSL) for basic protection, and then use the MessageContract to define header and body of your SOAP message, include a specific value in the header, and then just check for that presence of the element in the header in your service?

    Something like that:

    [DataContract]
    class YourRequestData
    {
     ...
    }
    
    [MessageContract]
    public class YourRequest
    {
      [MessageBodyMember]
      public YourRequestData bodyData { get; set; }
    
      [MessageHeader]
      public string AppThumbprint { get; set; }
    }
    

    And then on your server in your code just check for the presence and the validity of that AppThumbprint code:

    public Stream RequestStream(YourRequest request)
    {
      if(AppThumbprintIsValid(request.AppThumbprint))
      {
         .... begin your streaming
      }
    }
    

    That might end up being a lot easier than the username/password security scenario.

    Marc

    Steve Dignan : I'd like to avoid adding certificates to client machines since the users of the application change often. I'd like to implement the username/password method you mentioned but I'm not sure how I would transmit those values to the actual service. The method being exposed by the service has streaming enabled so I wouldn't be able to pass those values as parameters (due to the method signature restrictions in place for a streaming-enabled service); can you recommend a method for passing a un/pw combo to the service and authenticating from within the service?
    Steve Dignan : After I modify my service's config as above and run the service I get the error "BasicHttp binding requires that BasicHttpBinding.Security.Message.ClientCredentialType be equivalent to the BasicHttpMessageCredentialType.Certificate credential type for secure messages. Select Transport or TransportWithMessageCredential security for UserName credentials.". I thought a streaming-enabled endpoint required Transport level security? Also, in the tag, I think the binding value be basicHttpBinding instead of basicHttpConfiguration.
    Steve Dignan : Thanks for all your help Marc, but unfortunately I don't think this approach (EDIT 2) will work for my specific scenario. The service method being called must both accept and return a Stream. Your answer raises an interesting idea; I suppose I could inherit a Stream and decorate it with some un/pw properties; this Stream could be the input parameter of my service method (not overly secure, mind you). But given the apparent flexibility of WCF, I have to assume there is a better way... hmmmm.
  • If this is going to be an application that lives on the intranet it might be easiest to just create a new group in your Active Directory and only give members of that group the ability to use the service.

    You can add Authentication (using windows credentials) with something like this:

    <basicHttpBinding> 
     <security mode="TransportCredentialOnly"> 
      <transport clientCredentialType="Windows" /> 
     </security> 
    </basicHttpBinding>
    

    Could then Authorise by decorating the Interface to your services methods:

    <PrincipalPermission(SecurityAction.Demand, Role:="MyAppsUsers")> _ 
    Public Function MyMethod() As String Implements IService.MyMethod
    

    Heres a good link to Security in WCF. It has lots of How To's at the end (the one titled 'How To - Use basicHttpBinding with Windows Authentication and TransportCreditals' might be of use to you).
    Wcf Secruity

    [Disclaimer: I'm also new to WCF and haven’t done this exact case before so apologises if this is slightly off!]

    Steve Dignan : Since we are trying to ensure that the WCF service is only accessed from a single application, I don't think using windows credentials will do since those users could potentially call the service from outside of the application (correct me if I'm wrong). Supplying a username/password to the service seems like the way to go (from my limited experience). Thanks for the link to the WCF security guide, I'll also be looking at that to see what I can apply to my scenario.
  • Well, I found a lot of issues surrounding security/streaming while working on this problem. The hack (er...um...workaround) I finally ended up going with was to create a new DataContract that inherits MemoryStream and decorated it with a BaseStream property (for holding the data I want streamed) along with appropriate properties used for simple authentication.

    Here is the resulting DataContract:

    [DataContract]
    [KnownType( typeof( MemoryStream ) )] 
    public class StreamWithCredentials : MemoryStream
    {
        [DataMember]
        public Stream BaseStream { get; set; }
    
        [DataMember]
        public string Username { get; set; }
    
        [DataMember]
        public string Password { get; set; }
    }
    

    The above DataContract ends up being the input parameter of my service's method. The first action my service takes is to authenticate the supplied credentials against known valid values and to continue as appropriate.

    Now I do know that this is not the most secure option but my directive was to avoid using SSL (which I'm not even sure is possible anyway - as stated here) for this internal process.

    That being said, this was the best solution to the above stated problem I could come up with, hope this helps anyone else stricken with this issue.

    Thanks to all who responded.

  • If you want to use basicHttpBinding (for interop) you can only pass your credential at message level. So you have to set your security confiuguration to TransportWithMessageCredential. To do that you have to create a SSL channel, so you need a certificate at server side, and it's not necesary for a cliente to have one.

Background process in GAE

I am developing a website using Google App engine and Django 1.0 (app-engine-patch)

a major part of my program has to run in the background and change local data and also post to a remote url...

can sumone suggest an effective way of doin this...

From stackoverflow
  • Without using a third-party system, I think currently your only option is to use the cron functionality.

    You'd still be bound by the usual GAE script-execution-time limitations, but it wouldn't happen on a page load.

    There is plans for background processing, see this App Engine issue #6, and this roadmap update

  • I second dbr's recommendation of http://code.google.com/appengine/docs/python/config/cron.html (and hopes for better future approaches, such as the promised "task queues").

    Nevertheless I suspect that if you do indeed need major (as in CPU heavy) background processing, GAE may not be the most hospitable environment for that. You may want to consider running those heavy background tasks in other environments, and have them communicate with GAE proper e.g. via the "bulk load/download" APIs, see http://code.google.com/appengine/docs/python/tools/uploadingdata.html (and http://code.google.com/appengine/docs/python/tools/uploadingdata.html#Downloading_Data_from_App_Engine for the downloading part).

    Google's documentation only describes the usage of the command-line appcfg.py for these purposes (I can't find a proper documentation of the APIs it uses!), but, if you do need more programmatic usage of these APIs, it's not hard to evince them from appcfg.py's sources.

  • One option is the use the Remote API to access the datastore from another machine (either your own, or something like EC2) to do the processing. The downside to this is that you'll incur bandwidth costs for transferring the data, but you won't be limited to doing your operations in a bunch of 30-second chunks.

  • Check out The Task Queue Python API that was released a few days ago.

Django templates: Group items in Threes

Hi here guys. I have an odd problem with Django. I have a set of objects that Im looping through in a template as you would normally. However, I need to group the items in threes. The layout of the page goes like this:

Painting 1 - Painting 2 - Painting 3

D E S C R I P T I O N 1
D E S C R I P T I O N 2
D E S C R I P T I O N 3

Painting 4 - Painting - 5 Painting 6

D E S C R I P T I O N 4
D E S C R I P T I O N 5
D E S C R I P T I O N 6

etc etc

I cant quite figure out the best set of Django tags to do this really. It seems somewhat tricky. the {% cycle %} statement didnt quite help.

Unless of course, I do some java script hacking of some kind and leave Django out of this? There must be someway of saying "Put all the description divs after one another" or similar. Not sure how best to play with this ordering. Any thoughts? Cheers.

From stackoverflow
  • How's about something around these lines:

    {% for p in paintingss %}
        <div class="painting">whatever</div>
        {% if forloop.counter|divisibleby:"3" %}
            <br>
        {% endif %}
    {% endfor %}
    

    Will this do you good?

  • Yuval is on the right lines, but it looks as though you're wanting to loop through the list of paintings twice: once to display the names (three per line), and once for the descriptions. This isn't at all easy to achieve within the template language.

    I would suggest seeing if you can do something with some CSS. It should be possible to assign a class to the name and/or description divs so that the names all float left together, and the descriptions display as blocks underneath. Still tricky, though.

    Alternatively, you could pre-process the list in your view, so that you separate out the names and descriptions into groups of three. You want to end up with this structure:

    [
        [name1, name2, name3],
        [description1, description2, description3],
        [name4, name5, name6],
        [description4, description5, description6],
        ...
    ]
    

    So you could try doing this:

    painting_list = []
    counter = 0
    while counter < len(paintings):
        painting_list.append([p.name for p in paintings[counter:counter+3])
        painting_list.append([p.description for p in paintings[counter:counter+3])
        counter += 3
    

    and then in your template:

    {% for group in painting_list %}
        <div class="names">{% for name in group.0 %}{{ name }} {% endfor %}</div>
    
        <ul class="descriptions">
            {% for description in group.1 %}
            <li>{{ description }}</li>
            {% endfor %}
        </ul>
    {% endfor %}
    
  • I definitely vote for creating the structure in your view and passing it on to your template in the correct form.

    If you find yourself struggling with template logic then it's a sign you should be doing more of the work in your view. (this also taught me that quite a bit of my view logic needed to be pushed back into my models...)

  • Whenever you find yourself trying out complex code inside templates, its usually a good indication that it should be moved elsewhere. One of the alternative solutions have already been suggested, which is to move the code into your view function.

    The other solution would be to expose the functionality via a new template tag. One of the reasons you would choose this solution over the view solution, is that you'll be able to easily re-use the code for pages that are served with different views.

    class GroupPaintingsNode(template.Node):
        def __init__(self, num, varname):
         self.num, self.varname = int(num), varname
    
        def render(self, context):
         paintings = Painting.objects.all # do your fetching/filtering here.. 
         l = [[] for i in range(len(paintings))]
         i = 0
         while i < len(paintings):
          l[i].append([p.title for p in paintings[i:i+self.num]])
          l[i].append([p.desc for p in paintings[i:i+self.num]])
          i += self.num
         context[self.varname] = l
         return ''
    
    def group_paintings(parser, token):
        tokens = token.contents.split()
        if len(tokens) != 4:
         raise template.TemplateSyntaxError, "'%s' tag requires three arguments" % tokens[0]
        if tokens[2] != 'as':
         raise template.TemplateSyntaxError, "Second argument to '%s' tag must be 'as'" % tokens[0]
        return GroupPaintingsNode(tokens[1], tokens[3])
    group_paintings = register.tag(group_paintings)
    

    In template code you would use it like this:

    {% group_paintings 3 as paintings %}
    {% for p in paintings %}
        {% for title in p.0 %} {{ title }} {% endfor %}<br>
        {% for desc in p.1 %} {{ desc }} {% endfor %}
    {% endfor %}
    
    Oni : I think this seems best as a template tag is the nicest place for this functionality to go as oppose to a view which is more awkward. Lot of lists there but I get it :) Somewhat elegant solution there! Thanks :)
  • {% for painting in painting_list %}
        <div class="painting">{{ painting }}</div>
        {% if forloop.counter|divisibleby:"3" %}
            <br>
            {{ description_list.forloop.counter0-2 }}
            {{ description_list.forloop.counter0-1 }}
            {{ description_list.forloop.counter0 }}
        {% endif %}
    {% endfor %}
    

    just so you know this code won't work, but something like this is what you want.

    Maybe you could come up with your own templatetag to access the nth object in an object list.

Assembly Language Primer video tutorials?

I've seen a lot of text based Assembly tutorials but finding it tough to learn from them. What video tutorials exist for Assembly Language?

From stackoverflow

What's the best way to encrypt short strings in .NET?

My boss wants me to encrypt some information used during data transfer. The individual strings to be encrypted are between eight and twenty characters long. A single password must be used to encrypt and decrypt so I need a symmetric alogrithm. I don't want to roll my own - I want to use one built into .NET from C#.

So, which algorithm is best?

From stackoverflow
  • TripleDes ?

    You can use the System.Security.Cryptography.TripleDESCryptoServiceProvider

    Small amount of code to encrypy/decrypt... does exactly what it says on the tin :)

    Syed Tayyab Ali : I agree with you DES is best option for him.
    James Black : My only concern with DES is how to do a key exchange securely.
    Matthew Flaschen : This issue (key exchange) applies to any symmetric cipher (of course there are also issues with asymmetric), and the OP explicitly requested symmetric. http://en.wikipedia.org/wiki/Key_exchange is a good place to start, but it's a complex topic.
  • check this encryption tutorial.

  • You could just use RSA encryption, since these are short strings, which will make key exchange simpler.

    How much you can encrypt with RSA is based on the key length.

    I am a fan of the rsa library from bouncy castle.

  • See my post here:

    http://stackoverflow.com/questions/202011/encrypt-decrypt-string-in-c

  • Rot 26, nobody will figure it out.. it's hiding in plain sight!

    Greg B : LOL .
  • TripleDES is a very good option, but you can also consider AesCryptoServiceProvider (AES), which is a modern symmetric cipher.

  • .net security classes:

    Hash

    * MD5
    * MD5Cng
    * SHA1
    * SHA1Managed
    * SHA1Cng
    * SHA256
    * SHA256Managed
    * SHA256Cng
    * SHA384
    * SHA384Managed
    * SHA384Cng
    * SHA512
    * SHA512Managed
    * SHA512Cng
    

    Symmetric Encryption: Uses the same key for encryption and decryption.

    * DES
    * DESCryptoServiceProvider
    * TripleDES
    * TripleDESCryptoServiceProvider
    * Aes
    * AesCryptoServiceProvider
    * AesManaged
    * RC2
    * RC2CryptoServiceProvider
    * Rijandel
    * RijandelManaged
    

    Asymmetric Encryption: Uses different keys for encryption and decryption.

    * DSA
    * DSACryptoServiceProvider
    * ECDsa
    * ECDsaCng
    * ECDiffieHellman
    * ECDiffieHellmanCng
    * RSA
    * RSACryptoServideProvider
    
    Matthew Flaschen : That's a very good dump of class names, but most of those have no relevance to the submitter (who wants a /symmetric/ /encryption/ algorithm), not a hash or an asymmetric cipher.
  • Here is encrypt & decrypt function with des3 encryption

    ''' <summary>
    ''' Encrypts a memory string (i.e. variable).
    ''' </summary>
    ''' <param name="data">String to be encrypted.</param>
    ''' <param name="key">Encryption key.</param>
    ''' <param name="iv">Encryption initialization vector.</param>
    ''' <returns>Encrypted string.</returns>
    Public Shared Function Encrypt(ByVal data As String, ByVal key As String, ByVal iv As String) As String
        Dim bdata As Byte() = Encoding.ASCII.GetBytes(data)
        Dim bkey As Byte() = HexToBytes(key)
        Dim biv As Byte() = HexToBytes(iv)
    
        Dim stream As MemoryStream = New MemoryStream
        Dim encStream As CryptoStream = New CryptoStream(stream, des3.CreateEncryptor(bkey, biv), CryptoStreamMode.Write)
    
        encStream.Write(bdata, 0, bdata.Length)
        encStream.FlushFinalBlock()
        encStream.Close()
    
        Return BytesToHex(stream.ToArray())
    End Function
    
    ''' <summary>
    ''' Decrypts a memory string (i.e. variable).
    ''' </summary>
    ''' <param name="data">String to be decrypted.</param>
    ''' <param name="key">Original encryption key.</param>
    ''' <param name="iv">Original initialization vector.</param>
    ''' <returns>Decrypted string.</returns>
    Public Shared Function Decrypt(ByVal data As String, ByVal key As String, ByVal iv As String) As String
        Dim bdata As Byte() = HexToBytes(data)
        Dim bkey As Byte() = HexToBytes(key)
        Dim biv As Byte() = HexToBytes(iv)
    
        Dim stream As MemoryStream = New MemoryStream
        Dim encStream As CryptoStream = New CryptoStream(stream, des3.CreateDecryptor(bkey, biv), CryptoStreamMode.Write)
    
        encStream.Write(bdata, 0, bdata.Length)
        encStream.FlushFinalBlock()
        encStream.Close()
    
        Return Encoding.ASCII.GetString(stream.ToArray())
    End Function
    
  • Why not just use a SecureString?

    Matthew Flaschen : How does that handle serialization/deserialization?
    Mike Post : Now that I dig deeper, I see that you can't serialize SecureString objects. Bummer.
  • DES is pretty much obsolete at this point. Here is the Wikipedia. If you are changing the key a lot, it might be adequate, but if you are relying on a key for a while, AES seems like a better choice.

    Of course it is a question of how much protection you need. But AES is build right in there too.

    I have used AES for small strings, and it works nice.

    What I have read about TripleDES is that since DES is easily crackable, TripleDES is still not substantial.

    Matthew Flaschen : Actually, Wikipedia (http://en.wikipedia.org/wiki/TripleDES#Security) and NIST (http://csrc.nist.gov/publications/nistpubs/800-57/SP800-57-Part1.pdf) (p. 66), say that TripleDES is expected to be secure until 2030.