Friday, March 4, 2011

Retrive browser and OS in PHP

Hi friends,

I need to retrive the browser and OS through php coding.

I had used $_SERVER['HTTP_USER_AGENT'], but its shows the following

Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; IEMB3)

How can i separate the browser and Os from the above received value..

Please guide me..

Thanks in advance

From stackoverflow
  • Grab a copy of browscap.ini compare $_SERVER['HTTP_USER_AGENT'] with that file.

  • Hi, you can use simple explode();

    <?php
    $ex=explode(' ',$_SERVER['HTTP_USER_AGENT']);
    echo 'OS: '.$ex[4].' '.$ex[5].' '.$ex[6].'/n'; 
    echo 'Browser: '.$ex[0]; 
    ?>
    
  • Just use the built in function for this http://ie.php.net/manual/en/function.get-browser.php

  • You could use the Google code Browscap class. It essentially does the same thing as PHP's get_browser(), but you don't have to worry about keeping your browscap.ini up to date.

    This worked for me:

    require('Browscap.php');
    $browscap = new Browscap('/path/to/cache');
    var_dump($browscap->getBrowser());
    
  • The best way would be using the buil-in get_browser() function as it's a few times faster than the Google-Code-version if you're only running it once. (If you're running it 4+ times the Google-Code-version is faster)

    So unless you need the auto-update and only use one check at a time, you should use the built-in version. :)

    And it shouldn't be that hard to make a cronjob to get the newest version. ;)

Starting project from scratch: how and when to distribute the workload?

Hello,

My friend and I are going to develop a new commercial web project. We have a kind of a document that lists all the things that we want to have and we are wondering what is the best way to actually start coding it. The thing is that we used to develop software either in solo-mode or join some projects that were in the middle of development and responsibilities are easy to distribute between members of a team. Now we're starting from scratch and there're obviously things like database design or some essential functionality development, absence of those would be a showstopper for either of us. Also we have like seven hours time difference between us.

Again, we know how teamwork works, we have all the tools we need and we know how to spread the workload when all the groundwork is done, however how to start the groundwork in a distributed team, when everything depends on the results of this groundwork? If there's no database, how my party can start working on the user dashboard functionality?

So, how you guys would start such a development process? At which point you can easily start distributing workload between team members?

I'm wondering if Joel and Jeff could share their experience on the subject, given that Stack Overflow was developed by distributed team in quite a short time.

Thanks!

From stackoverflow
  • Try listening to the earlier episodes of the Stack Overflow podcast for insight into the SO dev process.

  • Also, look into Extreme Programming. Not all the details fit this, but there is a technique that will do you great good: organize the project into small "user stories", which describe one little bit of end-to-end functionality, define an "aceptance test" that tells you when a user story is done, and then work on one user story at a time, or one each.

  • heed the wisdom of Charlie Martin, but also have at least a gentleman's agreement between the two of you as to responsibilities and commitments for completion and commercialization.

    It's one thing to say "yeah i'll help you write the whizbang.com site", but it's quite another to commit to maintaining it, supporting it financially, marketing it, and making it work as a business

    : Yes, we do have an agreement and will form an LLC eventually, when the thing will take off. All we need now is a way to start the damn thing! :)
  • I have worked with distributed teams before, The most important thing you need to have is clarity of your goals, milestones and responsibilities. There are many tools on the net to help you with this project:

    • Google code < You can use this as your code repository.
    • Checkout the tools at 37signals.com, they have a few good tools for collaboration and the basic versions are free
    • You can use crossloop to share your screen to fix things and discuss them.
  • I clarified my question a little bit.

Haskell Function Application

A bit of a neophyte haskell question, but I came across this example in Haskell's tutorial examples. For "find the last element of a list" there are some obvious versions, like

last' [x] = x
last' (_:xs) = last' xs

But I can't make sense of an alternate version presented:

myLast' = foldr1 (const id)

So, in trying to make sense of what the application of the id function is doing, I tried in ghci:

const id 1 2 -> gives 2

This binds like this:

(const id) 1 2 -> gives 2

And not like this:

 const (id 1) 2 -> gives 1

But I'm not making sense of this. (const id) should translate to something like

`(\x y->x) (\x->x)`

Shouldn't this return a function that simply returns the id of its first element? Or, how is the function order making (const id) behave differently than const?

