Monday, March 28, 2011

Adding custom log locations to the OS X console application...

After searching online, the best solution I've found so far is to just make a symbolic link in either "/Library/logs/" or "~/Library/logs/" to get it to show up in the Console application.

I'm wondering if it would be possible to add a new directory or log file to the "root" level directly under the "LOG FILES" section in the console.

Here's a quick screenshot:

OS X Console

From stackoverflow
  • I don't believe it's possible.

    If you're generating log files, you should generate them into one of the standard locations anyway, so this won't be an issue.

  • There is one way to get you log files into the console.

    You can add a symlink to the log file or log directory to one of the directories in the list. The directory ~/Library/Logs seems like the logical choice for adding your own log files.


    For myself I wanted easy access to apache2 logs. I installed apache2 using macports and the default log file is located at /opt/local/apache2/logs.

    Thus all I did was create the symlink to that directory.

    # cd ~/Library/Logs
    # ln -s /opt/local/apache2/logs/ apache2
    

    Now I can easily use the console.app to get to the logs.

  • In Terminal run this command... append any log file directories you want to add

    defaults write com.apple.Console LogFolderPaths -array '~/Library/Logs/' '/Library/Logs/' '/var/log/' '/opt/local/var/log/'

    Ted Naleid : This didn't seem to work for me on Leopard 1.5.7, am I missing something?
    Wilco : Doesn't work for me either (sasme OS/version) - any ideas?
    sholsinger : Sorry I thumbed it up before trying. That default doesn't exist.
  • I actually just came across this option that worked perfectly for me:

    Actually if you open terminal and...

    $ cd /Library/Logs

    then sym-link to your new log directory. eg i want my chroot'ed apache logs as 'www'

    $ ln -s /chroot/apache/private/var/log www

    then re-open Console.app

    drill down into /Library/Logs and you will find your sym-linked directory.

    ;-)

    Mohclips.

    http://forums.macosxhints.com/showthread.php?t=35680

How can AWK do array arithmetics?

I want to shift away from Excel to Awk. I need basic mathematical operations, such as addition and division, for arrays.

For example, arrays A and B are [1, 3, 2] and [2, 1, 2], respectively. How can I get an array [2, 3, 4] from the multiplication between A and B? What about the addition and division between A and B?

From stackoverflow
  • I think awk is not done for this sort of numeric work. It's more for text processing. Arrays in awk are associative and sparsely occupied (may have "holes" between its indexes). You use strings to index them:

    for(int j=0; j<length(A) && j<length(B); j++)
        C[j] = A[j] * B[j]
    

    It's like a hash-map. So, in awk you can do

    A[100] = 10;
    A[1] = 2;
    

    And have only 2 elements stored in that array (elements from 2 to 99 do not exist), indexed by strings that are created by converting the numbers 100 and 1. The GNU Awk manual has a nice section about arrays in awk here.

  • In awk "arrays" are associative. That is they are hashes indexed not by a continous string of numbers but by arbitrary input values. So you can do things like

    for (i=0; i<3; i++){
       c[i] = a[i] * b[i];
    };
    

    if you know that the numerically indexed elements exist, or you can do things like:

    d["sam"] = a[3] + b["dog"];
    

    But array processing really isn't awk's strength, and I would advise taking a careful look at what is involved before committing wholesale to this course.

    You might be better off with python or another fairly modern rapid development language.

    BTW-- I wrote my first non-trivial bit of code in python last week, and I am totally hooked. After occasional exposure to tcl and perl, I was really wishy-washy on the value of these kinds of tools. I think python will make a believer out of me.

Data handling in web app with GWT, Struts and Hibernate

I am writing a Web App using Struts and Hibernate. Recently, I discovered GWT and the Visualization API. This all looked very interesting and provides AJAX functionalities that my app needs. I'm a newbie that is quite confused....

Where to put data access level checks?

In the web app, users have different level of access for the data. e.g. different combinations of read/write privileges for different data. There will be some kind of user profile that the app checks for when any data is accessed or modified. The user will be given data access according the result -- denied viewing access or can see the data but cannot change it etc. I'm not sure where to put this particular check. I guess I could have it coded in the DAO's, everytime data operation is processed, manually check the queried data against the profile. Or, put it in the business logic/display layer, if an user does not have a data access privilege, take the button away from the user. Or both? Or is there a configuration file in hibernate somewhere I can specify data access privileges for all the tables mapped?

Best practice for passing information around

There is great need to communication between the model/view/controller, make RPC call for GWT and pass data off to the Visualization code to render charts and stuff. I'm guessing it definitely need some kind of translator that converts Java objects into JSON objects in order to make gwt-rpc calls and draw charts with the Visualization API. Am I correct? Also, in terms of passing information around in Struts and Hiberante -- is writing Data Transfer Objects a good idea? Then just pass beans around all the time? Or (I just came across this today..not even sure if I understood it correctly) maybe bind the objects onto JNDI, and access them from other parts of the program?

Any input/clarification will be appreciated. Thank you very much!

