Sunday, February 13, 2011

How can I create EPS files in C#?

How can I create EPS files in C#? Are there any opensource libraries available or do I have to resort to the spec and do it by hand?

  • You can use the same principle as I suggested in the HTML to Postscript question here: html-to-postscript-conversion

    It is clumsy to set up, but once it is done it works quite well. If you don't have a printer driver that creates EPS files you can download some of the freeware pdf creator printer drivers. I believe some of these allow you to create EPS files as well.

  • The cairo library http://www.cairographics.org generate all kinds of graphical formats, svf, pdf or ps for instance, and it has bindings for c# I think.

    From stephanea

How does one add a svn repository build number to Python code?

EDIT: This question duplicates http://stackoverflow.com/questions/110175/how-to-access-the-current-subversion-build-number#111173 (Thanks for the heads up, Charles!)

Hi there,

This question is similar to http://stackoverflow.com/questions/16248/getting-the-subversion-repository-number-into-code

The differences being:

  1. I would like to add the revision number to Python

  2. I want the revision of the repository (not the checked out file)

I.e. I would like to extract the Revision number from the return from 'svn info', likeso:

$ svn info

Path: .
URL: svn://localhost/B/trunk
Repository Root: svn://localhost/B
Revision: 375
Node Kind: directory
Schedule: normal
Last Changed Author: bmh
Last Changed Rev: 375
Last Changed Date: 2008-10-27 12:09:00 -0400 (Mon, 27 Oct 2008)

I want a variable with 375 (the Revision). It's easy enough with put $Rev$ into a variable to keep track of changes on a file. However, I would like to keep track of the repository's version, and I understand (and it seems based on my tests) that $Rev$ only updates when the file changes.

My initial thoughts turn to using the svn/libsvn module built in to Python, though I can't find any documentation on or examples of how to use them.

Alternatively, I've thought calling 'svn info' and regex'ing the code out, though that seems rather brutal. :)

Help would be most appreciated.

Thanks & Cheers.

  • I use a technique very similar to this in order to show the current subversion revision number in my shell:

    svnRev=$(echo "$(svn info)" | grep "^Revision" | awk -F": " '{print $2};')
    echo $svnRev
    

    It works very well for me.

    Why do you want the python files to change every time the version number of the entire repository is incremented? This will make doing things like doing a diff between two files annoying if one is from the repo, and the other is from a tarball..

    Cebjyre : I would imagine BMH doesn't want to use this in every file, but to have a single location that details the current version of the system - look at the bottom right of this page for an example.
    From Jerub
  • Python has direct bindings to libsvn, so you don't need to invoke the command line client at all. See this blog post for more details.

    EDIT: You can basically do something like this:

    from svn import fs, repos, core
    repository = repos.open(root_path)
    fs_ptr = repos.fs(repository)
    youngest_revision_number = fs.youngest_rev(fs_ptr)
    
    Charles Duffy : Yes, but that doesn't give you access to all the logic in svnversion -- which does *exactly* the Right Thing in this kind of situation.
    From JesperE
  • There is a command called svnversion which comes with subversion and is meant to solve exactly that kind of problem.

    Charles Duffy : You might amend this to show how one would write the result to a build artifact bundled into a generated egg/package/whatnot, just to be complete and answer both legs of the question (how to calculate the answer, and how to bundle it into your python project).
    From CesarB
  • If you want to have a variable in one source file that can be set to the current working copy revision, and does not replay on subversion and a working copy being actually available at the time you run your program, then SubWCRev my be your solution.

    There also seems to be a linux port called SVNWCRev

    Both perform substitution of $WCREV$ with the highest commit level of the working copy. Other information may also be provided.

    From Ber
  • Stolen directly from django:

    def get_svn_revision(path=None):
        rev = None
        if path is None:
            path = MODULE.__path__[0]
        entries_path = '%s/.svn/entries' % path
    
        if os.path.exists(entries_path):
            entries = open(entries_path, 'r').read()
            # Versions >= 7 of the entries file are flat text.  The first line is
            # the version number. The next set of digits after 'dir' is the revision.
            if re.match('(\d+)', entries):
                rev_match = re.search('\d+\s+dir\s+(\d+)', entries)
                if rev_match:
                    rev = rev_match.groups()[0]
            # Older XML versions of the file specify revision as an attribute of
            # the first entries node.
            else:
                from xml.dom import minidom
                dom = minidom.parse(entries_path)
                rev = dom.getElementsByTagName('entry')[0].getAttribute('revision')
    
        if rev:
            return u'SVN-%s' % rev
        return u'SVN-unknown'
    

    Adapt as appropriate. YOu might want to change MODULE for the name of one of your codemodules.

    This code has the advantage of working even if the destination system does not have subversion installed.

    From pobk
  • Based on CesarB's response and the link Charles provided, I've done the following:

    try:
      from subprocess import Popen, PIPE
      _p = Popen(["svnversion", "."], stdout=PIPE)
      REVISION= _p.communicate()[0]
      _p = None # otherwise we get a wild exception when Django auto-reloads
    except Exception, e:
      print "Could not get revision number: ", e
      REVISION="Unknown"
    

    Golly Python is cool. :)

