Archive for the 'Tech Stuff' Category

Windows can be programmatically shutdown using the ExitWindowsEx() Win32 function.  However it turns out that the trick to getting it to work is to first grant shutdown priviliges to the calling process via some rather ugly security functions - this type of faffing around can never me remembered so I will post some sample code here in the hopes that it might help me (in the future) or maybe someone else:

bool ShutdownPC(const bool reboot) {   HANDLE hToken = NULL;   if(!OpenProcessToken(GetCurrentProcess(),                        TOKEN_ADJUST_PRIVILEGES |                        TOKEN_QUERY, &hToken))   {     cerr << "OpenProcessToken() " << GetLastError();     return false;   }   TOKEN_PRIVILEGES tkp;   if (!LookupPrivilegeValue(NULL,                             SE_SHUTDOWN_NAME,                             &tkp.Privileges[0].Luid))   {     cerr << "LookupPrivilegeValue() " << GetLastError();     return false;   }   tkp.PrivilegeCount = 1;   tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;   if(!AdjustTokenPrivileges(hToken, false,                          &tkp, 0, NULL, NULL))   {     cerr << "AdjustTokenPrivileges() " << GetLastError();     return false;   }   // And shutdown… with force!   bool ret = ExitWindowsEx((reboot ? EWX_REBOOT : EWX_SHUTDOWN)                            | EWX_FORCE | EWX_FORCEIFHUNG,                            SHTDN_REASON_MAJOR_APPLICATION |                            SHTDN_REASON_MINOR_MAINTENANCE) == TRUE;   if (!ret)   {     cerr << "ExitWindowsEx() " << GetLastError();   }   return ret; }

Some time ago (!) I wrote about an investigation that I had carried out into how a literal value could be mapped to and stored as a lambda expression/delegate in C#.  This was important for me at the time because I needed to find some way to have a ‘value’ and a ‘value rule’ appear the same to callers.  I wanted to define a type whose value when queried could either come from the evaluation of a previously specified ‘rule’ or could simply be retrieved from a real, previously stored value - without the caller knowing the difference at all.

 

This type of concept is common in functional and logic programming languages - in these languages the separation between functionality (code) and data is very blurry, what is data one minute can become code the next, and visa verse.  It is harder to achieve (at a high level) in procedural languages but the addition of lambda expressions in .NET 3.0 brings us a a lot closer (in .NET 3.0)!

 

The following might help to demonstrate how such a type might work, imagine a generic class called DualProp whose job is to yield a typed value when requested, this value could have been previously stored as a real value or could be obtaind by evaluating a previously specified lambda expression:

 

// Create an integer property     var speed = new DualProp();     // set it to 3     speed = 3;     // Create an bool property, whose value depends     // on the speed’s value.     var visible = new DualProp();     // visible only true if speed &gt; 5     visible.Lambda = () =&gt; speed &gt; 5;     // Check visible’s value ( this results in the     // stored delegated being evaluated)     if (visible == true)         Console.WriteLine("It is visible");     else         Console.WriteLine("It is invisible");     // Set speed to 8, sould now be visible     speed = 8;     // Try again, it should be visible now     if (visible == true)         Console.WriteLine("It is visible");     else         Console.WriteLine("It is invisible");     // now just set visible’s value to false     visible = false;     // And check it’s value again, should be invisible     if (visible == true)         Console.WriteLine("It is visible");     else         Console.WriteLine("It is invisible");

 

Two properties are defined, an integer property called ’speed’ and a bool property called ‘visible’.  Visible’s value depends on the evaluation of the delegate compiled from the lambda expression that was assigned to it:

visible.Lambda = () =&gt; speed &gt; 5;

So when queried, visible’s value is ‘true’ if speed’s current value is greater than 5.

This scheme should allow us to build up whole sets of properties some of whose values are real and others whose are dynamically computed based on the values of others.  The values on which the lambda expressions depend can themselves be real or computed.

 

This type of set-up could be very handy, especially when used as part of a data driven user interface.  A data driven user interface is typically laid out and behaves in accordance with some specified meta-data, this meta-data is usually static (no meta-rules, just meta-data!).  Employing a scheme such as this should allow us to specify meta-data which can be dynamic, in that some of the meta-data can dynamically change based on applying ‘rules’ to some of the real data.

 

Imagine a CAD/CAM system for a laser drilling machine, it will have various logical tools defined that represent the different laser cutting tools onm the laser cutting machine. The laser tool’s various parameters can be viewed and changed on the CAD/CAM interface via a data driven property-page type interface. As usual the meta-data for this interface will specify a list of parameters along with some other data like:

 

  • Name - Attribute’s Name
  • Type - Attribute’s Type (Number/Boolean/String etc.)
  • Visibility - Is this Attribute visible for editing
  • ReadOnly - Can the attribute’s value be changed?
  • Min - Attribute’s Minimum allowed value
  • Max - Attribute’s Maximum allowed value
  • HelpString - Some help text for the attribute

 

Rule based properties should allow us to do things like set the min & max values based on another parameter’s value or force a parameter to be read-only based on the value of yet another parameter (by specifying a rule for the visibility attribute).  Anyway, I hope to expand on this in a future post.

 

Meanwhile, Here is the code for the DualProp class:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; // (c) 2009 Kevin Godden, Ridge Solutions. public class DualProp {     // The property’s delegate, which will     // be evaluated whenever the property’s value     // is queried.     private Func _lambda = null;     // Map the passed value (of type T) to a lambda and     // then compile to a delegate.     private Func ToLambda(T val)     {         var body = Expression.Constant(val);         var exp = Expression.Lambda&gt;(body, null);         return (Func)exp.Compile();     }     // Given a value of type T, convert it     // to a corresponding lambda delegate     // and store it.     private void SetValue(T val)     {         _lambda = ToLambda(val);     }     // Set for _lambda, used when we want     // to specify a property ‘rule’ rather     // than a literal value.     public Func Lambda     {         set { _lambda = value; }     }     // Constructors     public DualProp()     {     }     // Construct with value     public DualProp(T val)     {         SetValue(val);     }     // Construct with a ‘rule’ (lambda/delegate)     public DualProp(Func lambda)     {         _lambda = lambda;     }     // Allows us to assign a value directly to     // a DualProp i.e. –&gt;     // DualProp dualProperty = new DualProp();     // dualProperty = 10;     public static implicit operator DualProp(T val)     {         return new DualProp(val);     }     // Allows us to query a DualProp’s value directly     // i.e. –&gt;     // DualProp dualProperty = new DualProp(10);     // int value = dualProp;     public static implicit operator T(DualProp sp)     {         return sp._lambda();     } }

In drupal there are many ways to go about putting together teasers for custom content types created with the Content Creation Kit (CCK). The quickest to get up and running with is often to use the Content Templates (Contemplate) module, this allows you to specify in-line markup and PHP with code to get at and display the node’s data fields - formatted just as you require.

 

Often when putting together a teaser you may want to neatly truncate some long text to a summary and append ‘…’ or the like to the end - well there’s a great little PHP function which does just this called neat_trim() it is provided by Justin Cook and does the job  nicely!

 

One thing to note however is that HTML mark-up as well as newlines and carriage-returns in the input string can confuse this function.  To get around this problem you can arrange to remove the offending material either by modifying the function or by stripping it out of the input string before calling the function.  Use can use strip_tags() to remove HTML mark-up.

Q: How can I pass an argument to a ‘block view’ in Drupal 6?

A: There is no way to pass an argument to a block view in Drupal 6, but don’t panic as there is a way to achieve the same result through some slight-of-hand.

The use of arguments with Drupal views are vital for getting the most out of the views functionality. How are the arguments normal passed to a view?  Well, if a view is configured to produce a page then the arguments are easily passed as part of the requesting URL,  while if a view is embedded using code, then the arguments are passed in as part of the call to embed the view.  But if a view is configured to produce a block, how do you pass arguments to it?  The bad news is you can’t - the good news is that there is a way fake it and achieve the same result.

The trick involves providing a PHP handler within the view which will be called when the view is invoked without an expected argument (this is what happens when the block is displayed!).  We just arrange for this handler to retrieve and return the argument’s value and then the view will behave as required - just as if the argument had been passed to it in the first place.

To do this create the block view as normal and configure the required argument(s).  For each argument we choose the ‘Provide default argument’ option, and select the ‘PHP code’ sub-option.  We then provide some PHP code which will ‘get’ and return the argument’s value, it doesn’t really matter where or how the PHP code gets the argument once it returns the correct value.   Have a look at screen shot below:

Adding a default parameter

The example above is a bit simplistic as the PHP code just returns a static value - not very useful at all!  A more realistic or useful example  (inspired by one of the posts referenced below) would be to return the argument that was passed to the page that contains and displays the block.  Consider the mythical paths:

www.somedomain.com/content/projects/web-design

and

www.somedomain.com/content/projects/illustration

Here things are set-up so that ‘web-design’ and ‘illustration’ are arguments to the ‘projects’ page, they result in only the projects of that type being displayed.   Assuming we are using the pathauto module for nice clean URLs (as we almost always are!) then the following PHP code when provided as the default argument handler will get the URL, parse it and return the argument part to the view.

$path = drupal_get_path_alias($_GET["q"]); //get URL alias $path = explode("/", $path); //break path into an array if ($path[0] == "projects" &amp;&amp; $path[1] != "") {   return $path[1]; }

So there is is, it’s definitely not the easiest method in the world but at least it does provide a mechanism of getting those arguments to the view…

Sources: http://drupalsn.com/learn-drupal/drupal-questions/question-2650, http://drupal.org/node/332521

For setting up a Drupal maintenance cron job on the blacknight.ie unix hosting plan, I have found that the following command works well:

 

/usr/bin/wget -O - -q -t 1 http://www.yourdomain.com/cron.php

 

Original Source: http://drupal.org/cron

We are using good old Drupal and its Content Construction Kit (CCK) once again to create a custom CMS for our client. One of the things that usually completely mystifies me time and time again is how to customise a new content type’s add/edit form layout.  So, lest I forget again in the future, here’s a link to a good article on the subject:

 

http://drupal.org/node/101092

Today I came across a situation which brought it home to me again how (in my opinion) C++ could desperately do with native lambda function support.  The standard library has introduced a load of great algorithms, but providing predicates and the like to them is a real pain - and I think that because of this people tend to stick to hand rolling good old-fashioned loops.

 

Consider replacing a few different characters in a std::string with a single given character, e.g., replace the characters ‘$’ and ‘|’ with ‘_’.  A good way of doing this in C++ would be to use the boost regular expression library, but we could also use the std::replace_if() algorithm.  All we have to do to use this algorithm is to privide a predicate that indicates if a given character should be replaced or not (say called is_bad_char()), then we do something like:

 

replace_if(str.begin(), str.end(), is_bad_char(), ‘_’);

 Looks easy enough, and it’s nice and concise.  All we have to do now is define is_bad_char(), something like:

struct is_bad_char: public std::unary_function {   bool operator() (const char& c) const   {     return !(c == ‘$’ || c == ‘|’);   } };

I mean! what a pallava!  that’s quite a mouthful, would you really be bothered? You would have a loop coded in just the time it took to start to remember that syntax, never mind the typing. it also looks terribly inelegant.

 

Now when native lambda support arrvies we will be able to do something like this instead:

replace_if(str.begin(), str.end(),        <>(char c) -> bool { return !(c == ‘$’ || c == ‘|’); },        ‘_’);

That’s much better… but not available yet, we will just have to wait for c++0x to arrive. In the mean time I will just have to use lambdas in the many other languages that support them and pine when using C++.

December 18, 2008

I have recently been doing some fairly intensive merging and difference checking with Tortoise SVN and subversion and once again find myself thanking my luck stars that Winmerge is installed on my (windows) system just waiting to lend a helping hand!

 

For those who haven’t come across it Winmerge is an open source tool for visually checking file differences, it allows you to move individual changes or differences from one file to the other.  I have found it to be one of the best such tools and it’s free!  It also does a good job of comparing a whole directory tree of files.

 

Tortoise SVN can be configured to use Winmerge when showing differences etc. rather than its default difference visualiser, I find that this makes tortoise much more effective.  Instructions for configuring Winmerge as the default diff viewer can be found in the Tortoise help pages, but to summarise:

 

Right-Click on a folder in explorer, choose the ‘Tortoise SVN’ sub menu and then choose the ‘Settings’ menu option.  Click on the ‘Dif Viewer’ pane, select ‘External’  and  enter the following into the text-box below:

 

C:\Program Files\WinMerge\WinMergeU.exe -e -x -ub -dl %bname -dr %yname %base %mine

 

[the path entered will depend on where you installed Winmerge, for the real low-down on configuring this you had better check the documentation!]

 

Anyway, to sum up, if you find yourself struggling with comparing files or merging changes with subversion then I have found that Winmerge can be of great help, I can’t imagine doing without it anymore!

Our client’s brief was to display their latest blog post on their main web page in a truncated form, their main web page is not part or their blog.  After a little searching I came across a wordpress plugin called Get-a-Post which seemed to promise just what we required.

 

It will retrieve a post, and sets the post’s data up correctly so that wordpress functions like the_title() and the_content() which must normally be called from within the wordpress loop can be called by php code that is outside of the wordpress loop, this is important to us as we want to display the data on a web page which is not part of the actual wordpress blog - from a ‘random’ page.

 

To install the plugin, just download it, and copy get-a-post.php to the blog’s wp-content/plugins/ directory.  Then goto the wordpress admin/plugins screen and activate it.

 

Once the plugin has been activated, its function get_a_post() can be called from any php script, if called with no parameters the latest post will be made active - perfect!  Before calling it make sure to include/require ‘wp-config.php’.  Here is an example script that gets the latest post’s title and content and packages it up into a div and some spans:

 

<?php require_once(”./wp-config.php”); ?>

<?php get_a_post(); ?>
<div class=”last_post_div”>
<span class=”last_post_title”><?php the_title()?></span> - <span class=”last_post_content”>
<?php echo get_the_content(); ?>
</span>
</div>

The wordpress php function get_the_content(), when called from within the wordpress ‘loop’ will usually return the current post’s content - ‘very handy’ I hear you cry!  Indeed, but all is not as simple as it may seem.  If there is a <!–More–> block in the post it will not return the full text but instead will return some of the text with a link like ‘read more…’ inserted (what is displayed can be controled by an argument to the function). This is fine _unless_ you actually want to get the post’s full contents!!

 

Finding the answer to this seemingly simple question nearly drove me mad, but I eventually found a solution, there is a global flag called $more, setting this to 1 before calling get_the_content() or the_content() etc. will result in the <!–more–> blocks not being processed and all of the post’s text will be returned!

 

global $more;
$more = 1;
$content = get_the_content();