From stackoverflow
  • I can't speak much about your first question because I really don't like using Struts for anything GWT related.

    As to your second question, no you shouldn't have to use any JSON. It sounds like your back end is Java, which means that the GWT RPC mechanism will just work with POJOs. So you would just create the objects you need for drawing and pass them back and forth between your client and server. GWT will do all the RPC stuff for you out of the box.

    Writing Data Transfer objects might be necessary, but only if your hibernate model files contain things that the GWT compiler can't understand. I normally user EJB3 and Stripes (instead of Hibernate and Struts) and in my case I never have to write any data transfer objects, I just use the EJB3 POJOs and pass them between my client and server.

    Chii : if you use hibernate, your domain object can not be serialized by gwt, even if it only contains gwt serializable objects. thats because hibernate proxies the results, especially sets/lists. you will beed DTO's unless the objects participating in rpc are not from hibernate.
    tomato : Thanks for your input! I still have to explore more about RPC...
  • access level checks:

    i would seperate the access level checks into its own class, and have your "controllers" call the access managers first before calling DAO's. i.e., each action performs a check before doing the DAO calls to get/insert data.

    but a better method, if you are using gwt, is to make RPC calls instead of using struts actions. the rpc calls becomes the "controllers" i mentioned above, and can do access checks using the managers i mentioned above - i.e., elminitate actions.

    as for the access managers, i recommend enumerating all granular access privileges, and the compose these priviledges into a set that can be associated with each user/profile/whatever.

    passing info around gwt is a pain to work with hibernate - you can try using Gilead , but i havent had much success with it, its too cumbersome for me. your idea with json converting is the right way to go in gwt imho. gwt 1.5 supports whats called javascript object overlay, which lets you return json, and "superimpose" it into a gwt java object directly with little code on your part. check out this post for more info.

    the other method is to roll your own DTO generation facility (which is what Gilead is meant to do, but i dont think it does autogeneration?not sure). implement it as part of your build. its a bit of extra work that wouldnt be worth it if its not a large project.

  • Data access level checks in server side is the safest way. But still GWT generates a packed JS. You can do it on Client side. But in that case user profile should be checked/fetched in/from the server side every time.

    passing info around: I am using delimited strings in vector. And it is running good...

How to best develop web crawlers

Heyall,

I am used to create some crawlers to compile information and as I come to a website I need the info I start a new crawler specific for that site, using shell scripts most of the time and sometime PHP.

The way I do is with a simple for to iterate for the page list, a wget do download it and sed, tr, awk or other utilities to clean the page and grab the specific info I need.

All the process takes some time depending on the site and more to download all pages. And I often steps into an AJAX site that complicates everything

I was wondering if there is better ways to do that, faster ways or even some applications or languages to help such work.

From stackoverflow
  • Using regular expressions for parsing content is a bad idea that has been covered in questions here countless times.

    You should be parsing the document into a DOM tree and then you can pull out any hyperlinks, stylesheets, script files, images or other external links that you want and traverse them accordingly.

    Many scripting languages have packages for getting Web pages (eg curl for PHP) and for parsing HTML (eg Beautiful Soup for Python). Go that route instead of the hackky solution of regular expression matching.

  • If you use python, Scrapy is great is easy to use.

Floorplan and packaging architecture resources for the interested software professional?

One of the more interesting things I've run into lately is the art and science of laying out chip floorplan and determining packaging for the silicon. I would like to read some materials on the subject for the "Interested Software Guy".

Does anyone have any recommendations (Website or book, so long as it is a good quality)?

From stackoverflow
  • This is a result of my search on the subject as I was curious about your question and this is where I would start myself. Sorry I am not a specialist on the subject but hope it can kick-start you!

    Seems floorplan optimization is a matter of combinatorial optimization.

    As a developer, you'll want to tackle the theory behind it and most likely some proven algorithms. You might then be interested by books such as:

    It's a bit more difficult to get links on this subject, but if you're a member of IEEE Xplore, you might want to look at this paper and other similar ones.

    Finally, on the floorplan wikipedia entry, you'll notice this on sliceable floorplans that might give you your best starting point:

    Sliceable floorplans have been used in a number of early EDA tools for a number of reasons. Sliceable floorplans may be conveniently represented by binary trees which correspond to the order of slicing. What is more important, a number of NP-hard problems with floorplans have polynomial time algorithms when restricted to sliceable floorplans

    Good luck!

    BCS : Nice, a hard copy list. Their sure is something to be said for good old bound paper. +1
    lpfavreau : It was a pleasure, hope it helps!
  • There seems to be a class on this at Carnegie Mellon

    VLSI CAD

    some of the lecture notes that looked more interesting than others:

    That site make references to one or more books that this fellow published:

    Also I found a short tutorial here

  • AutoCAD is a classic... Though on my limited budget I prefer Rhino 2.0.

Best way to store Badge criteria?

I've been thinking about how to implement the badge feature similar to SO's on a new website. What is the best way to store criteria for badges?

Two ideas:

  • All code
  • 'Second system' - create a meta architecture for defining badges and their criteria. Store some info in the database and have code query it to figure out the badges and their criteria.

Are there better ways?

