Posted 2 weeks ago

The Reverse Association Between Anaconda Willingness and Present Buns

So, you’ve probably wondered regularly how you can concisely explain the inner workings of your anaconda to your significant other. Well, fear not as I have the optimal solution for you.

The Monkey Patch

Your definitions are pretty clear, but you just want to add a specific getter for your personal situation.

class Me < Man
  def anaconda
    return nil unless Hon::buns
    super
  end
end

This assumes that you have a single namespace for your significant other. If you find yourself trying to explain this to multiple targets, you might need to define this as “anaconda_for hon” and pass in an instance of the currently addressed Hon.

The Multi-Skilled Anaconda

You have a pocket snake that can do more than just binarily exist or not? Maybe you’ve even created a one-to-one association between it and yourself and want to write this definition directly on the appropriate class?

class Anaconda
  belongs_to :man

  def wants?
    Hon::buns ? true : false
  end
end

Maybe Hon has a boolean #buns? function, in which case you could just delegate. Could also be refactored to:

!!Hon::buns

The One-Liner

Need a more concise script? Maybe you just need to set the current state of your Anaconda?

@anaconda = nil unless Hon.buns

Posted 7 months ago
#Social #Startup #nackt. #Fairnopoly - konsequent #transparent. http://thndr.it/1fcwehg

#Social #Startup #nackt. #Fairnopoly - konsequent #transparent. http://thndr.it/1fcwehg

Posted 1 year ago

Using Appcelerator Titanium with Vim commands

You might belong to the majority of people who can only wonder why, oh WHY, some #?@! nutheads decide to use vi. Or you might already be converted and try to find ways to use similar commands in all kinds of different places. Did you know you can even control firefox with vi-like commands?


Well, I recently got into programming iOS/Android apps with Titanium. It’s a really neat IDE. Based on Eclipse … so how bad can it be right? Not bad at all. If only getting around the code wasn’t so tedious (at least when compared to good old vi editing).


Well, there’s a pretty simple way to get your precious Escape-key back. The answer is called Vrapper.

Here’s what you do:

1. Start up Titanium

2. In the menu bar go to “Help” -> “Install new Software…”

3. After the “Work with:” field click on “Add…”

4. For the location enter: http://vrapper.sourceforge.net/update-site/stable

5. Click OK. Make sure your new addition is selected in the “Work with:” field.

6. Wait a moment for Titanium to pull the data.

7. Select Vrapper as soon as it shows up in the field below.

8+ The rest is basically just accepting to the terms and clicking “Next” a few times. Restart Titanium, open a file, hit Esc and breathe a deep breath of victory.

It’s not actually vim, just edited Eclipse commands and navigation to feel like vim. Still, good enough for me.

Enjoy!

PS: Wanna get started with vim? When you have it installed, open a console, type ‘vimtutor’, and practice, practice, practice.

Posted 2 years ago
Okay, I tried implementing the mathcaptcha component with Cakephp 2.0 and received an illegal offset error message. I narrowed down the problem to the component inclusion in the controller public $components = array('MathCaptcha', array('timer' => 3)). When I removed the timer array, the problem went away. Is there another way to include the timer without causing this error to occur?
eldorado2768 asked

Could this be related to this issue?

Otherwise it’s hard to answer you without knowing your exact code. If you really did nothing else in regards to the component I unfortunately can’t reproduce your error.

Posted 2 years ago

CakePHP 2 - Sessions are not persisting between actions/controllers

When migrating a project from 1.3 to 2.0 I just had the strangest problem: Suddenly sessions would be deleted the instant a redirect or page switch would happen.

Looking around on the internet the most common solution suggestion was to check the rights of the tmp folder, clearing the tmp folder, checking Session settings in the config .. but none of that helped me.

Well, long story short: It turns out that in 2.0 you can’t call $this->Session->destroy(); right before another $this->Session->write(…);

This was done in the project to clear out residual session variables. Destroy should start a fresh session, but it turns out it’s not that quick. Using $this->Session->delete(…);instead it works again.

Yes, I am aware that you would actually use the AuthComponent for most of that stuff. But that’s for later to implement.

Hope that helped someone out there.

Posted 2 years ago

CakePHP - Generating Unique Slugs

This is about a code snippet I use in a project to generate a unique string that is

  • search engine optimized
  • url-safe
  • readable by humans

Those are generally called “slugs” and used to get urls for posts by their title.

The original code was published by Harmen Janssen a few years ago on his blog and Harmen, I hope you read this through a trackback or so. I would just have written this in your comments but you disabled them.

Anyway, this is the original code:

<?php
class AppModel extends Model {
function createSlug ($string, $id=null) {
$slug = Inflector::slug ($string,'-');
$slug = low ($slug);
$i = 0;
$params = array ();
$params ['conditions']= array();
$params ['conditions'][$this->name.'.slug']= $slug;
if (!is_null($id)) {
$params ['conditions']['not'] = array($this->name.'.id'=>$id);
}
while (count($this->find ('all',$params))) {
if (!preg_match ('/-{1}[0-9]+$/', $slug )) {
$slug .= '-' . ++$i;
} else {
$slug = preg_replace ('/[0-9]+$/', ++$i, $slug );
}
$params ['conditions'][$this->name . '.slug']= $slug;
}
return $slug;
}
}
?>