Why does addition of long variables cause concatenation?

What does Java do with long variables while performing addition?

Wrong version 1:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = speeds.size() + estimated; // time = 21; string concatenation??

Wrong version 2:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = estimated + speeds.size(); // time = 12; string concatenation??

Correct version:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long size = speeds.size();
long time = size + estimated; // time = 3; correct

I don't get it, why Java concatenate them.

Can anybody help me, why two primitive variables are concatenated?

Greetings, guerda

  • I suspect you're not seeing what you think you're seeing. Java doesn't do this.

    Please try to provide a short but complete program which demonstrates this. Here's a short but complete program which demonstrates correct behaviour, but with your "wrong" code (i.e. a counterexample).

    import java.util.*;
    
    public class Test
    {
        public static void main(String[] args)
        {
            Vector speeds = new Vector();
            speeds.add("x");
            speeds.add("y");
    
            long estimated = 1l;
            long time = speeds.size() + estimated;
            System.out.println(time); // Prints out 3
        }
    }
    
    matt b : So what was it about this answer that was correct? What was the author doing wrong?
    furtelwart : Yeah, I was wrong. It was probably a thread problem.
    From Jon Skeet
  • My guess is you are actually doing something like:

    System.out.println("" + size + estimated);
    

    This expression is evaluated left to right:

    "" + size        <--- string concatenation, so if size is 3, will produce "3"
    "3" + estimated  <--- string concatenation, so if estimated is 2, will produce "32"
    

    To get this to work, you should do:

    System.out.println("" + (size + estimated));
    

    Again this is evaluated left to right:

    "" + (expression) <-- string concatenation - need to evaluate expression first
    (3 + 2)           <-- 5
    Hence:
    "" + 5            <-- string concatenation - will produce "5"
    
    From toolkit

Dynamic rendering of webpage for logged in users only

When a user logs in to my site I want a css styled button to appear (this could be anything really, i.e. some special news text item etc), how can you do this via masterpages in asp.net? Or is there some other way you do this?

  • This MSDN article describes how you can find and manipulate master page content from a content page.

    MSDN

    From Steve Horn
  • Check out the LoginView control in ASP.Net. It takes two templates - one for logged in users and one for not-logged in users. I guess it should do what you want.

  • You haven't provided a whole lot of information about your setup simon, but assuming you're using a .NET Membership Provider, then you can use a login view to have a section of your page render differently for logged in Vs. not

        <asp:LoginView>
            <AnonymousTemplate>
                Nothing Displayed
            </AnonymousTemplate>
            <LoggedInTemplate>
                <asp:Button ID="myButton" runat="server">
            </LoggedInTemplate>
        </asp:LoginView>
    

Self-owned objects in Objective-C Garbage Collection

I'm wondering what are the recommended ways to handle situations where, in memory managed code, object didn't belong to any particular owner, i.e. objects released themselves. One such example could be a subclass of NSWindowController, which configures, displays and manages input and output of a single window. The controller object displays a window and releases itself later at some point (usually when the window or sheet it manages is closed). AppKit provides couple examples as well: NSAnimation retains itself in startAnimation and releases itself when the animation is done. Another example is NSWindow, which can be configured to release itself when closed.

When implementing these "self-owned" objects myself, I see at least three different GC-safe patterns, but all of them have some drawbacks.