From stackoverflow
  • Rules.

    You create events in the system, and use rules within an event stream processor.

    Specifically, say you have a badge "made 10 posts". You don't run "select count(*) from posts where user = :user" for every post. Rather, you have a simple rule that watches each post come by, and "count them", storing the rules state in the user profile.

    That way "made 10 posts" is as cheap as "made 1,000,000" posts.

    This also makes the system much more extensible.

    Doug McClean : If you go this route, be careful of the cases when you add a new badge and need to analyze what existing users should have already earned it.
    Will Hartung : Yes, absolutely a downside of the system, but still its more flexible and scalable as (typically) adding new badges happens far less than testing and awarding them.
    Micah : So how would you handle adding badges down the road? Let 's say I have a new badge like the "woot" badge that SO added. How would you make it retroactive?
    Will Hartung : You would need to have some mechanism to rerun the event history data to accumulate the statistics necessary for your new badge and bring it up to date.
  • I agree with Will on this one.

    Create "events" over the pages so every time an event happens ie. a user deletes a post, it will query the event module with the event, lets say, EVENT_USER_DELETE_POST and then you can select that event and build a query based on it. You can then decide if a badge is awarded or not.

    This will keep the two logics seperate and keep a modular design. It should be very easy to implement this way.

    The only downside is that if the event was not "captured" then a user may well have earned a badge criteria but it has not yet been rewarded. However, this should never occur. The only situation I can think of is if the database is manipulated manually.

In Eclipse, how do I change perspectives after terminating a process?

So Eclipse by default automatically switches to the Debug perspective when you hit a breakpoint. However, it is annoying me that it doesn't automatically switch back to the previous perspective (say, Java) when terminating the process. It just stays in the debug perspective even though there is nothing to debug because nothing is running.

Is this possible?

From stackoverflow
  • you would need to write eclipse plugin

    here i found example how in plugin switch perspective

    helifreak : I am surprised that such a fundamental user interaction is missing from what is supposedly the worlds most used IDE.
  • To complete mark's answer, that option tells Eclipse when to switch to the associated perspective upon program suspension - meaning when a breakpoint is hit, it will switch to Debug perspective.

    Switching back to another perspective after you're done debugging has to be manual

    alt text

    If you want to avoid it switching to Debug in the first place, you can choose "Never" as the option.

    alt text

    If you want to switch back in the situation where the debugged program terminates normally (Not when you want to stop debugging it yourself), you may hope Eclipse figures out that your program terminates normally and switch to a "default" perspective at that time...

    However, there is no notion of "default" perspective, so how would Eclipse knows which one to switch to ? (the "Preferences/Perspectives/Make default" is only for the "Open Perspective" dialog, but that may not be the same perspective than the one you actually want to switch back to after a debug)

    alt text

    Also, should Eclipse closes the Debug perspective or just changes to a different one ?
    What if there is more than one program running -- when one terminates, you might still be interested in debugging the other one, or maybe not.

    The point is, the decision about when to change perspective (and what perspective to change to) is not reasonable for the machine to make -- it requires a person knowing what he wants to do next.

    Joe Ludwig : I agree with everything but "is not reasonable for the machine to make ". Visual Studio does a fine job by returning to the main view when there are no processes left to debug.
    VonC : @Joe Ludwig: agreed. Eclipse may be victim of its own complexity, tricking itself into *not* offering this feature.
    VonC : @Joe Ludwig: btw, sorry: I did not play at Pirate: I am not so much into MMO... Right now, I play GTAIV (solo) ;)
    helifreak : I think the appropriate solution would be to switch back to the previous perspective that I was in before the debug perspective, if all debug sessions have ended. As Joe mentioned, Visual Studio, and all other IDEs i've used do this by default.
  • I filed a bug for this:

    https://bugs.eclipse.org/bugs/show_bug.cgi?id=327983

VBA String sanitation

I get data imported from an Oracle database and use Excel to create some reports from that. Recently one of our data entry folks has started beginning her entries with "+". Excel than evaluates that and adds = then displays the dreaded ?name# error. The error is error 2029.

I tried using

If IsError(C.Value) Then
    C.Value = Replace(C.Value, "=+", "", 1, -1, vbTextCompare)
End If

But that isn't getting me anywhere.

Any suggestions?

From stackoverflow
  • Excel has it's own replace function:

    ActiveSheet.Cells.Replace What:="=+", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
    
    CABecker : When I run that I get runtime error '438' obeject dosen"t support this property or method
    DJ : oops - try again with the "Cells" - which returns a range object of all the cells in the worksheet
  • If you have the data in a text/CSV file then you can try: Data > Import External Data > Import Data This launches a wizard which lets you specify specific columns as text and that causes symbols like +, - etc not to be parsed by Excel

    In VBA this can be done through the Worksheet("foo").QueryTables.Add method. There are quite a few options but the TextFileColumnDataTypes property lets you specify which columns to treat as text. It might be easier to work out what is happening by recording a macro of the wizard being used and then editing that to suit

    If you're reading in the data more directly (e.g. via ADO or DAO) then just make sure the destination cell is in text format before the data is added

    Worksheet("foo").Cells(r, c).NumberFormat = "@"


    NB in your original solution, you almost certainly wanted to look at C.Formula rather than C.Value If a cell C had a formula of =123+456 then C.Value would be 579 whereas C.Formula would be =123+456

    +1 on using the built-in Replace method in this context

    CABecker : Thank you barrowc, your final answer turned the trick, I forgot about looking at the .formula rather than the .value
  • Just one other thing too, it should be:

    If IsError(C.Value) Then
        C.Value = Replace(C.Formula, "=+", "", 1, -1, vbTextCompare)
    End If
    

    This is because the =+ is stored in the formula property, not the value...You can assign the replace(...) to C.Value or C.Formula if you don't want to do the cleanup yourself in VBA