From stackoverflow
  • The definition of const is

    const x = \_ -> x
    

    Hence, (const id) is a function which takes one argument and always returns id and

    const id 1 2 = (\_ -> id) 1 2
                 = id 2
                 = 2
    

    The definition of foldr1 is

    foldr1 f [x] = x
    foldr1 f (x:xs) = f x (foldr1 f xs)
    

    If we have

    myLast' = foldr1 (const id)
    

    then

    myLast' [x] = foldr1 (const id) [x]
                  {- definition of foldr1 -}
                = x
    

    and

    myLast' (x:xs) = foldr1 (const id) (x:xs)
                     {- definition of foldr1 -}
                   = (const id) x (foldr1 (const id) xs)
                     {- definition of const -}  
                   = (\_ -> id) x (foldr1 (const id) xs)
                     {- function application -}  
                   = id (foldr1 (const id) xs)
                     {- definition of id -}  
                   = foldr1 (const id) xs
                     {- definition of myLast' -}  
                   = myLast' xs
    

    which agrees with the definition of last'.

    Steve B. : ahhh. Didn't make the connection of the const returning the function. Thanks for the explanation.
    J Cooper : This is a great explanation, and stepping through it I can see how it works. But is foldr1 (const id) really the idiomatic way to do a myLast function? The first example given seems way more clear...
    Chris Conway : I wouldn't say it's idiomatic... Haskell geeks enjoy working out how to express things in a "point-free" style, or purely in terms of folds. It becomes a kind of programming puzzle. The first version is much more clear.
  • I rely heavily on :t when trying to understand Haskell. In this case:

    Prelude> :t const id
    const id :: b -> a -> a

    might have helped you see what was going on.

    Jay Conrod : To clarify, ":t" is a command you can use in GHCI to print the type of an expression.

Writing a compiler for a DSL in python

I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing python tools which can do this more easily, like re2c which is used in the PHP engine.

Some extra info:

  • Yes, I do need a DSL, and even if I didn't I still want the experience of building and using one in a project.
  • The DSL contains only data (declarative?), it doesn't get "executed". Most lines look like:

    SOMETHING: !abc @123 #xyz/123

    I just need to read the tree of data.

From stackoverflow
  • There are plenty of Python parsing tools: http://nedbatchelder.com/text/python-parsers.html

  • Yes, there are many -- too many -- parsing tools, but none in the standard library.

    From what what I saw PLY and SPARK are popular. PLY is like yacc, but you do everything in Python because you write your grammar in docstrings.

    Personally, I like the concept of parser combinators (taken from functional programming), and I quite like pyparsing: you write your grammar and actions directly in python and it is easy to start with. I ended up producing my own tree node types with actions though, instead of using their default ParserElement type.

    Otherwise, you can also use existing declarative language like YAML.

  • I've always been impressed by pyparsing. The author, Paul McGuire, is active on the python list/comp.lang.python and has always been very helpful with any queries concerning it.

    Torsten Marek : I would have suggested it if you hadn't done it already! PyParsing is awesome.
  • Here's an approach that works really well.

    abc= ONETHING( ... )
    xyz= ANOTHERTHING( ... )
    pqr= SOMETHING( this=abc, that=123, more=(xyz,123) )
    

    Declarative. Easy-to-parse.

    And...

    It's actually Python. A few class declarations and the work is done. The DSL is actually class declarations.

    What's important is that a DSL merely creates objects. When you define a DSL, first you have to start with an object model. Later, you put some syntax around that object model. You don't start with syntax, you start with the model.

    too much php : I know what you're saying, but writing all those comments, parenthesis, equals, prefixes is obfuscating the actual data. Also, this method doesn't port well to more verbose languages like PHP or Java.
    S.Lott : @Peter. Disagree. You can use positional args and eliminate the labels and ='s. It translates perfectly to Java. Already used it in production applications to define a declarative DSL.
    Mendelt : I've seen what you're suggesting referred to as an internal DSL. I like this method. One problem might be that while the method does port to other languages (i've seen stuff like this implemented in C#) the precise syntax of your DSL will probably change a bit. The map files won't be portable.
    S.Lott : @Mendelt: Didn't see portability as a requirement. You're right, but it doesn't seem to apply in this case.
  • I have written something like this in work to read in SNMP notification definitions and automatically generate Java classes and SNMP MIB files from this. Using this little DSL, I could write 20 lines of my specification and it would generate roughly 80 lines of Java code and a 100 line MIB file.

    To implement this, I actually just used straight Python string handling (split(), slicing etc) to parse the file. I find Pythons string capabilities to be adequate for most of my (simple) parsing needs.

    Besides the libraries mentioned by others, if I were writing something more complex and needed proper parsing capabilities, I would probably use ANTLR, which supports Python (and other languages).

  • Peter,

    DSLs are a good thing, so you don't need to defend yourself :-) However, have you considered an internal DSL ? These have so many pros versus external (parsed) DSLs that they're at least worth consideration. Mixing a DSL with the power of the native language really solves lots of the problems for you, and Python is not really bad at internal DSLs, with the with statement handy.

  • For "small languages" as the one you are describing, I use a simple split, shlex (mind that the # defines a comment) or regular expressions.

    >>> line = 'SOMETHING: !abc @123 #xyz/123'
    
    >>> line.split()
    ['SOMETHING:', '!abc', '@123', '#xyz/123']
    
    >>> import shlex
    >>> list(shlex.shlex(line))
    ['SOMETHING', ':', '!', 'abc', '@', '123']
    

    The following is an example, as I do not know exactly what you are looking for.

    >>> import re
    >>> result = re.match(r'([A-Z]*): !([a-z]*) @([0-9]*) #([a-z0-9/]*)', line)
    >>> result.groups()
    ('SOMETHING', 'abc', '123', 'xyz/123')
    

SQL "SELECT IN (Value1, Value2...)" with passing variable of values into GridView

Hi there, I have a strange encounter when creating a GridView using "SELECT..WHERE.. IN (value1, val2...)".

in the "Configure datasource" tab, if i hard code the values "SELECT ....WHERE field1 in ('AAA', 'BBB', 'CCC'), the system works well.

However, if I define a new parameter and pass in a concatenated string of values using a variable; be it a @session, Control or querystring; e.g. "SELECT .... WHERE field1 in @SESSION" the result is always empty.

I did another experiment by reducing the parameter content to only one single value, it works well.

in short, if I hardcode a string of values, it works, if I pass a variable with single value only, it works, but if i pass a varialbe with two values; it failed.

Pls advise if I have make any mistake or it is a known bug.

BR SDIGI

From stackoverflow
  • Take a look at the answer to this question (which is very similar to yours)

    http://stackoverflow.com/questions/337704/parameterizing-a-sql-in-clause

    Which ultimately links (via a convoluted route) to this definitive answer:

    http://www.sommarskog.se/arrays-in-sql.html

  • If you go to using a stored procedure, you can use this method, which I discussed in regards to how to do it in SQL.

  • Thanks all.

    I tried "CancelSelectOnNullParameter" to False n problem persist.

    The fact is that I created only one parameter and I am not leaving the parameter to NULL value.

    When I pass in the single value "'AAA'", it works; but when I pass in the value "'AAA', 'BBB'", it fails. and if I hardcode the values "'AAA', 'BBB'" in the SELECT statement without passing via a variable, it works well too.

    For Andrew and Mitchel's article, we will try creating a new table to store the values.

    will keep you posted on the outcome.

    BR

    Timothy Khouri : Are you setting a single variable to "'AAA','BBB'" ? because that won't work at all. You would have to be building a dynamic SQL string or use one of the suggested answers below.
  • Thanks everyone who responded to help me. I appreciate :-)

    Timothy is sharp enough to spot my silly mistake! salute to you...

    Yes, once I change to dynamic SQL, it works.

    I also tried with Mitchel's suggestion, thanks.

    BR

Rhino Mocks - Setting up results for non-virtual methods

I'm playing around with Rhino Mocks and am trying to set some dummy results on my mocked objects so when they are called in my factory methods I don't have to worry about the data.

But I've hit a snag, the methods I want to have the dummy results for are causing exceptions because they aren't virtual.

I've got code like this:

using(mock.Record()){
  SetupResult.For(service.SomeMethod()).Return("hello world");
}

Does the SomeMethod method have to be a virtual to be have a mocked result?

Also, what's the difference between SetupResult.For and Expect.Call?

From stackoverflow
  • Rhino Mocks uses DynamicProxy2 to do it's magic, so you will not be able to set up expectations/results on non-virtual methods.

    As for the difference between SetupResult.For, and Expect.Call if you want your test to fail validation if a method is not called, use Expect.Call. If you just want to provide a result from your mock object, and you don't want to fail verification if it is not called, use SetupResult.For

    So the following will fail:

    using(mock.Record()){
        Expect.Call(service.SomeMethod()).Return("you have to run me");
    }
    
    using(mock.Replay()){
        // Some code that never calls service.SomeMethod()
    }
    

    And this test will not:

    using(mock.Record()){
        SetupResult.For(service.SomeMethod()).Return("you don't have to run me");
    }
    
    using(mock.Replay()) {
        // Some code that never calls service.SomeMethod()
    }
    

    Does that make sense?

    Slace : Thanks, that explains it well. I was compairing Typemock and Rhino Mocks when I found this. Typemock can mock non-virtuals so it's a plus in my book so far.
  • typemock isolator can do this: Typemock.com

    Slace : I know, but it's not free ;). But I do own a copy

create java console inside the panel

How can I create an instance of the Java console inside of a panel?

From stackoverflow
  • Here's a functioning class - you'll have to replace my library function EzTimer with Thread.sleep() and try/catch the InterruptedException.

    You can install an instance of this into the system out and err using

    PrintStream con=new PrintStream(new TextAreaOutputStream(...));
    System.setOut(con);
    System.setErr(con);
    

    Here's the class

    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    
    public class TextAreaOutputStream
    extends OutputStream
    {
    
    // *****************************************************************************
    // INSTANCE PROPERTIES
    // *****************************************************************************
    
    private JTextArea                       textArea;                               // target text area
    private int                             maxLines;                               // maximum lines allowed in text area
    private LinkedList                      lineLengths;                            // length of lines within text area
    private int                             curLength;                              // length of current line
    private byte[]                          oneByte;                                // array for write(int val);
    
    // *****************************************************************************
    // INSTANCE CONSTRUCTORS/INIT/CLOSE/FINALIZE
    // *****************************************************************************
    
    public TextAreaOutputStream(JTextArea ta) {
        this(ta,1000);
        }
    
    public TextAreaOutputStream(JTextArea ta, int ml) {
        if(ml<1) { throw new IoEscape(IoEscape.GENERAL,"Maximum lines of "+ml+" in TextAreaOutputStream constructor is not permitted"); }
        textArea=ta;
        maxLines=ml;
        lineLengths=new LinkedList();
        curLength=0;
        oneByte=new byte[1];
        }
    
    // *****************************************************************************
    // INSTANCE METHODS - ACCESSORS
    // *****************************************************************************
    
    public synchronized void clear() {
        lineLengths=new LinkedList();
        curLength=0;
        textArea.setText("");
        }
    
    /** Get the number of lines this TextArea will hold. */
    public synchronized int getMaximumLines() { return maxLines; }
    
    /** Set the number of lines this TextArea will hold. */
    public synchronized void setMaximumLines(int val) { maxLines=val; }
    
    // *****************************************************************************
    // INSTANCE METHODS
    // *****************************************************************************
    
    public void close() {
        if(textArea!=null) {
            textArea=null;
            lineLengths=null;
            oneByte=null;
            }
        }
    
    public void flush() {
        }
    
    public void write(int val) {
        oneByte[0]=(byte)val;
        write(oneByte,0,1);
        }
    
    public void write(byte[] ba) {
        write(ba,0,ba.length);
        }
    
    public synchronized void write(byte[] ba,int str,int len) {
        try {
            curLength+=len;
            if(bytesEndWith(ba,str,len,LINE_SEP)) {
                lineLengths.addLast(new Integer(curLength));
                curLength=0;
                if(lineLengths.size()>maxLines) {
                    textArea.replaceRange(null,0,((Integer)lineLengths.removeFirst()).intValue());
                    }
                }
            for(int xa=0; xa<10; xa++) {
                try { textArea.append(new String(ba,str,len)); break; }
                catch(Throwable thr) {                                                 // sometimes throws a java.lang.Error: Interrupted attempt to aquire write lock
                    if(xa==9) { thr.printStackTrace(); }
                    else      { EzTimer.delay(200);    }
                    }
                }
            }
        catch(Throwable thr) {
            CharArrayWriter caw=new CharArrayWriter();
            thr.printStackTrace(new PrintWriter(caw,true));
            textArea.append(System.getProperty("line.separator","\n"));
            textArea.append(caw.toString());
            }
        }
    
    private boolean bytesEndWith(byte[] ba, int str, int len, byte[] ew) {
        if(len<LINE_SEP.length) { return false; }
        for(int xa=0,xb=(str+len-LINE_SEP.length); xa<LINE_SEP.length; xa++,xb++) {
            if(LINE_SEP[xa]!=ba[xb]) { return false; }
            }
        return true;
        }
    
    // *****************************************************************************
    // STATIC PROPERTIES
    // *****************************************************************************
    
    static private byte[]                   LINE_SEP=System.getProperty("line.separator","\n").getBytes();
    
    } /* END PUBLIC CLASS */
    
    OscarRyz : Look interesting. Do you have an screenshot?
    Software Monkey : Not much to see... it's a console window! But I see someone has already posted their test program with a pic in another answer.
    OscarRyz : It was me! :) , I couldn't resists.
  • @Sofware Monkey:

    It works!! :)

    alt text

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    
    public class Main{
        public static void main( String [] args ) throws InterruptedException  {
            JFrame frame = new JFrame();
            frame.add( new JLabel(" Outout" ), BorderLayout.NORTH );
    
            JTextArea ta = new JTextArea();
            TextAreaOutputStream taos = new TextAreaOutputStream( ta, 60 );
            PrintStream ps = new PrintStream( taos );
            System.setOut( ps );
            System.setErr( ps );
    
    
            frame.add( new JScrollPane( ta )  );
    
            frame.pack();
            frame.setVisible( true );
    
            for( int i = 0 ; i < 100 ; i++ ) {
                System.out.println( i );
                Thread.sleep( 500 );
            }
        }
    }
    
    furtelwart : Please upvote his answer if it works.
    OscarRyz : If helps for anything. I've mark this as community wiki. At least I won't get points for something I didn't program.
  • what is Ioscape