a). Using CFRetain/CFRelease.

Self-owned object calls CFRetain on self before it starts its operation (e.g. in the window controller example before the window is displayed). It then calls CFRelease() on self when it's done (e.g. in the window controller example after the window is closed).

Pros: User of the object doesn't have to worry about memory management.
Cons: A bit ugly, since requires use of memory management functions, although we're using GC in pure ObjC code. If CFRelease() isn't called, leak may be hard to locate.

b). Avoiding self-ownership idiom with static data structure.

Object adds itself into a data structure (e.g. a static mutable array) before it starts its operation and removes itself from there when it's done.

Pros: User of the object doesn't have to worry about memory management. No calls to memory management functions. Objects have explicit owner. Potential leaks are easy to locate.
Cons: Locking is needed if objects may be created from different threads. Extra data structure.

c). Avoiding self-ownership idiom by requiring the user of object to save a reference to the object (e.g. into an ivar).

Pros: No calls to memory management functions. Objects have explicit owner.
Cons: User of the object has to keep a reference even if it doesn't need the object anymore. Extra ivars.

What pattern would you use to handle these cases?

  • Apple's recommendation is (c), but I like the sound of (b). A static data structure allows you to hide the GC details from the API user while avoiding dipping into the CFRetain/CFRelease level. As you state, it also makes debugging and unit testing easier; if an object is still referenced by the static data structure after it's finished its task, you know there's a bug.

    From Barry Wark
  • For a), the more idiomatic alternative to CFRetain(foo)/CFRelease(foo) is [[NSGarbageCollector defaultCollector] disableCollectorForPointer:foo]/[[NSGarbageCollector defaultCollector] enableCollectorForPointer:foo].

    From Ahruman

WebSphere Portal v.5.1 and AJP?

Hello,

is there a way to configure WebSphere Portal to accept AJP connections? E.g. Tomcat/JBoss and Oracle have a specific AJP port. I can't find it in WebSphere, and I'm getting tired of Googlin' around IBM pages.

Thank you in forward... Balint

Effort Spent on Designing, Implementing and Maintaining CRUD.

Hi,

What percentage of your total development effort do you spend on implementing and maintaining simple Create, Read, Update and Delete (CRUD) methods in your data access layer?

Does moving to an ORM like Hibernate or Entity Framework lead to significant savings? Are there any design smells which let you know when moving to an ORM for your data access layer is a good choice?

Kind regards, Ashish

  • Having recently spent ridiculous numbers of hours (probably on the order of 40%) duplicating what an ORM would have done in minutes, I have to say that whenever you can allow well tested frameworks to generate (and maintain!) basic CRUD operations, LET IT DO IT!

    Let the framework do that at which it excels. Spend your time on the part of the application that really adds value, the business problem you're solving. Only when the framework falls short should you really consider working around it. 'Falling short' could include performance, but generally there are "hooks and knobs" within the framework to let you do what you need to get done.

    Implementation/Design Smell: When you've coded the 'StoredProcedureWrapper' for the 40th time or are implementing caching for query results by capturing DAO output, you coulda/shoulda used ORM

    With a Ruby/Rails or Groovy/Grails type of framework, I can't see a real reason NOT to start with the ORM layer, as both environments generate the Domain for you.

    With Spring/Hibernate, it is a little more complicated, but still saves a lot of hand-coding of very similar small classes.

    I've also found in several projects in the last 10 years or so that if we didn't start using an ORM, we ended up developing or 'stealing' JDBC frameworks or other scaffolding code that again duplicates a lot of what an ORM can get you.

    From Ken Gentle

Are you using event streaming products?