Passing a work item between threads (Java)

I have two threads. The producer is producing pieces of data (String objects), where the consumer processes these strings. The catch is that my application only needs the most recent data object to be processed. In other words, if the producer managed to produce two strings "s1" and then "s2" then I want the consumer to process only "s2". "s1" can be safely discarded.

Of course there's no problem implementing a class that realizes this behavior, but I want to use a standard mechanism from java.util.concurrent (if such a mechanism exists). Note that SynchronousQueue is not a good solution: the consumer will block when enqueueing "s1" and will not get the chance to produce "s2".

(In short, I am looking for a single-element collection with a blocking remove operation and a non-blocking set operation)

Any ideas?

From stackoverflow
  • You could use an array of size one for that:

    String[] oeq = new String[1];
    

    Sample source:

    public class Test {
        private static final String[] oeq = new String[1];
        public static void main(String[] args) {
            (new Producer()).start();
            (new Consumer()).start();
            (new Consumer()).start();
            (new Consumer()).start();
            (new Consumer()).start();
            (new Consumer()).start();
            (new Consumer()).start();
        }
    
        private static class Producer extends Thread {
            public void run() {
                int i=0;
                while(true) {
                    i++;
                    synchronized(oeq) {
                        oeq[0] = ""+i;
                        oeq.notifyAll();
                    }
                }
            }
        }
    
        private static class Consumer extends Thread {
            public void run() {
                String workload = null;
                while(true) {
                    synchronized(oeq) {
                        try {
                            oeq.wait();
                        } catch(InterruptedException ie) {
                            ie.printStackTrace();
                        }
                        if(oeq[0] != null) {
                            workload = oeq[0];
                            oeq[0] = null;
                        }
                    }
                    if(workload != null) {
                        System.out.println(workload);
                    }
                }
            }
        }
    }
    
    Peter Štibraný : This will be very inefficient. Consumer thread should not block CPU while waiting for work.
    kdgregory : Actually, consumer here would consume all CPU, as there's no wait() in the loop (this may be what you meant by "block"). Which is why, I think, the OP wanted to use an existing JDK class -- it's easy to write a broken homegrown concurrent object.
    Johannes Weiß : Both hints are true, I fixed the first one, thanks.
    kdgregory : OK, to the point of homegrown concurrency objects being broken: why are you extending Thread?
    Johannes Weiß : implementing Runnable would have been better probably. It's a quick sample
    Johannes Weiß : or do you mean anything else?
    Johannes Weiß : Exchanger seems to be the way to go!
  • I think your best answer is probably to use ArrayBlockingQueue, where the producer (you only have one producer, right?) removes any existing element before adding the new element.

    Sure, there are race conditions in this implementation: the consumer could start processing an element just before the producer removes it. But those race conditions will always exist, no matter what data structure you use.

  • What about the Exchanger class? This is the standard way of exchanging objects between threads. Specialize it with your class, may be a list of strings. Make the consumer only use the first/last one.

    kdgregory : probably a better approach than mine, although you do need to set the producer's timeout to 0
    Peter Štibraný : Exchanger also blocks producer :-(
    kdgregory : unless you set the timeout to 0 (or a negative number)
  • Well, if you only want the most recently produced string, then you don't need a queue at all - all you need is a string reference: the producer sets it, the consumer reads it. If the consumer takes so long to read it that the producer re-sets it ... so what?

    Setting and reading references are atomic. The only issue is if you want the consumer to somehow be notified that there's a string available. But even then ... if the consumer is doing something that takes a while, then you really don't need any fancy-pants stuff from the concurrency libraries.

    Note, btw, that this example works with any number of producer and/or consumer threads.

    import java.util.Random;
    
    public class Example {
        public static void main(String[] av) {
         new Example().go();
        }
    
        Object mutex  = new Object();
        String theString = null;
    
        void go() {
         Runnable producer = new Runnable() {
          public void run() {
           Random rnd = new Random();
           try {
            for (;;) {
             Thread.sleep(rnd.nextInt(10000));
             synchronized (mutex) {
              theString = "" + System.currentTimeMillis();
              System.out.println("Producer: Setting string to " + theString);
              mutex.notify();
             }
            }
           } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           }
    
          }
         };
    
         Runnable consumer = new Runnable() {
          public void run() {
           try {
            String mostRecentValue = null;
            Random rnd = new Random();
            for (;;) {
             synchronized (mutex) {
              // we use == because the producer
              // creates new string
              // instances
              if (theString == mostRecentValue) {
               System.out.println("Consumer: Waiting for new value");
               mutex.wait();
               System.out.println("Consumer: Producer woke me up!");
              } else {
               System.out.println("Consumer: There's a new value waiting for me");
              }
              mostRecentValue = theString;
             }
             System.out.println("Consumer: processing " + mostRecentValue);
             Thread.sleep(rnd.nextInt(10000));
            }
           } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           }
          }
         };
    
    
         new Thread(producer).start();
         new Thread(consumer).start();
        }
    }
    
    kdgregory : you need to make the reference volatile, and be running in a 1.5+ JDK, for this to be guaranteed (the Java Memory Model allows a thread to maintain its own copy indefinitely otherwise)
    paulmurray : Yup - forgot that bit.