However, there is a problem with it. It sucks. Sorry :-)

My main beef with it:

  1. It has 2 regex calls where none is needed. Regexes are pure resource hogs and should be avoided wherever possible.
  2. No need to trouble the database by retrieving all the fields all of the time, you basically need one, sometimes two.
  3. low()? Never heard of it, if it was ever a function in cakePHP it’s not supported anymore. I’m gonna assume you meant strtolower().

Here my revised version:

private function createSlug($string, $id = null) {
    $slug = Inflector::slug($string, '-');
    $slug = strtolower($slug);

    $i = 0;
    $params = array(
      'conditions' => array($this->name.'.slug' => $slug),
      'fields' => array($this->name.'.id', $this->name.'.slug'));

    if (!is_null($id))
      $params['conditions']['not'] = array($this->name.'.id'=>$id);
   

    while (count($this->find('all', $params)))  {
      $i++;
      $params['conditions'][$this->name . '.slug'] = $slug."-".$i;
    }
    if ($i) $slug .= "-".$i;

    return $slug;
  }

Works in CakePHP 2 but should work in 1.3 and 1.2 as well. Have fun! And if you want a more detailed explanation of the underlying principles used in that code, check out Harmen’s blog.

Posted 2 years ago

List of Valid and Invalid Email Addresses

For my own and your reference when testing email regexes or other email validation processes, here a copy&paste list of test samples:

Thanks goes out to who published a major part of this list on the msdn blog, unfortunately it’s in a table there so you can’t just copy & paste them. That’s why I’m saving this here. If you want to know why those emails are valid or invalid, check out his post.

Stranger valid and invalid email addresses where copied directly from Wikipedia.

List of Valid Email Addresses

email@example.com
firstname.lastname@example.com
email@subdomain.example.com
firstname+lastname@example.com
email@123.123.123.123
email@[123.123.123.123]
"email"@example.com
1234567890@example.com
email@example-one.com
_______@example.com
email@example.name
email@example.museum
email@example.co.jp
firstname-lastname@example.com

List of Strange Valid Email Addresses

much.”more\ unusual”@example.com
very.unusual.”@”.unusual.com@example.com
very.”(),:;<>[]”.VERY.”very@\\ "very”.unusual@strange.example.com

List of Invalid Email Addresses

plainaddress
#@%^%#$@#$@#.com
@example.com
Joe Smith <email@example.com>
email.example.com
email@example@example.com
.email@example.com
email.@example.com
email..email@example.com
あいうえお@example.com
email@example.com (Joe Smith)
email@example
email@-example.com
email@example.web
email@111.222.333.44444
email@example..com
Abc..123@example.com

List of Strange Invalid Email Addresses

”(),:;<>[\]@example.com
just”not”right@example.com
this\ is"really"not\allowed@example.com

And there you have it.

Finally for your pleasure here a php code snippet to test your regex against. Feel free to just copy the array where I have already put in the escaping backslashes and build your own tests around it.

$emails = array(
    'email@example.com',
    'firstname.lastname@example.com',
    'email@subdomain.example.com',
    'firstname+lastname@example.com',
    'email@123.123.123.123',
    'email@[123.123.123.123]',
    '"email"@example.com',
    '1234567890@example.com',
    'email@example-one.com',
    '_______@example.com',
    'email@example.name',
    'email@example.museum',
    'email@example.co.jp',
    'firstname-lastname@example.com',

    'much."more\ unusual"@example.com',
    'very.unusual."@".unusual.com@example.com',
    'very."(),:;<>[]".VERY."very@\\\\\\ \"very".unusual@strange.example.com',


    'plainaddress',
    '#@%^%#$@#$@#.com',
    '@example.com',
    'Joe Smith <email@example.com>',
    'email.example.com',
    'email@example@example.com',
    '.email@example.com',
    'email.@example.com',
    'email..email@example.com',
    'あいうえお@example.com',
    'email@example.com (Joe Smith)',
    'email@example',
    'email@-example.com',
    'email@example.web',
    'email@111.222.333.44444',
    'email@example..com',
    'Abc..123@example.com',

    '"(),:;<>[\]@example.com',
    'just"not"right@example.com',
    'this\ is\"really\"not\\\\allowed@example.com'
);

foreach ($emails as $email) {
    if (preg_match("/YOURREGEX/", $email))
        echo "<div style='color:green'>".$email." is valid.</div>";
    else
        echo "<div style='color:red'>".$email." is invalid.</div>";
}

PS: Yes, email addresses are a pain in the behind to validate. Wanna see the perfect regex for email addresses? Here it is.