Maybe you're familiar with the concept of event streaming processing (ESP) ... if you are, I'd love to hear what you're using and what platforms you're using them on. I am an active contributor to the Esper project (http://esper.codehaus.org/) but I'd be interested in hearing what others are using? Anyone using Coral8, Aleri or Streambase? What platforms are you using them on?

  • at present i am not using any event stream processing (ESP) / complex event processing (CEP) products, but am familiar with the concepts - we evaluated Streambase for a prior (military) project and I still get emails from them every now and then ;-)

    I looked into using esper for another real-time system (not a financial trading system, which seems to be the primary application for CEP these days), but thought it was - no offense - overkill. We wanted something lightweight to control an event-driven process in such a way that it could be altered without redeploying the code base, but frankly ran out of time so the evaluation did not get to go 'deep' enough. Will probably revisit this in future.

    ESP/CEP is underrated, in my opinion, as a solution platform. It can be difficult to comprehend if you're used to purely transactional thinking.

  • At a previous job, we looked at Cayuga, Esper, StreamBase, and Coral8. I'm actually interested in seeing if I can make a souped-up RSS reader using one of these engines and a text-processing engine. I'm not sure how it would all fit together, as I haven't had the time to think about it, but I think an RSS item can be consumed as an "event", processed, and then things could happen if similar "events" (similar messages or postings) are received in a time span. Perhaps the identification of hot topics and such.

    Stephen Darlington : CEP engines tend to work best when data is "pushed" into it. RSS is more "periodic polling," but it certainly could be done. You'd probably have to write an RSS-CEP adapter, but that wouldn't be terribly hard. Spotting patterns in the stream is what CEP/ESP platforms were designed for.
  • I work for Aleri (opinions here are my own, though), so my view is a little skewed. Having said that...

    We're seeing a number of great use cases, ranging hugely in complexity and data volume. A few examples:

    • Market data cleansing. We take stock quotes and "sanitise" them, flagging quotes that are out of expected market bounds
    • Algo trading is the canonical CEP example application, and that's kind of the sanitising application above with an extra piece at the end that places an order if a certain pattern of events occurs
    • Aggregating order books across trading venues, i.e., feeding in market prices across exchanges and outputting a consolidated order book
    • Liquidity and risk management

    Some people use it for the low-latency aspect, but many use it because it allows rapid development of many event-driven applications.

    I'm seeing a lot of installations on Solaris/x86-64 machines, though we also have SPARC and Linux in production too.

    By the way, most vendors use the term CEP, Complex Event Processing, to describe their products. I don't think that was the best TLA to use, but it looks as though we're stuck with it now.

    Feel free to ask any further questions. Obviously there are certain things I can't talk about but I'll do what I can.

  • I was on a team that did a proof-of concept with rulecore. We used it to run a couple of hundreds of rules which were automatically generated from a database. We used a single server with 16 gigs of ram and 4 cores.

    From Dieter

Web.Config Falling back to Global Config in Web Farm

Hi all,

This problem has several of us stumped in the office. We are all new to deploying ASP.NET apps to a web farm, and I am fresh out of ideas.

We have a web farm, and the application is copied on to all of them. However, we are having a problem..

An exception is being thrown when trying to get settings from appSettings. Upon further investigation, it turns out the node is actually not using the local Web.Config but it falling back to the Web.Config in the .NET framework folder (we have proved this by adding keys there, which appear on a test page).

I must be missing something, because my understanding is that so long as the file is there, IIS should use that! One of the servers seems to work fine!

Here's a list of what we have confirmed:

  • The config file is in the app directory.
  • Said file's content is correct.
  • When viewing the file from IIS > Site > Properties > ASP.NET > Edit Config the correct content is shown.

However, at run-time the file that is used is the global one (windows\ms .net\framework\v2\config\web.config).

Anyone have any suggestions as to what may be going wrong? Appreciate all the help I can get!

Thanks.