NSImage - after crop PDF is blurry

I'm trying to crop a NSImage which contains a PDF. When printing I am using NSImage's drawInRect to have it draw only what I need - and this works great.

But, now instead I'm trying to create a new NSImage of just the cropped area. I played with it for a while, then found this code on CocoaBuilder:

- (NSImage *) imageFromRect: (NSRect) rect
{
  NSAffineTransform * xform = [NSAffineTransform transform];

  // translate reference frame to map rectangle 'rect' into first quadrant
  [xform translateXBy: -rect.origin.x
                  yBy: -rect.origin.y];

  NSSize canvas_size = [xform transformSize: rect.size];

  NSImage * canvas = [[NSImage alloc] initWithSize: canvas_size];
  [canvas lockFocus];

  [xform concat];

  // Get NSImageRep of image
  NSImageRep * rep = [self bestRepresentationForDevice: nil];

  [rep drawAtPoint: NSZeroPoint];

  [canvas unlockFocus];
  return [canvas autorelease];
}

This works, but the returned NSImage is blurry, and no longer suitable for printing. Any ideas?

From stackoverflow
  • lockFocus/unlockFocus performs raster drawing to the image's cache. That's why it's “blurry”—it's low-resolution and possibly misregistered. You need vector drawing.

    Use PDF Kit. First, set the crop box of each page to your rectangle. You should then be able to create your cropped NSImage from the dataRepresentation of the PDFDocument.

  • Here is the code to perform what Peter Hosey answered. Thanks!

    PDFDocument *thePDF = [[PDFDocument alloc] initWithData:pdfData];
    PDFPage *thePage = [thePDF pageAtIndex:0];
    NSRect pageCropRect = NSMakeRect(0, 100, 100, 100);
    
    [thePage setBounds:pageCropRect forBox:kPDFDisplayBoxMediaBox];
    NSImage *theCroppedImage = [[NSImage alloc] initWithData:[thePage dataRepresentation]];
    
    Peter Hosey : Make sure you duly release or autorelease thePDF and theCroppedImage.

Functional style C# API design (returning function parameter augmented with calculation result)

Hi,

There is a question regarding usage of functional programming techiques in C# code. Example

Let we have interface

interface IGraph { /*contains vertices and edges*/}

Suppose we need to layout graph's vertices (assign Point to each vertex).

interface ILayoutInfo {
  Point GetVertexPoint(vertex);
}

Simple layout route can have such signature:

ILayoutInfo SimpleLayout(IGraph graph);

Which can be used in such way

void Demo() {
  IGraph graph = CreateGraphInAnyWay();
  ILayoutInfo layout = SimpleLayout(graph);
  PrintCoordinates(graph,layout);
}

In design below PrintCoordinates need both references to graph and layout.

Consider functional style design where layouting routing augments graph information with information about graph vertices coordenates.

ILayoutedGraph SimpleLayoutNew(IGraph graph);

Where ILayoutedGraph implements BOTH IGraph and ILayoutInfo

void DemoNew() {
  IGraph graph = CreateGraphInAnyWay();
  ILayoutedGraph layoutedGraph = SimpleLayoutNew(graph);
  PrintCoordinatesNew(layoutedGraph);
}

1)In this design PrintCoordinatesNew gets only ONE parameter. 2)Weird interface ILayoutedGraph was born which doesn't contain any methods and just wraps other interfaces. If some library has other types like INetwork, ITree we end up creating wrap interfaces ILayoutedNetwork, ILayoutedTree (which is bad).

So such techique is used only in functinal languages just because they can't work in other way (there are no state so function must combine input with calculated info to be used by outer routines) or it is viable in imperative world too?

Thanks a lot,

PS: a more verbose pretty printed example can be found here http://tivadj.blogspot.com/2009/02/designing-c-api-in-functional-style.html

From stackoverflow
  • Can you implement this using a class that implements both interfaces and casting the returns as that class?

    tivadj : The problem is what API (interfaces) to publish: traitional style case1) IGraph, ILayoutInfo and SimpleLayout(IGraph):ILayoutInfo or functional style case2) IGraph, ILayoutedGraph SimpleLayoutNew(IGraph):ILayoutedGraph ==== ILayoutedGraph really can be implemented by some internal class.
  • There is no problem with your original API of

    void Demo() {
      IGraph graph = CreateGraphInAnyWay();
      ILayoutInfo layout = SimpleLayout(graph);
      PrintCoordinates(graph,layout);
    }
    

    It is perfectly functional. An imperative API would involve a change to graph once it is created. Eg

    void Demo() {
      IGraph graph = CreateGraphInAnyWay();
      graph.Layout(new SimpleLayout()); // changes the state of graph
      PrintCoordinates(graph);
    }
    

    As for the problem of ILayoutedGraph, ILayoutedTree, ILayoutedQueue, etc, I think you would get around this by generic classes in a functional languages and multiple inheritance in the OO languages where this is allowed.

    Personally, I would recommend generics: ILayout<a> where a is something with edges that needs to be laid out.

  • If seems that what disturbs you when passing two arguments is that your layout (ILayoutInfo) is linked to the graph used to generate it. I would be meaningless to pass a layout with a graph that was not used to generate it.

    In this case, you can keep a reference to the graph in the layout info, and provide an accessor on the ILayoutInfo interface.

    This way, you can only pass the ILayoutInfo instance, and you PrintCoordinates function can still acces the graph that was used to generate the ILayoutInfo.

    If you have other kind of object that can generate layout infos, use a common interface for them, or make the ILayoutInfo generic.

    tivadj : Thanks. You really give me a breath of fresh air.