Wanna see the second best email regex? Here you go: /^.+@.+\..+$/
It basically says “There is an at-sign, a period, stuff before/after/between them, and no line breaks.” Of course that’s just my personal opinion.

If someone wants to spam your form, they will do so regardless of your precious regex. president@whitehouse.gov - There you go. And really, how often have you mistyped your email address and a form validation helped you see it? I know I never have.

But that list is good for other stuff as well. Right now I’m generating default usernames from the emails people put in. That’s why I made that list to begin with. Anyway, I’m off!

Posted 2 years ago

CakePHP - disable SecurityComponent for a single action

It took me surprisingly long to figure this out and in the end the solution was so simple that I’m almost embarrassed to post this here.

Well, mainly it took me so long because I banged my head against the wall when neither

$this->Security->checkCSRF = false;

nor

$this->Security->validatePost = false;

stopped the component from black-holing my call from an external API (called by a Flash AS3 swf) every freaking time, not even when those where set in the AppController’s beforeFilter.

Well, in the end I simly disabled the component for that request and everything’s fine.

Following code applies to CakePHP 2:

// in Controller’s beforeFilter
if(‘actionname’ == $this->request->params[‘action’])
      $this->Components->disable(‘Security’);

Please tell me I’m not the only dumb fudge who couldn’t think of this right away

Posted 2 years ago

CakePHP 2 - Link Helper, give Html->Link classes based on their relation to the currently opened page

It’s surprising that this isn’t something already buildt into CakePHP from the get go: The ability to create links but have them markers for CSS styling based on their relation to the currently opened page.

But it apparently isnt, so here is a nice little helper for this. Just use $this->Link->link(…); instead of $this->Html->link(…);

Nearly all the credit goes to Richard and the user Rajesh Sharma and Leimi who commented on Richard’s blog. I basically switched just a few lines around to make it CakePHP 2.0 compliant. I haven’t thoroughly tested it, as it is it works for what I’m doing at the moment. If I run into troubles and fix them, I’ll update the script on here.

<?php class LinkHelper extends AppHelper {
 
	var $helpers = array(
		"Html"
	);
 
	function link($title, $url = null, $htmlAttributes = array(), $confirmMessage = false, $escapeTitle = true) {
 
 
			// parse the current url into its components
			$here = $this->params->params);
 
			// parse the destination url into its components
			if (is_array($url)) {
 
				$destination = $url;
 
			}
			else {
 
				$destination = Router::parse($url);
 
			}
 
			if (!isset($destination['controller'])) {
 
				$destination['controller'] = $this->params['controller'];
 
			}
 
			$class = "";
 
			if ($here['controller'] == $destination['controller']) {
 
				// link is to another action within this controller
				$class .= " current_controller";
 
				if ($here['action'] == $destination['action']) {
 
					// link is to the current action in this controller
					$class .= " current_action";
 
					if(isset($here['pass']) && !empty($here['pass'])){
 
						$match = false;
 
						foreach($here['pass'] as $key => $val){
 
							if(isset($destination['pass'][$key]) && $destination['pass'][$key] == $val){
 
								$match = true;
 
							}else{
 
								$match = false;
								break;
							}
						}
 
						if($match){
 
							$class .= " active withallmatch";
						}
 
					}else{
 
						$class .= " active";
					}					
 
				}
 
				if (isset($htmlAttributes['class'])) {
 
					// we already have a class attribute, append our classes
					$htmlAttributes['class'] .= $class;
 
				}
				else {
 
					// class not set, add ours
					$htmlAttributes['class'] = trim($class);
 
				}
 
			}

  
               if ($here['action'] == $destination['action']) {
                    // link is to the current action in this controller
                   $class .= " current_action";
                   if ($here['action'] == 'view') {
                        if ($here['slug'] == $destination['slug']) {
                            $class .= " current_view"; 
                        }
                    }
                }
			// build the link
			$link = $this->Html->link($title, $url, $htmlAttributes, $confirmMessage);
 
			// return the link
			return $this->output($link);
 
		}
 
 
}
 
?>

Again, thanks Richard, Rajesh and Leimi and as always if you find any bugs, please report them in the comments.

Edit: There was indeed a bug that didn’t give all active links the active class. Now it should work.

Posted 2 years ago

Browser Addon: Markdown Viewer

MarkupViewer Icon

Download Page: https://addons.mozilla.org/en-US/firefox/addon/markdownviewer/

Fed up with only being able to see the finished markdown of my readmes AFTER I have uploaded it somewhere, I developed a firefox addon that lets me view converted markdown right in my browser. It took me the whole day … and a very helpful answer by canuckistani on stackoverflow.

A basic screenshot

Just click the widget icon on a .md or .markdown file and see it work it’s wonders. Careful though: Just use it on real markdown files. Anywhere else it will screw up the current website-view (it’s only enabled on markdown files but some pages on websites like github or google code pretend to be markdown files when they really aren’t).

If you find any bugs, please report them here.