Rob

  • This is the hierarchy for ASP.NET configuration. Maybe this could help understanding which settings overwrite each other.

    Server

    Machine.config: The Machine.config file contains the ASP.NET schema for all of the Web applications on the server. This file is at the top of the configuration merge hierarchy.

    Root Web

    Web.config: The Web.config file for the server is stored in the same directory as the Machine.config file and contains default values for most of the system.web configuration sections. At run time, this file is merged second from the top in the configuration hierarchy.

    Web site

    Web.config: The Web.config file for a specific Web site contains settings that apply to the Web site and inherit downward through all of the ASP.NET applications and subdirectories of the site.

    ASP.NET application root directory

    Web.config: The Web.config file for a specific ASP.NET application is located in the root directory of the application and contains settings that apply to the Web application and inherit downward through all of the subdirectories in its branch.

    ASP.NET application subdirectory

    Web.config: The Web.config file for an application subdirectory contains settings that apply to this subdirectory and inherit downward through all of the subdirectories in its branch.

    Client application directory

    ApplicationName.config: The ApplicationName.config file contains settings for a Windows client application (not a Web application).


    Understanding which ASP.NET files and folders are inherited through folders and applications is very important for development and troubleshooting.

    Here is a short summary:

    • web.config files inherit all the way down the tree, past all application boundaries.
    • global.asax only lives within its application
    • /bin and the /app_{folders} only live within their application

    So, this means that anything set in the root web.config file will inherit down the entire site, even if some folders are marked as applications.

    Where this gets messy is if the web.config file has references to assemblies but sub-applications don't have those assemblies. For example, let's say that you have a HTTP Module configured in the root of the site and referenced from the site web.config file. If you have a sub-application called /subfolder which is marked as an application, then /subfolder will attempt to load the HTTP Handler from /subfolder/bin. Since it doesn't exist, an error will be thrown.

    There are multiple ways around this. Probably the cleanest if the HTTP Handler isn't needed in /subfolder is by 'removing' the reference by adding a clause in the /subfolder/web.config file. You can do this with . Here is an example of how to remove a HTTP Module in a subfolder:

    <httpModules>
      <remove name="ErrorLog"/>
    </httpModules>
    

    Here is what the site web.config might look like:

    <httpModules>
          <add name="ErrorLog"  type="GotDotNet.Elmah.ErrorLogModule, GotDotNet.Elmah, Version=1.0.5527.0, Culture=neutral, PublicKeyToken=978d5e1bd64b33e5" />
    </httpModules>print("code sample");
    
    Rob Cooper : My understanding is that the application level file takes precedence? The problem here is that at runtime, the application file does not get picked up. Thanks for the reply.
    Rob Cooper : Based on your expansion [thanks] - the file being applied is the Root Web, but there *is* a Web.config for the application!
    splattne : What happens, if you insert an erroroneous entry in that web.config? Does the application get that?
    From splattne
  • From what you tell in the comments, I suggest going with "Try and Error".

    What happens, if you insert an erroneous entry by purpose? Does the application fail or doesn't that affect anything?

    Try to copy the content and then delete and recreate that file from scratch.

    From splattne
  • Hi All,

    First off, thank you very much to the guys that answered, I do appreciate the help!

    Just an update on this issue. It was a tough one!

    Turns out, there was nothing wrong with the code, or the configuration.

    It appears that something weird was going on with the server farm (which I have absolutely no control over or access to). The sysadmin re-built the farm, re-deployed the solution and all worked fine.

    I guess we will never know what was wrong, but at least we know it was not a development issue!

    Thanks again, Rob

    From Rob Cooper

Is mutation testing useful in practice?

It exists the technology of mutation testing. It checks, if the tests are running even if you change the code. If not all is OK, if the tests are running they don't cover all eventualities. There is some theoretical work about it, but I'm interested in the question, if it is useful in practice? Do you have any examples of real life applications of mutation testing? Does it work better than simple test-coverage-tools? Or is it useless?

What are the advantages/disadvantages of mutation testing in the real world?

  • I looked at mutation test some time ago as a method for checking the efficacy of my automated regession testing scripts. Basically, a number of these scripts had missing checkpoints, so while they were exercising the application being tested correctly, they weren't verifying the results against the baseline data. I found that a far simpler method than changing the code was to write another application to introduce modifications to a copy of the baseline, and re-run the tests against the modified baseline. In this scenario, any test that passed was either faulty or incomplete.

    This is not genuine mutation testing, but a method that uses a similar paradigm to test the efficacy of test scripts. It is simple enough to implement, and IMO does a good job.

  • I recently did some investigations on mutation testing. Results are here:

    http://abeletsky.blogspot.com/2010/07/using-of-mutation-testing-in-real.html

    In short: mutation testing could give some information about quality of source code and tests, but it is something straighforward to use.

    From alexanderb

HTML <select> what is the name of on select event?

Does the HTML "select" element have an on select event? what exactly is the name of the event?

  • Is onchange what you're looking for?

    J Angwenyi : fantastic stuff - works!!! thanks guys.
    From insin
  • Regardless of input type, whenever a form input changes value, an onchange event should always be thrown. (With the exception of buttons, as they are not really input devices as such.)

    insin : Worth noting that when you're using a