Python cannot create instances

I am trying to create a simple Python extension using [PyCXX]. And I'm compiling against my Python 2.5 installation.

My goal is to be able to do the following in Python:

import Cats

kitty = Cats.Kitty()

if type(kitty) == Cats.Kitty:
    kitty.Speak()

But every time I try, this is the error that I get:

TypeError: cannot create 'Kitty' instances

It does see Cats.Kitty as a type object, but I can't create instances of the Kitty class, any ideas?

Here is my current source:

#include "CXX/Objects.hxx"
#include "CXX/Extensions.hxx"
#include <iostream>

using namespace Py;
using namespace std;

class Kitty : public Py::PythonExtension<Kitty>
{
    public:
        Kitty()
        {
        }

        virtual ~Kitty()
        {
        }

        static void init_type(void)
        {
            behaviors().name("Kitty");
            behaviors().supportGetattr();

            add_varargs_method("Speak", &Kitty::Speak);
        }

        virtual Py::Object getattr( const char *name )
        {
            return getattr_methods( name );
        }

        Py::Object Speak( const Py::Tuple &args )
        {
            cout << "Meow!" << endl;
            return Py::None();
        }
};

class Cats : public ExtensionModule<Cats>
{
    public:
        Cats()
            : ExtensionModule<Cats>("Cats")
        {
            Kitty::init_type();

            initialize();

            Dict d(moduleDictionary());
            d["Kitty"] = Type((PyObject*)Kitty::type_object());
        }

        virtual ~Cats()
        {
        }

        Py::Object factory_Kitty( const Py::Tuple &rargs )
        {
            return Py::asObject( new Kitty );
        }
};

void init_Cats()
{
    static Cats* cats = new Cats;
}


int main(int argc, char* argv[])
{
    Py_Initialize();

    init_Cats();

    return Py_Main(argc, argv);

    return 0;
}
From stackoverflow
  • I do'nt see it in the code, but sort of thing normally means it can't create an instance, which means it can't find a ctor. Are you sure you've got a ctor that exactly matches the expected signature?

    happy_emi : You are right I think. He has to "register" the name Kitty as a type somewhere

Is null a Java keyword?

Is null is a keyword in Java?

From stackoverflow
  • No.It is not a keyword.

  • Not according to the Java Language Specification list of keywords. On the other hand, this doesn't compile:

    int null = 10;
    

    The rules for identifiers specify that:

    An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7).

    I'm not sure what the benefit of making it not-a-keyword is, to be honest.

    Gamecat : Lol, this answer implies that there are implementations of Java that accept null as a keyword.
    tehvan : Gamecat, the way i read it, it says clearly the spec does _not_ consider null a keyword.
  • Not a keyword - the null literal.

    an identifier (oops, no it isn't)

    Jon Skeet : It's not an identifier either, according to http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#40625
    Marc Gravell : Yes, I realised by mistake already and fixed it...
    Tom Hawtin - tackline : Up vote just because it's a trick question...
  • No. See this for complete list KeywordList

  • true and false are also literals. Java trivia: const and goto are keywords.

  • null is a literal, in the same sense that false, 10, and '\n' are literals. It's not a "keyword", technically, but it is a character string that is treated specially by the compiler if the compiler encounters it in a java source file.

    So, no, you cannot name a variable "null". The lexical analyzer will decide that it is not an identifier.

How do I emit the text content of a reference in LaTeX?

I have a section:

\section{Introduction} \label{sec:introduction}

I'd like a link to the section where the link text is the name of the section. I can use hyperref:

The \hyperrf[sec:introduction]{Introduction} introduces the paper.

But that requires repeating the section title ("Introduction"). Is there a way to grab that? ref yields the section number, which isn't right. autoref yields "section " and then the section number, which isn't right, either.

From stackoverflow
  • You could try using

    • \newsavebox
    • \savebox
    • \usebox

    which won't save you any typeing but will give you a single authoritative source for each title


    And you might search ctan.org, I suspect this has been done already.

  • As far as I know, there's no standard way to do this. Simply put, the sectioning commands don't store the names of the sections anywhere they can be easily retrieved. Yes, they're inserted into the Table of Contents (and associated auxiliary file) and marks are set, but access to those is unreliable at best and usually impossible without additional context, which is almost always unavailable by the time you need to refer back to the section.

    The code sample you posted looks like what I would write. There might be a package to automate this, but if one exists it's probably pretty hairy code since this is really not a particularly common use case. Actually, to go all grammar nazi on you the final text you're creating is incorrect; the word "introduction" should be lowercase inside the sentence, and this can't be achieved (in general) with backreferences to the actual section titles.

    I'd just suck it up and write out references like this manually. There won't be enough of them to justify automation. Of course, if you're doing something more involved than your example suggests (many auto-generated sections or something) things might be different, but if that's the case it's really a different question entirely.

    Will Robertson : You make some good points but there are packages available to do this.
    kquinn : See, that's what I get for leaving my copy of the LaTeX Companion on my desk at work, and being too lazy to google for packages....
  • There are a couple of packages that provide this for you. nameref is distributed as part of hyperref to do this:
    http://tug.ctan.org/cgi-bin/ctanPackageInformation.py?id=nameref

    There is a more general package for cross-referencing basically anything, called zref: http://tug.ctan.org/cgi-bin/ctanPackageInformation.py?id=zref

    It's by the same author as hyperref, Heiko Oberdiek; it's the one that I would choose. Here's an example:

    \documentclass[oneside,12pt]{article}
    \usepackage[user,titleref]{zref}
    \begin{document}
    \section{Introduction of sorts.}\zlabel{sec:intro}
    Hello
    \subsection{Structure}
    We begin in `\ztitleref{sec:intro}'.
    \end{document}
    

    Note that it even removes the trailing period in the section title.

How to manage table without id in Rails?

I have two models: Person and Relation. The second one stores information about relations between two people. It has parent_id and child_id fields and doesn`t have id field. I connected it with has_many :through and it works.

But:

  1. Relation.find(:all) returns empty array even if there are some relations in the table (becouse there is no id field).
  2. I don`t know how to delete relation.

My models looks like this:

class Person < ActiveRecord::Base
  has_many :child_relations, 
           :class_name => "Relation", 
           :foreign_key => "parent_id"
  has_many :parent_relations, 
           :class_name => "Relation", 
           :foreign_key => "child_id"

  has_many :children, :through => :child_relations
  has_many :parents, :through => :parent_relations
end

class Relation < ActiveRecord::Base
  belongs_to :parent, :class_name => "Person"
  belongs_to :child, :class_name => "Person"
end

Any suggestions?

UPDATE: I've used has_many :through becouse I also store information about a type of the relation in the table. Currently I gave up and I added id field to my table (Rails convention...). But my question remains open.

From stackoverflow
  • has_many :through depends on an id in the join table. It makes the join table a whole model. Since every operation with records happens with an id, you wont be able to directly interface with a table without it. When you delete a record rails generates sql to delete the record by its id. If you have a join table that acts as a full model, it must have an id

    Or you can use has_and_belongs_to_many which works more like you expect. The remove a relationship you remove the object via its assocations and not directly with the relationship model.

    Your best bet is to add an ID to the join table. That way in the future if the relationship model becomes more complex you can track it as its own entity.

  • This should give you a step in the right direction. I am not at a rails prompt to test it, but it should be pretty quick to set up a model and try it. Hope it helps!

    class Relation < ActiveRecord::Base
      belongs_to :parent, :class_name => "Person", :foreign_key => :parent_id
      belongs_to :child, :class_name => "Person", :foreign_key => :child_id
    end
    
    class Person < ActiveRecord::Base
      has_many :relations
      has_many :children, :through => :relations
      has_many :parents, :through => :relations
    end
    
    klew : It doesn't work. You should set foreign keys in Person model, not in Relation. In Relation model Rails will guess names of foreign keys, becouse it will add _id to associations names (parent and child). So probably models specifications should stay as I proposed in my question. But anyway thanks!
  • I've successfully used the has_and_belongs_to_many in this situation. The join table only has foreign keys, no id key. One important thing is that you don't have a model for the Relations table, just the two has_and_belongs_to_many references in the Person class

    Here is a good thorough treatment on Has and belongs to many

How much documentation is optimal for an Agile project?

I recently joined a new project utilizing Agile methodology. The documentation is scarce to none, except for sticky papers on the whiteboard indicating stories, completed, in-progress, etc. The project is a web app for a workflow that is fairly complicated. Is this common or is it still useful to have functional/tech specs, etc. with Agile? What is the optimal amount of documentation for a fairly complex Agile web project?

From stackoverflow
  • Enough that it's clear. It's tid to the complexity of what's being built for me.

    I'm excited about using balsamiq in my next project to see what I can do away with.

  • As little as your team and client is comfortable with.

    Mark Brittingham : +1 Nice answer, good links
  • One of the tenets of most agile frameworks is to keep your technical debt in check by constant improvement and refactoring. This process results in highly readable and maintainable code. Thus you generally don't need much documentation; you can read the code. If this isn't the case on your project then you might consider that your engineering practices are in need of fixing rather than more documentation. Although a certain amount of high level docs are useful,and possibly necessary depending on the system; the general feeling should be that docs = waste.

    alchemical : I don't want to get you in trouble by clicking "offensive", so I'll just leave a comment. "You can read the code" and "docs=waste" is sheer lunacy. Unfortunately, I think many would agree with you--the travesty of Agile is people using it to justify their existing bad habits!
  • I don't think that you need any documentation.

    No Documentation

    alchemical : I'm calling this the best answer at this point as I think highlights a very real problem right now--people using Agile as an evangelical/theological basis for being lazy with process, rather than as a way to improve development of solutions to business problems.
  • We use Scrum along with Agile. Although the amount of documentation we generate is not much.. we tend to include the documentation in the code itself. Or documentation can itself be classified into a subtask and have an associated burn down chart.

xdocument question

I have two documents both are similar but I need to find an elegant and efficient way to compare the two files and return the values in Doc #1 that don't exist in Doc #2.

XML Doc #1

      <ids>
        <id>1</id>
        <id>2</id>
        <id>5</id>
        <id>6</id>
        <id>7</id>
        <id>8</id>
        <id>9</id>
       </ids>
    </ids>

XML Doc #2

  <ids>
    <id>1</id>
    <id>2</id>
    <id>7</id>
    <id>8</id>
    <id>9</id>
  </ids>

I was thinking about using linq if I could join these two documents on the id field. Is there a better way? I'm looking to return id #s 5 and 6.

From stackoverflow
  • Here is a sample that I know works, I only tried it out with small files (File1.xml had 20 items, File2.xml 8 items).

    XDocument file1Doc = XDocument.Load("File1.xml");
    XDocument file2Doc = XDocument.Load("File2.xml");
    
    IEnumerable<string> file1Elements = from d in file1Doc.Descendants("Id")
                                        select d.Value;
    
    IEnumerable<string> file2Elements = from d in file2Doc.Descendants("Id")
                                        select d.Value;
    
    var difference = file1Elements.Except(file2Elements);
    

    Alternatively, and likely more inline with what you seek is:

    XDocument file1Doc = XDocument.Load("File1.xml");
    XDocument file2Doc = XDocument.Load("File2.xml");
    
    IEnumerable<string> file2Elements = from d in file2Doc.Descendants("Id")
                                        select d.Value;
    
    var x = from include in file1Doc.Descendants("Id")
            where file2Elements.Contains(include.Value) != true
            select include;
    

    You might also find some help looking at 101 LINQ Samples on MSDN.

    Richard C. McGuire : glad I could help

jquery drag/drop problem: drop() function never gets called.

Hello,

I'm having trouble with the droppable effect in jquery 1.3.1 (UI version 1.5.3). As far as I can tell, everything works perfectly except the drop() function doesn't get called. I can tell the droppable target is accepting the element being dragged (via the thumbnail class), but the draggable item won't drop. Thanks for your help in advance!

<html>
<head>
<script type="text/javascript" language="javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript" language="javascript" src="/jquery/jquery.ui.js"></script>
<script type="text/javascript" language="javascript">
//<!--
    $(document).ready(function() {
     $('.drop_box').droppable({
      accept: '.thumbnail',
      activeClass: 'droppable-active',
      hoverClass: 'droppable-hover',
      drop: function (ev, ui) { 
       alert("Dropped!"); 
      }
     });

     $('#sample_thumbnail').draggable({ 
      helper: 'clone'
     });
    });
//-->
</script>
<style type="text/css">
    .drop_box {
     top:16px;
     width:250px;
     height:250px;
     border:1px solid #000000;
     float: right; 
    }
    .droppable-hover {
     background-color: #eeeeee;
     border: 1px solid red;
    }
    .droppable-active {
     background-color: orange;
     color: white;
     border: 1px solid blue;
    }
    .thumbnail {
     width:100px; 
     height:100px;
     border:1px solid green;
    }
</style>
</head>
<body>
<div class="drop_box">droppable</div>
<div id="sample_thumbnail" class="thumbnail">draggable</div>
</body>
</html>
From stackoverflow
  • "jquery 1.3.1 (UI version 1.5.3)"

    You should not be using this pair of versions. JQuery 1.3.x is not compatible with the UI 1.5.x series, and requires the 1.6 release candidates. The release candidate versions are quite stable if you just want the drag and drop functionality; I wouldn't be concerned at all for using them in production. I only use drag and drop, so I can't comment on the stability of the rest of the 1.6 branch of UI.

  • I don't have any problems with your code on either Mac/Safari or Mac/Firefox using jQuery 1.2.6 and jQuery UI 1.5.3. I think your issue is with incompatible versions.

How do I enter a multi-line footnote in LaTeX?

My intuition was

Lorem ipsum\footnote{long footnote
  that spans a whole
  bunch of
  lines.
}

But regardless of where I put the { and } in relation to the footnote text, I get the following error:

Latex Error: ./mydoc.tex:142 Package inputenc Error: Unicode char \u8:― not set up for use with LaTeX.
From stackoverflow
  • The error you're getting indicates there's a coding setup issue. Googling the error message suggests you may be running TexShop, or you need to install latex unicode support. use

    apt-get latex-ucs
    

    or something similar and try it again.

  • Footnotes are filled in the availible space just like any other paragraph: you just write

    \footnote{ 
        a whole lot of text that goes on and on and on and...
        ...
        and may consists of multiple sentences. But after a while
        ... 
        it finally comes to a stop.
    }
    

    That is not your problem. looking at the error message (which I don't recognize from personal experience), I'd say your problem is character set or font related.

    Is you editor using unicode?

    James A. Rosen : it was a random UTF-8 character in my footnote source -- stupid copy and paste.
    James A. Rosen : Now, of course, I _want_ some unicode in my document and I can't seem to get it. Thanks for pointing me in the right direction.
    dmckee : I think you want Charlie's advice for that...